Help with validation in Models and Forms - python

I have a few questions about validation in Models and Forms. Could you help me out with these:
Where should validation be done? Should it be in the Model or the Form? Is the right way to go about this is to have validators in the form and constraints in the mode?
What is the difference between writing a 'clean_' method in the form and writing a validator? I've seen that people often put validation checks in the 'clean_' method.
In the request that I'm handling, I have a param in the URL string called 'alive'. This is generally 1 or 0. What would be the correct way of defining this in my form? I need to validate it is a number and can only be 1 or 0. Is this the right way?
alive = models.IntegerField(null=False, max_value=1, min_value=0)
How do I define a default value for this field i.e. if this parameter isn't passed, I default to 0 (False).
I don't have a form on the client side. I'm using the Django form the validate my JS POST request.
In one of model fields I need to store screen resolution in the format 1234x4321. Should I declare this as a CharField add some regular expression validation in both the Model and the Form? Any examples of regular expression validations would be helpful.
Thanks.

The validation should be done on the form, not the model. However, if you are using ModelForms, which is usually makes a lot of sense, it will inherit some of the validation rules from the models themselves (those specific to the database, like maximum_field length, database field type, but also if they can be left blank).
The default value of a field should be passed with its constructor:
form = SomeForm(initial={'alive' : 0})
Although in your case, it appears that if the values that can be obtained are only zero and one, it would be make sense to use a BooleanField instead(tand in that case it would default to false).
In the case of resolutions I would create a mapping between the possible resolution and some arbitrary value.
RESOLUTIONS = (
("1","800x600"),
("2","1024x768"),
.....
)
and then pass it to the model:
resolutions = models.CharField(RESOLUTIONS, max_length=1)
So that the user gets a select field with the corresponding options and values.
On the other hand, if you need the user to insert it him/herself, using two fields (one for width, another for height) would be much easier than validating the user input.
So you can define a method for the model:
def get_resolution(self):
return "%sx%s" % (self.width, self.height)

Related

Is there a way to map data from form to insert in to database without explicitly defining each variable?

I have made a really long form with the help of colander alchemy and deform.
This form has 100 or so fields and currently the only way I know to add the data back to the database once form is submitted is to explicitly re-define each variable and then add that to the database but there must be a better way.
#my schema
class All(colander.MappingSchema):
setup_schema(None,atr)
atrschema =atr.__colanderalchemy__
setup_schema(None,chemicals)
chemicalsschema =chemicals.__colanderalchemy__
setup_schema(None,data_aquisition)
data_aquisitionschema =data_aquisition.__colanderalchemy__
setup_schema(None,depositor)
depositorschema =depositor.__colanderalchemy__
setup_schema(None,dried_film)
dried_filmschema =dried_film.__colanderalchemy__
form = All()
form = deform.Form(form,buttons=('submit',))
# this is how I get it to work by redefining each field but there must be a better way
if 'submit' in request.POST:
prism_material = request.params['prism_material']
angle_of_incidence_degrees =
request.params['angle_of_incidence_degrees']
number_of_reflections = request.params['number_of_reflections']
prism_size_mm = request.params['prism_size_mm']
spectrometer_ID = 6
page = atr (spectrometer_ID=spectrometer_ID,prism_size_mm=prism_size_mm,number_of_reflections=number_of_reflections,angle_of_incidence_degrees=angle_of_incidence_degrees,prism_material=prism_material)
request.dbsession.add(page)
Would like to somehow just be able to remap all of that 'multi dictionary' that is returned back to the database?
So, you have a dict (request.params) and want to pass the key-value pars from that dict to a function? Python has a way to do that using **kwargs syntax:
if 'submit' in request.POST:
page = Page(spectrometer_ID=6,**request.params)
request.dbsession.add(page)
(this works also because SQLAlchemy provides a default constructor which assigns the passed values to the mapped columns, no need to define it manually)
Of course, this is a naive approach which will only work for the simplest use-cases - for example, it may allow passing parameters not defined in your schema which may create a security problem; the field names in your schema must match the field names in your SQLAlchemy model; it may not work with lists (i.e. multiple values with the same name which you can access via request.params.get_all(name)).

Django form has no errors, but is not valid? [duplicate]

Given an example like this:
class MyForm(forms.Form):
name = forms.CharField()
I'm trying to grasp what the difference between the following two snippets is:
"Bound Data" style:
my_form = MyForm({'name': request.user.first_name})
"Initial data" style:
my_form = MyForm(initial={'name': request.user.first_name})
The documentation seems to suggest than "initial is for dynamic initial values", and yet being able to pass "bound data" to the constructor accomplishes exactly the same thing. I've used initial data in the past for dynamic values, but I'm tempted to use the more straightforward "bound data" style, but would like some insights about what the real difference between these two styles is.
Here's the key part from the django docs on bound and unbound forms.
A Form instance is either bound to a set of data, or unbound:
If it’s bound to a set of data, it’s capable of validating that data and rendering the form as HTML with the data displayed in the HTML.
If it’s unbound, it cannot do validation (because there’s no data to validate!), but it can still render the blank form as HTML.
You can't really see the difference for the example form you gave, because the form is valid in the "bound data" style. Let's extend the form by adding an age field, then the difference will be more obvious.
class MyForm(forms.Form):
name = forms.CharField()
age = forms.IntegerField()
Bound form
my_form = MyForm({'name': request.user.first_name})
This form is invalid, because age is not specified. When you render the form in the template, you will see validation errors for the age field.
Unbound form with dynamic initial data
my_form = MyForm(initial={'name':request.user.first_name})
This form is unbound. Validation is not triggered, so there will not be any errors displayed when you render the template.
No, that's not what the difference is (and I'd be interested to know where in the documentation you got that impression from). The difference is whether validation is performed.
Initial data does not trigger validation. This allows you, for example, to pre-fill certain fields but leave others empty, even though they are required. If you used bound data, you would get errors for those empty required fields even on the first viewing of that form, which would be annoying for the user.
Bound data, of course, triggers validation. Also, if you're using a modelform, the related instance will only be updated with bound data, not initial data.
Another difference is that data expects something that widgets can parse whereas initial is per-field. This makes a difference if you e.g. use MultiWidgets. In such case data should contain something like
{'myfield_0': 'data for subwidget 0',
'myfield_1': 'data for subwidget 1'}
whereas initial expects something like this:
{'myfield': 'data for subwidget 0,data for subwidget 1'}

How to properly validate a MultipleChoiceField in a Django form

I have a MultipleChoiceField representing US states, and passing a GET request to my form like ?state=AL%2CAK results in the error:
Select a valid choice. AL,AK is not one of the available choices.
However, these values are definitely listed in the fields choices, as they're rendered in the form field correctly.
I've tried specifying a custom clean_state() method in my form, to convert the value to a list, but that has no effect. Printing the cleaned_data['state'] seems to show it's not even being called with the data from request.GET.
What's causing this error?
from django import forms
class MyForm(forms.Form):
state = forms.MultipleChoiceField(
required=False,
choices=[('AL','Alabama'),('AK','Alaska')],
)
MultipleChoiceFields don't pass all of the selected values in a list, they pass several different values for the same key instead.
In other words, if you select 'AL' and 'AK' your querystring should be ?state=AL&state=AK instead of ?state=AL%2CAK.
Without seeing your custom clean_state() method I can't tell you what's going wrong with it, but if the state field isn't valid because the querystring is wrong then 'state' won't be in cleaned_data (because cleaned_data only holds valid data).
Hopefully that helps. If you're still stuck try adding a few more details and I can try to be more specific.

Difference between Django Form 'initial' and 'bound data'?

Given an example like this:
class MyForm(forms.Form):
name = forms.CharField()
I'm trying to grasp what the difference between the following two snippets is:
"Bound Data" style:
my_form = MyForm({'name': request.user.first_name})
"Initial data" style:
my_form = MyForm(initial={'name': request.user.first_name})
The documentation seems to suggest than "initial is for dynamic initial values", and yet being able to pass "bound data" to the constructor accomplishes exactly the same thing. I've used initial data in the past for dynamic values, but I'm tempted to use the more straightforward "bound data" style, but would like some insights about what the real difference between these two styles is.
Here's the key part from the django docs on bound and unbound forms.
A Form instance is either bound to a set of data, or unbound:
If it’s bound to a set of data, it’s capable of validating that data and rendering the form as HTML with the data displayed in the HTML.
If it’s unbound, it cannot do validation (because there’s no data to validate!), but it can still render the blank form as HTML.
You can't really see the difference for the example form you gave, because the form is valid in the "bound data" style. Let's extend the form by adding an age field, then the difference will be more obvious.
class MyForm(forms.Form):
name = forms.CharField()
age = forms.IntegerField()
Bound form
my_form = MyForm({'name': request.user.first_name})
This form is invalid, because age is not specified. When you render the form in the template, you will see validation errors for the age field.
Unbound form with dynamic initial data
my_form = MyForm(initial={'name':request.user.first_name})
This form is unbound. Validation is not triggered, so there will not be any errors displayed when you render the template.
No, that's not what the difference is (and I'd be interested to know where in the documentation you got that impression from). The difference is whether validation is performed.
Initial data does not trigger validation. This allows you, for example, to pre-fill certain fields but leave others empty, even though they are required. If you used bound data, you would get errors for those empty required fields even on the first viewing of that form, which would be annoying for the user.
Bound data, of course, triggers validation. Also, if you're using a modelform, the related instance will only be updated with bound data, not initial data.
Another difference is that data expects something that widgets can parse whereas initial is per-field. This makes a difference if you e.g. use MultiWidgets. In such case data should contain something like
{'myfield_0': 'data for subwidget 0',
'myfield_1': 'data for subwidget 1'}
whereas initial expects something like this:
{'myfield': 'data for subwidget 0,data for subwidget 1'}

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.

Categories