django use ModelForm to validate a Model - django

Suppose I have a ModelForm for my Model with custom validation logic, and I want to reuse that to validate an existing model instance. Is there any way to do this?
I thought I could just do something like MyModelForm(instance=foo).is_valid(), but that doesn't work for multiple reasons.
I'd like to reuse the existing form validation to avoid duplication of code, but I can't find any way to do so.
Edit: I'm using Django 1.10, in case that makes a difference.

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.

Do I need to create forms.py for my forms in Django?

I'm about to create a form in my website made in Django with elements that have complex input types from different plugins (like calendar plugins). Also, I'll be using a Validator plugin which validates the input before submission.
My question is do I need to create forms.py and like model the form or can I just create the form manually? The former seems like a very hassle process. Which one is more efficient and recommended?
As #dmitryro said you can create your forms manually in the templates and then getting in the request. It's recommended to use the forms api provided by Django since it allows you to reuse, validate, and customize your forms.
As to whether or not it is a good practice that depends completely on you but if you are trying to scale an application I would recommend use the forms.
It is good to use Django's built in form.
If we use django's form then we only have to write python code and django will create corresponding html for it. And our code will be short and clean.

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.

Process of creating form in Django?

Django is really flexible. The simple html form can be used and processed in Django. But while going through the Django documentation I find that there are numerous ways to write a form in Django. The best I find is to create a forms.py and then create a template for it and process using views. Is this the right approach? I think it's way too easy to validate the form and use it in template using this approach. But I am confused where to apply the validation rules in this process. I want to use less Javascript as possible.
For validation you can specify them by
while defining field using validators attribute
by implementing clean_field() method in form
or clean() method in form for multiple field dependent validation.
The validation will be done when you call form.is_valid() method in the view where you are processing the form.
Here is more detailed documentation. Form and field validation

Django auth.User

I'm developing web page with many type of users, each with different profiles properties. I would like to use built in auth system but:
a) I want to use django-registration.
b) I can point User.get_profile to only one profile model.
How to accomplish that in nice fashion?
I haven't used django-registration so I don't know what it entails. For the second part of your question one way would be to
Associate an UserProfile with every User
Add different kinds of ProfileProperty classes and link to them from UseProfile using a generic relationship.
I know, it is a bit of a stretch.
I'm not an expert nor in python, django or database but I encountered a somewhat similar issue few weeks ago and on #django someone advised me to use Generic relation to achieve that.
I created a UserProfile model that is liked (through a OneToOnefield) to the "true" profile, and using contrib.content-type and generic relation I'm able to use several distinct porfile types.
Note that should work for you if you don't fear to hit you database one more time on each get_profile().
An alternative would be to create a big table that contain all the field for all the profile type and using some kind of hook (or reimplementing a custom save()) to check the retired fields according the profile type. But it look complicated to me, especially if you want to have a lot of different profile type.
Another alternative could be to create a TextField derivated custom field and use it as a storage for a dictionary that you pickle to it on save and unpickle from it on load. With some hacking you could certainly map some of the model attribute to the dictionary key. That would allow a lot of flexibility.
Free hint for ya : I also use fixtures to test my application and forgot to check if the raw parameter of the post_save signal was True to prevent executing the UserProfile creation when using manage.py loaddata. As I had coded the creation of the "true" profile in my post_save callback the exception what kind of weird until I find out what was happening.
Usefull ressource :
defining a profile
generic relation