Amit Pal
Amit Pal

Reputation: 11042

Getting an error while using Django Model Form in views.py

In my models.py

 class Alert(models.Model):

    user = models.CharField(max_length=30, blank=True)
    a = models.IntegerField(blank=True)
    def __unicode__(self):
        return "'%s' at %s" % (self.user)

In My forms.py:

 class AlertForm(forms.ModelForm):
    class Meta:
        model=Alert
        fields = ('a','user')
        widgets = {
            'user': forms.HiddenInput()
        }

AlertCountFormset = modelformset_factory(Alert,
                                        form = AlertForm)

In my views.py:

def profile_setting(request, slug):
if request.method == 'GET':
    form = AlertForm(request.POST)
    if form.is_valid():
        alert_form = form.save(commit=False)
        alert_form.user = request.user.username
        alert_form.save() # Here i am getting the error
        return HttpResponseRedirect('/user/list')

extra_context = {
    'form': AlertForm()
}
return direct_to_template(request,'users/profile_setting.html',
                          extra_context)

I am trying to fill the Django model Form but i am getting following error where i had put the comment:

events_alertcount.a may not be NULL

What is this? Even after putting thenull=True in the field of a it shows an same error. Is that something wrong with my forms.py or models.py?

Upvotes: 2

Views: 601

Answers (3)

Gezim
Gezim

Reputation: 7308

When defining a model field, the blank option is validation related, meaning that if you set blank to true, validation will not fail if that field is not filled in.

blank is validation-related. If a field has blank=True, validation on Django’s admin site will allow entry of an empty value. If a field has blank=False, the field will be required.

However, if validation doesn't fail and you save the model, the field will be persisted to the database. Now, a field cannot be null in the database unless you set the null option to true.

null is purely database-related, whereas blank is validation-related.

Having said that, you can fix you error by adding the null option to Alert.a:

a = models.IntegerField(blank=True, null=True)

Now, if you've already ran the syncdb command, you need to drop your tables and then rerun syncdb in order for this change to be picked up. If this database is a production database and you cannot do this, look into django-south on how you can migrate your schemas and data.

Upvotes: 2

jagm
jagm

Reputation: 576

try this:

a = models.IntegerField(blank=True, null=True)

and you should call syncdb once again

Upvotes: 3

Jingo
Jingo

Reputation: 3230

This is enforced on database level, too. Set your "a" column in your db to allow the field to be NULL. This should fix it. HTH.

Upvotes: 3

Related Questions