Strip spaces from Django form - python

I am getting the form with through a post request:
form = ReportDataForm2(req.POST)
I am trying to strip spaces from all fields by:
for element in form:
form[element] = form[element].strip()
But this does not seem to do anything.
I also tried stripping at the point where I am receiving the data:
id = form.cleaned_data['id'].strip()
Not working either.
I am new to Django so don't know how forms are treated.

How about this:
You extend the CharField class, create your own Field, and use that anytime you want to have stripped field?
class StrippedCharField(CharField):
"""Newforms CharField that strips trailing and leading spaces."""
def clean(self, value):
if value is not None:
value = value.strip()
return super(StrippedCharField, self).clean(value)
There's been a long discussion on whether form data stripping should be handled by Django or not. The discussion was resurrected recently but the actual thread started about 7 years ago
I haven't tested the code above myself. The solution was pulled from this forum discussion

A good place to validate your form fields is the clean_<fieldname>() method. <fieldname> is the name of the field you want to validate. For example, if you want to validate a field called name, you will define a clean_name() method to validate it.
An elaborate example:
class MyForm(forms.Form):
text = forms.CharField(...)
...
def clean_text(self):
stripped_text = self.cleaned_data['text'].strip()
# do some other validation if you want...
return stripped_text
Apart from stripping, you can do all sorts of validation there.
See docs for more on validation.

Related

wtforms add value dynamically

I'm working on an app that uses WTForms in combination with an templating engine.
The forms that are being shown to the user are not pre defined, but can be dynamically configured by the admin. So the WTForm needs to be able to dynamically add fields, I have achieved this by specifying this subclass of Form (as suggested by):
class DynamicForm(Form):
#classmethod
def append_field(cls, name, field):
setattr(cls, name, field)
return cls
This works fine, but it seems that via this method you cannot populate the fields through Form(obj=values_here). This is my current instantiation of the Form subclass mentioned above:
values = {}
values['password'] = 'Password123'
form = DynamicForm(obj=values)
form.append_field("password", PasswordField('password'))
So this won't work, and this makes sense when you consider the field to be added after the Form's init has been called. So I have been searching for a way to also assign the value of a field dynamically, but I haven't had any luck so far.
Does anyone know of a way to set the password field in the example to a certain value? Would be greatly appreciated.
Try this:
>>> form = DynamicForm().append_field('password',
PasswordField('password'))(
password="Password123")
>>> form.data
{'password': 'Password123'}
The solution mentioned here by dkol works like a charm, but it does require you to actually know the name of the field (in other words, it can't be computed). This is because the named parameter's key which you're passing along in (password="Password123") can't be an expression, or an variable. Meaning that an for loop like this won't work:
form = DynamicForm()
for field in fields:
form = form.append_field(field.label, StringField(field.label))(field.label=field.value)
So after some fiddling around with the former solution provided by dkol, I came up with this:
form = DynamicForm()
class formReferenceObject:
pass
for field in fields:
form = form.append_field(field.label, StringField(field.label))
setattr(formReferenceObject, field.label, field.value)
form = form(obj=formReference)
This solution may require a bit more code, but is still really readable and is very flexible. So when using an for loop / an computed <input /> name, this will help you.

Django custom (multi)widget input validation

What is the correct method for validating input for a custom multiwidget in each of these cases:
if I want to implement a custom Field?
if I want to use an existing database field type (say DateField)?
The motivation for this comes from the following two questions:
How do I use django's multi-widget?
Django subclassing multiwidget
I am specifically interested in the fact that I feel I have cheated. I have used value_from_datadict() like so:
def value_from_datadict(self, data, files, name):
datelist = [widget.value_from_datadict(data, files, name + '_%s' % i) for i, widget in enumerate(self.widgets)]
try:
D = date(day=int(datelist[0]), month=int(datelist[1]), year=int(datelist[2]))
return str(D)
except ValueError:
return None
Which looks through the POST dictionary and constructs a value for my widget (see linked questions). However, at the same time I've tacked on some validation; namely if the creation of D as a date object fails, I'm returning None which will fail in the is_valid() check.
My third question therefore is should I be doing this some other way? For this case, I do not want a custom field.
Thanks.
You validate your form fields just like any other fields, implementing the clean_fieldname method in your form. If your validation logic spreads across many form fields (which is nto the same as many widgets!) you put it in your form's clean() method.
http://docs.djangoproject.com/en/1.2/ref/forms/validation/
According to the documentation, validation is the responsibility of the field behind the widget, not the widget itself. Widgets should do nothing but present the input for the user and pass input data back to the field.
So, if you want to validate data that's been submitted, you should write a validator.
This is especially important with MultiWidgets, as you can have more than one aspect of the data error out. Each aspect needs to be returned to the user for consideration, and the built in way to do that is to write validators and place them in the validators attribute of the field.
Contrary to the documentation, you don't have to do this per form. You can, instead, extend one of the built in forms and add an entry to default_validators.
One more note: If you're going to implement a MultiWidget, your form is going to pass some sort of 'compressed' data back to it to render. The docs say:
This method takes a single “compressed” value from the field and returns a list of “decompressed” values. The input value can be assumed valid, but not necessarily non-empty.
-Widgets
Just make sure you're handling that output correctly and you'll be fine.

django custom form validation

In Django/Python, when you make a custom form, does it need to have a clean() method, or will calling .is_valid() perform a default validation?
if request.method == 'POST':
filter = FilterForm(request.POST)
if filter.is_valid():
print 'Month is ' + filter.cleaned_data['month']
print 'Type is ' + filter.cleaned_data['type']
print 'Number is ' +filter.cleaned_data['number']
else:
print 'Invalid form'
print filter.errors
"Invalid Form" gets printed but no errors get printed.
class FilterForm(forms.Form):
months = [('January','January'),
('February','February'),
('March','March'),
('April','April'),
('May','May'),
('June','June'),
('July','July'),
('August','August'),
('September','September'),
('October','October'),
('November','November'),
('December','December'),]
types = [('text','Text'),
('call','Call'),]
month = forms.ChoiceField(months)
type = forms.ChoiceField(choices=types,widget=forms.CheckboxSelectMultiple)
def __init__(self,numbers,*args, **kwargs):
super(FilterForm,self).__init__(*args, **kwargs)
self.fields['number'] = forms.ChoiceField(choices=numbers)
def clean(self):
return self.cleaned_data
I've tried it with and without the clean method.
does it need to have a clean() method
No. Completely optional.
There's a big list of things that Django does in a specific order when it validates forms. You can learn about the process here:
http://docs.djangoproject.com/en/dev/ref/forms/validation/
As for finding your problem, if you stick a {{form.errors}} on your template, you'll see which field is blowing up. I have a feeling it could be that your choices is defined in a place that something can't get a handle on when it needs to (Move them out of the class).
Edit: Almost missed this. Look at this line:
def __init__(self,numbers,*args, **kwargs)
And then look at this line:
filter = FilterForm(request.POST)
You need to pass the numbers argument in this time too. It's a completely new instance. it can't validate because it doesn't know what numbers is.
If you have no specific clean method, Django will still validate all the fields in your form to ensure that all required fields are present, that they have the correct type where necessary, and that fields with choices have a value corresponding to one of the choices.
There are a couple of issues with this form that could be causing your problem. Firstly, you have overridden __init__ so that the first parameter after self is numbers. However, when you instantiate the form you don't pass this parameter - you just pass request.POST.
Secondly, it's a bad idea to add fields dynamically to self.fields as you do in __init__. Instead, declare your number field with an empty choices list and just set that in __init__:
self.fields['number'].choices = numbers

Django 1.1 FormWizard, Dynamically extend form

I am trying to create a multipage form, where the number of field elements on the second page is defined by the answers given on the first.
I have a formWizard set up and my understanding is that I need to use process_step() to alter the setup for the next page. I can either extend an existing form definition to add more elements, or merge 2 or more form definitions together to produce the correct number of form elements, but i have no idea how to do this.
Eg
Page 1 - Select interested subjects:
Page 2 - for each subject: ask relevant questions. Questions are defined as seperate forms in application, but need to be shown on one page, or merged into a single form.
Any help much appreiciated.
Spender
Spender,
At least at the moment I don't know a way of merging multiple forms onto one page in a FormWizard. In django 1.2 you will be able to include FormSets as steps in FormWizards (as per this ticket) but those only deal with multiple copies of identical forms, not compilations of many forms. But there is a way to do what you ask:
from django.contrib.formtools.wizard import FormWizard
from django import forms
class SubjectForm(forms.Form):
subjects = forms.MultipleChoiceField(choices = (('language', 'language'),
('sport','sport')))
class RelatedQForm(forms.Form):
"""Overload the __init__ operator to take a list of forms as the first input and generate the
fields that way."""
def __init__(self, interested_subjects, *args, **kwargs):
super(RelatedQForm, self).__init__(*args, **kwargs)
for sub in interested_subjects:
self.field[sub] = forms.CharField(label = "What do you think about %s" % subject)
class SubjectWizard(FormWizard):
def done(self, request, form_list):
process_form_list(form_list)
def process_step(self, request, form, step):
if step == 1:
chosen_subs = form.cleaned_data['subjects']
self.form_list[1] = RelatedQForm(chosen_subs)
With this code you instantiate your FormWizard as you normally would in the view and then let the wizard class take care of everything behind the scenes.
The general idea is to overload the init class of a "RelatedQForm" to dynamically alter the fields. This code snippet was taken from here. You can make the processing within the init operator as complex as you'd like, read "include the fields from your forms as if-elif blocks inside the for-loop" ... you could probably even figure out a way to strip the fields from your current forms programatically, I'd have to see them to figure it out though.
Your "process_form_list" function will need to loop over the fields using something like:
for field, val in form.cleaned_data.items():
do_stuff
Hope this gets you on your way :)
I don't think the
self.form_list[1] = RelatedQForm(chosen_subs)
part works. I always get the error message:
object is not callable
It seems to be like form_list only accepts RelatedQForm (the name of the form), not an instance of it.

Django Form Preview - How to work with 'cleaned_data'

Thanks to Insin for answering a previous question related to this one.
His answer worked and works well, however, I'm perplexed at the provision of 'cleaned_data', or more precisely, how to use it?
class RegistrationFormPreview(FormPreview):
preview_template = 'workshops/workshop_register_preview.html'
form_template = 'workshops/workshop_register_form.html'
def done(self, request, cleaned_data):
# Do something with the cleaned_data, then redirect
# to a "success" page.
registration = Registration(cleaned_data)
registration.user = request.user
registration.save()
# an attempt to work with cleaned_data throws the error: TypeError
# int() argument must be a string or a number, not 'dict'
# obviously the fk are python objects(?) and not fk_id
# but how to proceed here in an easy way?
# the following works fine, however, it seems to be double handling the POST data
# which had already been processed in the django.formtools.preview.post_post
# method, and passed through to this 'done' method, which is designed to
# be overidden.
'''
form = self.form(request.POST) # instansiate the form with POST data
registration = form.save(commit=False) # save before adding the user
registration.user = request.user # add the user
registration.save() # and save.
'''
return HttpResponseRedirect('/register/success')
For quick reference, here's the contents of the post_post method:
def post_post(self, request):
"Validates the POST data. If valid, calls done(). Else, redisplays form."
f = self.form(request.POST, auto_id=AUTO_ID)
if f.is_valid():
if self.security_hash(request, f) != request.POST.get(self.unused_name('hash')):
return self.failed_hash(request) # Security hash failed.
return self.done(request, f.cleaned_data)
else:
return render_to_response(self.form_template,
{'form': f, 'stage_field': self.unused_name('stage'), 'state': self.state},
context_instance=RequestContext(request))
I've never tried what you're doing here with a ModelForm before, but you might be able to use the ** operator to expand your cleaned_data dictionary into the keyword arguments expected for your Registration constructor:
registration = Registration (**cleaned_data)
The constructor to your model classes take keyword arguments that Django's Model meta class converts to instance-level attributes on the resulting object. The ** operator is a calling convention that tells Python to expand your dictionary into those keyword arguments.
In other words...
What you're doing currently is tantamount to this:
registration = Registration ({'key':'value', ...})
Which is not what you want because the constructor expects keyword arguments as opposed to a dictionary that contains your keyword arguments.
What you want to be doing is this
registration = Registration (key='value', ...)
Which is analogous to this:
registration = Registration (**{'key':'value', ...})
Again, I've never tried it, but it seems like it would work as long as you aren't doing anything fancy with your form, such as adding new attributes to it that aren't expected by your Registration constructor. In that case you'd likely have to modify the items in the cleaned_data dictionary prior to doing this.
It does seem like you're losing out on some of the functionality inherent in ModelForms by going through the form preview utility, though. Perhaps you should take your use case to the Django mailing list and see if there's a potential enhancement to this API that could make it work better with ModelForms.
Edit
Short of what I've described above, you can always just extract the fields from your cleaned_data dictionary "by hand" and pass those into your Registration constructor too, but with the caveat that you have to remember to update this code as you add new fields to your model.
registration = Registration (
x=cleaned_data['x'],
y=cleaned_data['y'],
z=cleaned_data['z'],
...
)

Categories