Cannot save a form

Hello,

I learning Python/Django since weeks. I managed to do some things by myself, but I don’t understand something… I think there is something I don’t understand about forms.

Here is my model :

class Author(models.Model):
    name = models.CharField(max_length=200)
    surname = models.CharField(max_length=200)
    bio = models.URLField(max_length=400)
    pass

    def __str__(self):
        return "%s %s" % (self.surname, self.name)

class Source(models.Model):
    name = models.CharField(max_length=350)
    author = models.ForeignKey(Author, on_delete=models.CASCADE)
    publication_date = models.DateField(auto_now=False)

    def __str__(self):
        return "%s" % (self.name)

class Quote(models.Model):
    content = models.TextField()
    source = models.ForeignKey(Source, on_delete=models.CASCADE)

Here is the form :

class QuoteForm(forms.ModelForm):

    class Meta:
        model = Quote
        fields = ('content',)

    def __init__(self, *args, **kwargs):
        super(QuoteForm, self).__init__(*args, **kwargs)
        self.fields['source']=forms.ModelChoiceField(queryset=Source.objects.all())

Here is my view :

def newquote(request):
    if request.method == 'POST':
        form = QuoteForm(request.POST)
        if form.is_valid():
            enreg = form.save(commit=False)
            enreg.content = form.cleaned_data['content']
            enreg.selected_source = form.cleaned_data['source']
            enreg.save()
            return redirect('index')
    else:
        form = QuoteForm()

    context = {'form': form, }

    return render(request, 'Citatio/newquote.html', context)

I want to save the form creating a new entry of a quote, linking it with an existing book.

I managed to create to create a form with a blank field to write my quote and a dropdown list to select a source book.

But when I save the form, I get a NOT NULL CONSTRAINT error with the source_id field…

I’m unable to understand the error :frowning:

Thank you for your help :slight_smile:

In your post method, you’re setting enreg.selected_source, but the name of the field in your model is source.

But beyond that, you’re doing more work than you need to.
Try this:

class QuoteForm(forms.ModelForm):

    class Meta:
        model = Quote
        fields = ('content', 'source')

and:

def newquote(request):
    if request.method == 'POST':
        form = QuoteForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('index')
    else:
        form = QuoteForm()

Thank you for your help.

It worked ! :wink: