0

Im getting null constraint when I'm trying to save the form

My model

class Subject(models.Model):
    name=models.CharField(max_length=128,  blank=True)
    created=models.DateTimeField('Created Date',blank=True)


    def __str__(self):
        return self.name

class Book(models.Model):
    book_subject=models.ForeignKey(Subject,on_delete=models.CASCADE)
    book_name=models.CharField(max_length=128)
    url=models.URLField()
    votes=models.IntegerField(default=0)
    created_time=models.DateTimeField('Created Date',blank=True)
    comments=models.CharField(max_length=400)

    def __str__(self):
        return self.book_name

my forms

class SubjectForm(forms.ModelForm):
    class Meta:
        model = Subject
        fields=('name', )

class BookForm(forms.ModelForm):
    class Meta:
        model = Book
        fields=('book_title',)

views.py

def add_subject(request):
    if request.method == 'POST':
        form = SubjectForm(request.POST)
        if form.is_valid():
            form.save(commit=True)
            return index(request)
        else:
            print form.errors
    else:
        form = SubjectForm()
    return render(request,'add_subj.html', {'form': form})

Im getting null constraint error when saving the form. Error is caused in views.py at form.save(commit=True) ...everything is straight forward..but confusing.....What could be the problem...

when I print the form I get following answer

<tr><th><label for="id_name">Name:</label></th><td><input id="id_name" maxlength="128" name="name" type="text" value="civil" /></td></tr>

Any help is much appreciated...thanks in advance

Moe Far
  • 2,742
  • 2
  • 23
  • 41
spidy
  • 269
  • 2
  • 13

1 Answers1

5

It looks like you're not actually setting the "created" field, and while you've set blank=True, you haven't set null=True. blank just means that the field doesn't need to be filled in forms, while null actually allows the fields to be None in the database. This is why your form is validating, but not actually saving.

So, you could add null=True to your created and created_time fields. However, if your intention is just to have them store the created date, it would be easier to just make the fields something like:

created = models.DateTimeField(auto_now_add=True)

auto_now_add will automatically set the field for you on the object's creation. This should pretty much do what you need.

csinchok
  • 741
  • 3
  • 10
  • could you please help me with my other question ....http://stackoverflow.com/questions/35357279/django-difficulty-in-displaying-the-datacount – spidy Feb 12 '16 at 17:43