fakeMake
fakeMake

Reputation: 778

How to avoid/eliminate Integrity error on form fields

I have a form that displays details but when I bring in a filter it fails. Where is the mistake?? The error is here

File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\sqlite3\base.py", line 413, in execute
    return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: NOT NULL constraint failed: libman_issue.book_id_id

This is the form

class IssueForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(IssueForm, self).__init__(*args, **kwargs)
        self.fields['book_id'] = forms.ModelChoiceField(
            queryset=Books.objects.filter(no_of_books=1),label='Available books')
    class Meta:
        model = Issue
        fields = ['borrower_id',]

When I have the form as shown below it works.

class IssueForm(forms.ModelForm):
      class Meta:
        model = Issue
        fields = ['borrower_id','book_id']

Upvotes: 1

Views: 48

Answers (1)

Ptar
Ptar

Reputation: 374

Pass the 'book_id' to the fields

class IssueForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(IssueForm, self).__init__(*args, **kwargs)
        self.fields['book_id'] = forms.ModelChoiceField(
            queryset=Books.objects.filter(no_of_books=1),label='Available books')
    class Meta:
        model = Issue
        fields = ['borrower_id','book_id']

Upvotes: 2

Related Questions