Use cases for overriding save method in Django - django

Suppose I have a ModelForm and want to save the form. I know that we can override save method in django in the forms and models python code. But I want to know when exactly we should use saving forms in views, override save in forms and override save in models?

There's no right answer.
All you can do is choosing case by case:
Forms:
Specific methods will be used specifically when model is saved using this form.
Models:
Method will (almost) be used when saving models.
A third way you don't mention is Signals.

Related

Django model validation in clean or in separate validators?

I am pretty new to Django and I was wondering what is the best method to validate your models in Django? Are there any advantages to using clean vs adding validators to your models? By validators I mean when you do declare the field, populating the validator=[] list. I find the models to be easier to read with the validators in another package, and declared in the field list. Also, I try to validate the data before in services, before initializing the models. What do you think / prefer? Thanks a lot.
The difference is that a validator will apply to model objects created in forms and directly, i.e.:
form = MyModelForm(...
# and
my_model = MyModel(...
Whereas clean will only apply to a form. If you are creating model objects outside of forms then you should consider using validators. You might also find using validators to be a cleaner, more DRY method of checking what is created rather than overriding form clean functions.

Storing value in django models without using Model forms

I am having very complex models in my project, that I cannot display easily on HTML page using modelForms.
So I want to to use normal forms instead and store the values in Models.is it possible?
It is possible. You simply create your own form by inheriting forms.Form.
Then get the form input from request in your views and create your object.
In short what you are asking is possible.
Here is the official documentation for forms: https://docs.djangoproject.com/en/1.8/topics/forms/

Django. Many forms have OneToOne to one specific model. Forms should always be saved with these relations. How to implement efficiently?

I have many models (Customer, Seller, Product etc.), each of them has a set of images (Gallery, OneToOne relationship).
Also, some models (Customer, Seller, Moderator, Administrator) has OneToOne with User that is used for storing credentials.
I want to create and update these related models together.
Of course, simplest way is to use a class-based view and override get, post and form_valid methods. But there are many models having Gallery and User and I intend to follow DRY and code reuse principles and not to alter each view in same way.
Ideally, solution is sophisticated form (or form set) and using of standard class-based views without method overriding. Other option is different form and class-based view mixin.
I thought few hours about mixins but didn't came up with solution. Now I'm trying to do something with some kind of form sets.
In the case of the gallery is recommended to create an app only for that purpose.
On the case of the user the implementation Here's my recommendation:
1 - Create a base User class with all the core functionality your looking for.
2 - Extend the User class for all the other cases with the functionality your looking for.

When to use form vs model validation?

Just curious. What is the best practice for when to use form vs model validation?
From what I understand currently, form validation should be used for:
AJAX / HTTP requests params
Forms that do not correlate to a model?
Another question is: I have a HTML form that roughly correlates to a model instance, do I use a ModelForm for it?
Definitely use ModelForm, if your form resembles model object even in a tiny bit.
If there are some minor differences (e.g. you don't use some of the fields or you want to use different error messages etc.) it's much easier to customize ModelForm then to use Form and implement all this functionality from scratch.
For more reference regarding ModelForm please checkout PyDanny's Core Concepts of Django ModelForms.
I am also trying to understand what is the difference/relation between form and model validation and I would like to share my notes that are formed after reading several docs.
I am currently interested in Creating Forms from Models
#mariodev shared the document Core Concepts of Django ModelForms and this provided a good start.
ModelForms select validators based off of Model field definitions
The main story behind the scenes seems to be the DRY principal. This article explains very well what exactly is the case here.
All right, all this is fair. The question is "Where in the Django Documentation is this explained"?
I bumped on a very brilliant article where it states that:
The form.full_clean() method is called by django at the start of the validation process (by form.is_valid(), usually immediately after the view receives the posted data).
Correct me if I am wrong but that line reads that everytime I enter data and hit 'enter' the validation process begins!
OK, this is simple now:
The validation on a ModelForm begins when we hit 'enter'.
Django first validates the form by checking one by one every applicable validation method on Fields, Field Subclasses (This is the documentation for a model's field subclass, not for a form field subclass), Form Subclasses and ModelForm (since it is a ModelForm).
Finally, it validates the Model Instance.
This is how all this works theoretically. The only thing that remains is to implement it.

Django Model field as formfield in templates

I guess this is a simple question, but I am not being able to find a definitive answer whether this is possible or not.
I have a Model object that is being passed to my template during rendering. While I use most of the Model fields to show their values, I came across a need to show a few of them as formfields (with their respective HTML element like rendered via ModelForms). Can ModelForm class usage be avoided here and simply use the Model's field to be rendered as formfield directly from template?
an example:
class MyModel(models.Model):
month = models.PositiveIntegerField(_('Month'), choices=MONTH_CHOICES)
year = models.PositiveIntegerField(_('Year'))
Now in template based on the above Model example I want to show the year as a value but month as a dropdown with selected current value?
Any pointer appreciated!
Use case:
Imagine a generic list_view like case where you are rendering a queryset. What you have there is object per iteration, however on the list view you want to allow your users to perform some quick editing of few object attributes to avoid forcing them to go to full edit mode (maybe via simple ajax).
No.
As canvassed in the comments, this is not possible. A model, and its fields do not know about forms - that is what forms, and modelforms are for.
The right way to do this is to wrap your model objects with a modelform, which you can adjust (using inheritance) to do whatever you want with the non-form fields, if you wish to make this more transparent.
Creating modelforms in the template means that you have nowhere to process the forms in django. Apparently you want to interface them with some kind of ajax interface, so perhaps this is not a problem for you, but in any case, I fail to see how it would be easier than simply creating the modelforms in the view.