1👍
What you usually do in django in a view to get the form data would be something like this.
form = testForm(request.POST)
if form.is_valid:
# form will now have the data in form.cleaned_data
...
else:
# Handle validation error
...
If you want to do some data formatting or validation yourself you can put this in the validation method in the form. Either for the entire form or for a form field. This is also a great way to make your code more DRY.
2👍
Like others have already mentioned, you need to make use of the form’s cleaned_data
dictionary attribute and the is_valid
method. So you can do something like this:
def getItems(self):
if not self.is_valid():
return [] # assuming you want to return an empty list here
return self.cleaned_data['list'].split(',')
The reason your method does not work is that the form fields are not your typical instance variables. Hope this helps!
- [Django]-Downgrade Website from Django 1.4 to Django 1.3
- [Django]-Why are Django signals removed without weak=False?
- [Django]-Extensions and libraries for Django
- [Django]-Django Compressor on a multi-server deployment
- [Django]-No Procfile and no package.json file found in Current Directory – See run-foreman.js
0👍
There are a couple of things you need to know here.
First is that generally in a Python class method you access the attributes through the ‘self’ object. So in theory your function should be:
def get_items(self):
return self.list.split(",")
However, in the case of a Django form, this won’t work. This is because a field doesn’t have a value of its own – the value is only attached to the field when it’s rendered, and is obtained in different ways depending on whether the value was applied through initial data or by passing in a data dictionary.
If you have validated the form (through form.is_valid()
), you can get the form via the cleaned_data
dictionary:
return self.cleaned_data['list']
However this will fail if list
has failed validation for any reason.
- [Django]-Get nested serialized data as one
- [Django]-Django crispy-forms – Custom button
- [Django]-Use Django Model class inheritance to create an audit log for a table
- [Django]-Quick question: how to set *.domainname.com url in django
- [Django]-Django not taking script name header from nginx
- [Django]-How to post to allauth signup form to fill in initial data?
- [Django]-Query on manyToMany field with related_name
- [Django]-Django ordered ManyToManyField in admin interface
- [Django]-Change unique=True to unique=False from my model field