Search code examples
djangodjango-formsmodelform

Add a "+" button that opens a popup inside my django model form


I want to add a "+" button that opens a popup inside my django model form.. Any idea about that?

My code in models.py

class library(models.Model):
    book_name = models.CharField(max_length=50, null=True, blank=True)
    author = models.ForeignKey(User, on_delete=models.CASCADE, limit_choices_to={'is_superuser': True}, null=True,
                               blank=True)
    description = models.TextField(null=True, blank=True)
    duration = models.DurationField(null=True, blank=True)
    date = models.DateField()
    book_image = models.ImageField(upload_to='lib/book_img', null=True, blank=True)

parallel to author field i want to add a "+" button(To add new author) that opens a popup modal form.

my forms.py is

class library_details(forms.ModelForm):
    class Meta:
        model = library
        fields = "__all__"

Solution

  • You could use bootstrap modal.

    https://getbootstrap.com/docs/4.0/components/modal/

    You'd just have to add a form field that is blank but set the attributes that are necessary to open the modal.

    Something like the below

    NOTE: I have not tested this.

    class library_details(forms.ModelForm):
        checkbox = forms.CheckboxInput()
    
        class Meta:
            model = library
            fields = "__all__"
    
        def __init__(self, *args, **kwargs):
            super(library_details, self).__init__(*args, **kwargs)
            self.fields['checkbox'].widget.attrs['data-toggle'] = "modal"
            self.fields['checkbox'].widget.attrs['data-target'] = "#exampleModal"