Russell
Russell

Reputation: 1804

Django two forms interconnected in single template

I have another model which is like below

class Status(models.Model):
    name = models.ForeignKey(User, on_delete=models.CASCADE)
    status = models.BooleanField(default=False)

I just want to create a form which will render all users from django User model with upper model connected. When click single Status button it will just save that field. I'm using CreateView. How to do that?

<form method="post" action="">
User1 <input type="checkbox" name="status" />
<input type="submit" name="submit" value="Status"/>
</form>
<form method="post" action="">
User2 <input type="checkbox" name="status" />
<input type="submit" name="submit" value="Status"/>
</form>
<form method="post" action="">
User3 <input type="checkbox" name="status" />
<input type="submit" name="submit" value="Status"/>
</form>

Upvotes: 0

Views: 85

Answers (1)

Essex
Essex

Reputation: 6118

You could use Formsets from Django. Through this way, you can set 2 forms in one, get fields from both forms and save them with a single button.

For example, you have two models bounded by a ForeignKey in your models.py file :

class MyModelA(models.Model):
    field1 = ...
    field2 = ...

class MyModelB(models.Model):
    field1 = ...
    field2 = models.ForeignKey(MyModelA, ...)

Then, in your forms.py file, you have to bound these both forms thanks to formsets :

from django.forms.models import inlineformset_factory
from .models import MyModelA, MyModelB

MyFormSet = inlineformset_factory(MyModelA, MyModelB, form=MyModelBForm, extra=1, max_num=1)

With this line, your models will be set into the same django form in your template.

Now, in your views.py file, you have to call your formset :

class MyClassCreateView(CreateView):
    model = MyModelA
    template_name = 'path/to/your/template'

    def get_context_data(self, **kwargs):
        context = super(MyClassCreateView, self).get_context_data(**kwargs)
        context['my_form'] = MyFormSet(self.request.POST or None)
        return context

    def form_valid(self, form):
        context = self.get_context_data()
        document = context['my_form']
        if document.is_valid():
            self.object = form.save()
            document.instance = self.object
            document.save()
        return super(MyClassCreateView, self).form_valid(form)

And finally, in your template.html file, you can call your formset :

<form method="post" action="" novalidate>
     {% csrf_token %}
     {{ form }}
     {{ my_form }}   
     <input type="submit" class="btn btn-default" value="{% trans 'Save' %}" />
</form>

Hopfully it could help you to set your Django formsets

Upvotes: 2

Related Questions