Django - saving fields in invalid form submissions - python

What is the recommended way of handling a "save"-style form submission (created from a ModelForm) when:
A non-empty subset of the form's fields validate
A non-empty subset of the form's fields do not validate
I want to save the subset of fields that are valid to the instance in question, and not the invalid ones.
I'm fairly sure I could write the code to do this but as with much of Django I'm sure there's a "normal"/"recommended" way of solving this, or some pattern I can follow.
All advice much appreciated.

You will need to provide your own clean method to deal with the non-validating fields, and prevent cleaned_data being clobbered.
You will need to also provide your own save method which knows to only save the right fields.

Related

Set Textarea size for all Textfields in ModelForm

I have a model with tons of (10-20) fields, some of which are Textarea fields.
All of the textare fields should have a certain size (which differs from the default). I could set them all using the widget dictionary in the Meta class, but then i'd have to set them one by one, which seems unnecessary redundant.
Is there any better way to solve this?
Update:
Since it was suggested in the comments to use database normalization, I'm going to flesh out my case a little bit:
I have an model object which has the main purpose of taking in a lot of user data (i.e. an "application"). The benefit of just writing out every question to the user as one field is that I can easily create a model form for it and display and edit the data in the admin (which is good for my crm people as well).
I could create a dictonary like model for every field of the form but I'm not sure how I would go about actually using a ModelForm for creating it.
On the basis of your data, I can only offer this approach:
from django import forms
textarea_fields = ['field1', 'field2']
form = YourForm()
for field_name in [f for f in form.fields.keys() if f in textarea_fields]:
form.fields[field_name].widget = forms.Textarea()

Database queries with ModelForm Model(Multiple) Choice fields in Django

I have a form with some Model(Multiple)Choice fields that have so many options that I would like to trim down the available options based on user responses on the front-end, and then populate the select options through AJAX.
I am a little confused as to when Django will query the database in this case, and what are considered the best practices for Django ModelChoice fields that are populated with AJAX data.
Originally, I had been doing things like this:
contact = forms.ModelChoiceField(queryset=aRelatedModel.objects.all())
or a restricted queryset:
contact = forms.ModelChoiceField(queryset=aRelatedModel.objects.filter(somefield = someValue))
So, my question is, when does the DB get queried for ModelChoice options?
The confusion stems from another form I did, where I had a ModelChoiceField with the ability to add new options dynamically. In that case, unless I instantiated the ModelChoiceField after saving the new option, I would get an error. This makes me feel like the database is queried on form instantiation. But, given the lazy nature of Django querysets, it seems like it would also make sense that the DB is not queried until you iterate over said list (ie, when printing the form options).
So, in this kind of case is there a way to avoid potentially needless DB queries? What is the best practice for ModelChoiceFields that will be populated with AJAX data?
I've seen mentions of:
contact = forms.ModelChoiceField(queryset=aRelatedModel.objects.none())
...but never any explicit explanation on why to use this.
Edit:
In that case, I had a form with
field = forms.ModelChoiceField(queryset = relatedModel.objects.all())
Subsequently in the view, I naively did:
myForm = modelForm(request.POST). This produced an error if I instantiated the form before first saving the dynamically added field. After adding the field, and then calling modelForm(request.POST) I no longer had an "invalid choice" error - presumably because the dynamically added field was now included in the modelForm queryset.
I am not sure how that is relevant to the question, however. The question is when a modelForm's queryset is populated with data from the DB.

Django Rest Frame API: additional fields in ModelSerializer

Can I add additional fields to ModelSerializer subclass?
By saying 'additional field', I mean some fields don't belong any models in database, which any effort that try to map those fields to exist model fields will fail. The reason I need to include those fields is for design purpose. I need to those fields' value to do the validation and creating a new instance eventually.
I know there is a kwarg in ModelSerialzer called 'context'. By putting all the additional information into 'context', it will work. However, I want to know is that possible to create additional fields?
I have tried adding 'write_only=True', which doesn't work. The only left option is to override default restore_object method to create the instance with my will.
Any other ideas?
As you have not posted any code I can only give you a generic answer, but if I understand you correctly, you wish to add a custom field to a ModelSerializer thats not part of your model...
In DSF you can do this very esaily (read here):
In this case you just want a simple read-only field, so instead just use:
custom_field = Field(source='get_whatever')
In terms if validation after that please read the DRF guide here

Django best practice for displaying mostly read-only form, one field writeable

I have a requirement where one user creates an 'instance' of an object via a ModelForm. Another user of a different group has access to read all of the fields of the form, but has to update only one field. Think of a student who creates an exam object. Then a teach pulls up the exam and just needs to put in a grade, the rest of the exam is read only.
What's the best way to do that? Should I just query for the object, and display each field individually, then create a form (not a ModelForm?) for just the one field?
Should I just query for the object, and display each field individually, then create a form (not a ModelForm?) for just the one field?
This is probably the best way to go about it. Note you can use a ModelForm for the teacher form, see the Django documentation on using a subset of fields on a model form. You will have to display all the other fields manually in your template, but you should probably have a separate template for this view (I would use separate views as well).
You could find some code for a read only field on Django Snippets, but generally it's better to be explicit about what fields you are updating from each view. This is likely to be more trouble than it's worth.

Model and Validation Confusion - Looking for advice

I'm somewhat new to Python, Django, and I'd like some advice on how to layout the code I'd like to write.
I have the model written that allows a file to be uploaded. In the models save method I'm checking if the file has a specific extension. If it has an XML extension I'm opening the file and grabbing some information from the file to save in the database. I have this model working. I've tested it in the built-in administration. It works.
Currently when there's an error (it's not an XML file; the file can't be opened; a specific attribute doesn't exist) I'm throwing an custom "Exception" error. What I would like to do is some how pass these "Exception" error messages to the view (whether that's a custom view or the built-in administration view) and have an error message displayed like if the forms library was being used. Is that possible?
I'm starting to think I'm going to have to write the validation checks again using the forms library. If that's the case, is it possible to still use the built-in administration template, but extend the form it uses to add these custom validations?
Anything to help my confusion would be appreciated.
UPDATE:
Here's my model so far, for those who are asking, "nzb" is the XML file field.
http://dpaste.com/hold/6101/
The admin interface will use the Form you associate with your model; your own views can also use the form.
This is exactly what I'd like to do. However, I don't know how to associate my forms with my models. When ever I've created forms in the past they've always acted as their own entity. I could never get the administration views to use them while using the ModelForm class. Can you shead any light on this?
I've read over the link you gave me and it seams to be what I've done in the past, with no luck.
Getting attributes from the file, should probably be a method.
Sorry, could you please elaborate on this? A method where?
UPDATE:
It seams I've been compleatly missing this step to link a form to the administration view.
http://docs.djangoproject.com/en/dev/ref/contrib/admin/#adding-custom-validation-to-the-admin
This should now allow me to do the validation in a Form. However, I'm still confused about how to actually handle the validation. S.Lott says it should be a method?
The Form errors are automatically part of the administrative view.
See http://docs.djangoproject.com/en/dev/ref/forms/validation/#ref-forms-validation
You're happiest if you validate in a Form -- that's what Forms are for. The admin interface will use the Form you associate with your model; your own views can also use the form.
Getting attributes from the file, should probably be a separate method of the model class. The separate method of the model class can be used by the save() method of the model class or invoked at other times by view functions.
"I could never get the administration views to use them while using the ModelForm class."
http://docs.djangoproject.com/en/dev/ref/contrib/admin/#form
http://docs.djangoproject.com/en/dev/ref/contrib/admin/#adding-custom-validation-to-the-admin
"I'm still confused about how to actually handle the validation. S.Lott says it should be a method?"
Validation in a form is done with a clean() method or a clean_somefield() method.
The "Adding custom validation to the admin" link (above) shows how to add the clean_name method to the "MyArticleAdminForm" form.
If you're still confused, trying actually typing the code from the Django web page and see what it does.
I guess the best way would be to implement a special field class that extends FileField with custom validation of the uploaded file.
The validation is implemented in the field's clean method. It should check the XML file and raise ValidationErrors if it encounters errors. The admin system should then treat your custom errors like any other field errors.
The ImageField class is a good example of special validation like this — I recommend just reading through the source.
You can provide a form that will be used by the admin site. You can then perform validations in the form code that will be displayed in the admin area.
See the docs on the admin site, and in particular the form attribute of ModelAdmin.
"I'm throwing an custom "Exception" error " - Where exactly are you throwing the exception ? In your model or in your view ?
I am confused with your question, so I am assuming that you should be asking 'Where should I catch input errors if any ? ' to yourself.
The Model and View as I see are like pieces in a small assembly line.
View/ Form validation is the first action which should be performed. If there is any issue with the input data through the forms. It should be prevented at the form level using form.is_valid() etc.
The models functionality should be to provide meta information about the entity itself apart from performing CRUD. Ideally it should not be bothered about the data it is getting for the CRUD operations.

Categories

Resources