Search code examples
djangodjango-model-field

How to make django model ManyToMany field empty initially?


I'm having two related models as follows.

class Book(models.Model):
    title = models.CharField(max_length=100)
    author = models.ForeignKey(Author)
    isbn =models.CharField(max_length=15)


class Lending(models.Model):
    member_id = models.ForeignKey(Member)
    name = models.CharField(max_length=100)
    borrowed = models.DateField(auto_now_add=True)
    returning = models.DateField()
    book_list = models.ManyToManyField(Book, related_name='borrowed_books')

I want to make the book list field empty in Lending creation HTML form when displayed to the user. I want to make sure it is not blank in backend model form and not null in the model. I'm doing this because the book list could be huge and will use ajax to query the book to add them dynamically to the book list in HTML form field when sending data. How can I do this?


Solution

  • If you are using django class based views, you can override get_form method to edit form and set some initial values. I can give you an example -

    class LendingView(generic.CreateView):
        ...
        def get_form(self,form_class=None):
            form = super().get_form(form_class)
            form['book_list'].field.choices = {}
            return form
    

    This will empty your choices for a field. Still have any doubts comment it.