Confusion between Form Validation and Model Validation in Django

Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design-- www.djangoproject.com

Using Django Model Form can make it fast and powerful to validate input data. But new Django programmer can be confused between form validation and model validation. Both of these are defined in models.py

class Report(models.Model):
    name = models.CharField(_('Name'), max_length=20, blank=False, null=False, default=None)

When you define "null=False" and "blank=False" to the model field, let see what you will get?

"null = False", sure thing that it's gonna raise IntegrityError when you try to save but didn't assign value to the field.

"blank=False", Do you suppose that it's gonna work at model level?

If so, you will be disappointed because "blank=False" will take effect only at form level. Means that you can save the instance using the shell.

(InteractiveConsole)
>>> from report.models import Report
>>> new_report = Report()
>>> new_report.save()
>>> Traceback (most recent call last):
...
>>> IntegrityError: report_report.name may not be NULL

 Assign blank name.

>>> new_report.name = ''
>>> new_report.save()

Now you get the Report object with blank in the name field in the database!

To avoid this, let's create the helper:

from django.db import IntegrityError
def not_null_not_blank(instance, attribute_name_iter ):
    for attribute_name in attribute_name_iter:
        if not getattr(instance, attribute_name):
            raise IntegrityError('%s.%s may not be NULL or BLANK' % (instance.__class__.__name__, attribute_name )) #This line is inspired by Nattapon (@wrongite)

And override your model's save function:

class Report(models.Model):
    name = models.CharField(_('Name'), max_length=20, blank=False, null=False, default=None)
    def save(self, force_insert=False, force_update=False):
        not_null_not_blank(self,('name',  ))
        return super(Report , self).save(force_insert=force_insert, force_update=force_update)

Now exit the shell and open it again ( to reload new code you've just changed )

(InteractiveConsole)
>>> from report.models import Report
>>> another_report = Report()
>>> another_report.name=''
>>> another_report.save()
>>> Traceback (most recent call last):
...
>>> IntegrityError: Report.name may not be NULL or BLANK

Now you're good to go!! ; )

Comments:

Why not make it into a decorator instead?

Using decorator is a good idea. ;)

I will add this to the entry. Thank you.

I just read through the entire article of yours and it was quite good. This is a great article thanks for sharing this informative information. I will visit your blog regularly for some latest post.

Will there be any difference if you are using Linux? Does this get any worst?

The solution in the ticket only works with the latest version of bpython in the repository.

Bob has asked me to document the procedure you used to make Django work with bpython. Is it okay if I copy/paste the w

Ryan checks that you have 4 spaces before "pass". If it doesn't fix see if you miss ":" at the end of the line above "pass".

Nice, I linked to this, so nice to have bpython with settings and it works with virtualenv too.

Absolutely gorgeous! You’ve done a wonderful job on it. I like the trimmer fit of this version compared to the previous version.

Hello you I do absolutely dig your nice article, I would feel very honored if you allow me to publish a adorable review on your incredible web blog in my Blog Site would you be OK with that?

I love seeing websites that understand the value of providing a quality resource for free. It’s the old what goes around comes around routine.

I completely agree with you. I have no point to raise in against of what you have said I think you explain the whole situation very well

I enjoyed your blog. It’s easy to read, the content is good, and you’re an educated writer unlike most of the blogs I come across when searching on this topic. I will check back in the future and see if you have more articles. Thanks for posting this, I appreciate the information and the effort you put into your site.

This site is good because they give us a new thing and new ideas and new topic how good all of they are we should appreciate them because of these good thing.

I have learned many important things from your post and i want to thank you for sharing this post.

Great article! I’m happy, that there is no Bieber hysteria here in Europe. But in the end, we’ve got our own beavers (taht’s what German word Bi[e]ber means).

well, I know this confusion between form validation in model is always great and wanted to be like that always.

yeah this is one confirmations that I wanted to know "Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design"

I have found this article is great. I hope it would be helpful for me. Thanks for this nice post

I honestly don't understand the meaning of this "Django" and what is this for. Anyway Can you help me understand it?

how are we going to validate this model? I know that this is something that we should do about.

I am new to programming, but I learn quickly, probably because to me it's interesting. I've taught myself a few features found library and wrote a couple of challenging programs. If I do not understand something, I ask this in the forums or find articles like this.

Because of a considerable overlap in technology, spare and backups method are frequently confused with archives and fault-tolerant systems.

I want to show my admiration of your writing skill and ability to make audience, browse the whole thing to the end. I'd really like to read more of your blogs and to talk about my views with you. I'll be your frequent website visitor, that’s for sure.

I know also that will get validated with the django.

"Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design"

- yeah I get it now.

Thanks for straighten things out. Thanks for the information provided.

I like this concept. I visited your blog for the first time and became your fan. Keep posting as I am going to read it everyday.

Wish I had found this blog before. The advices in this post are very helpful and I surely will read the other posts of this series too. Thank you for posting this.

You have a very good site, well constructed and very interesting i have bookmarked you hopefully you keep posting new stuff.

Good post....thanks for sharing.. very useful for me, I will bookmark this for my future needs.

Its really wonderful and watchable. I like to share it with all my friends and I am sure they will like it.

I happen to enter your blog with the help of Google search. To my sheer luck I got what I was searching for. Thanks!!!

Amazing!I also wish him good luck to defend his gold medal. I like to share it with all my friends and hope they will also encourage him.

I also wish him good luck to defend his gold medal. I definitely enjoyed every little bit of it I have you bookmarked to check out new stuff you post.

Very significant article for us ,I think the representation of this article is actually superb one. This is my first visit to your site.

Excellent read, I just passed this onto a colleague who was doing a little research on this topic. And he actually bought me lunch because I found it for him. So I should thank you for the free lunch I got.

I don't have any words to appreciate this post.....I am really impressed ....the person who created this post surely knew the subject well..thanks for sharing this with us.

Everyone dreams of having his own house. If you too want to have your own house, read this blog where you will find tips to help you find your dream house.

All the information on how to get your dream house is there for you on this blog. Take a look and and you will find all that you need to know.

I am so glad this internet thing works and your article really helped me. Might take you up on that home advice you gave. Perhaps a guest appearance would be good.

Escorts Las Vegas: Escort Agency Las Vegas provides the best Independent Escorts Las Vegas. Considered as the best Escort Agency in Las Vegas.

This is a really good post. Must admit that you are amongst the best bloggers I have read. Thanks for posting this informative article.

I have been reading your posts regularly. I need to say that you are doing a fantastic job. Please keep up the great work.

Just read your post and would like to thank you for maintaining such a cool blog.

Awesome content. I bookmarked it for future reference.

Nice post. I like the way you start and then conclude your thoughts. Thanks for this information .I really appreciate your work, keep it up

I really appreciate the kind of topics you post here. Thanks for sharing information that is actually helpful. Good day!

Its always good to have tips on good blog posting. As I just started posting comments for blog and faced a lot of rejections. I think your suggestion would be helpful for me. I will let you know if this works for me.

I wanted to thank you for this great read!! I definitely enjoyed every little bit of it, I have you bookmarked to check out all the new stuff you post....

This kind of validation is necessary to make the software have a better user experience.

The Django Form is confusing. However, I just bought a TV and it made it better.

I discovered so many interesting products in your site, especially its conversation. From the plenty of feedback on your content, I think I am not the only one having all the pleasure here! Keep up the great.

As I just started posting comments for blog and faced a lot of rejections. I think your suggestion would be helpful for me. I will let you know if this works for me.

I discovered so many interesting products in your site, especially its conversation. From the plenty of feedback on your content, I think I am not the only one having all the pleasure here! Keep up the great.

That's great, I never thought about how much wine should you buy for a party like that before.

I want to demonstrate my appreciation of your composing expertise and capability to make visitors, look at the whole element to the end. I'd really like to study more of your weblogs and to discuss my opinions with you. I'll be your consistent web page guest, which is sure for you.

I want to demonstrate my appreciation of your composing expertise and capability to make visitors, look at the whole element to the end. I'd really like to study more of your weblogs and to discuss my opinions with you. I'll be your consistent web page guest, which is sure for you.

The homes in Vital Feelings tend to be spacious to provide you with sufficient inhaling area and comfort.

Fantastic products from you, man. Ive comprehend your products past to and you are just too excellent. I really like what you have obtained here, certainly like what you are revealing and the way in which you say it. You create it interesting and you still proper take good to keep it sensible. I cant delay to study far more from you.

Fantastic products from you, man. Ive comprehend your products past to and you are just too excellent. I really like what you have obtained here, certainly like what you are revealing and the way in which you say it. You create it interesting and you still proper take good to keep it sensible. I cant delay to study far more from you.

Nice hard work, extremely useful, this will help me personally to finish my own job.

Great hard work, very helpful, this will aid me personally to perform my personal activity.

Congratulation for the great post. Those who come to read your article will find lots of helpful and informative tips.

awesome information. Thanks for sharing.

this is very useful for us. so thanks for sharing

I want to thank you for the efforts you made in writing this article. I hope the same best work from you in the future too. In fact your creative writing abilities has inspired me.

Adore and am accustomed to preserving a range with those people transformed things.Only on this way can i am aware what will not be abandoned by time. Forexample, even although you adore someone, lkljljl1i9tyytyu modifications are all around. Then I stepbackward and viewing it silently, then I see the correct feelings.

I am glad to see that people are actually writing about this issue in such a smart way, showing us all different sides to it. You are a great blogger. Please keep it up. I cant wait to read whats next

Nice hard work.keep it up..Your help is really appreciated..

Petra was elected as a headquarter of the Nabateans for the reason that it was situated in a basin bordered by mountains of sandstones. There are several routes that lead into the capital, but not a single of them are unchallenging, and in case the gorges are closed, it is nearly unfeasible for any person to get inside the city.

Post your comment:

Author:

  • chanita

Archives:

Powered by Django.