How to save multiple model form in one template?

108 views
Skip to first unread message

Django Lover

unread,
Sep 7, 2018, 10:43:11 AM9/7/18
to Django users

I have one page, which I have to show three model form and three different submit button for each.

My question is how I can save these three form individually?

FOLLOWING IS CODE:-

**form.py**


class UserTaxesMultiForm(MultiModelForm):
   form_classes = {
       'user_tax_form': MyForm,
       'user_discount_form': DiscountForm,
       'user_shiping_form': ShipmentForm,
   }

Note- myForm, DiscountForm, ShipmentForm are model forms. like following-

class MyForm(forms.ModelForm):
       prefix = 'tax'
       class Meta:
           model = StUserTaxDetails
           fields = ('tax_name', 'tax_rate')
     
       tax_name = forms.CharField(max_length=10,
        widget=forms.TextInput(),
        required=True, label="tax name")

        tax_rate = forms.FloatField(required=True,  label="tax rate")


        error_messages  = {
           'required': _('fields are required.'),
       }

        def clean_title(self):
           return self.cleaned_data['tax_name']

        def clean(self):
           tax_name = self.cleaned_data.get('tax_name')
           tax_rate = self.cleaned_data.get('tax_rate')
       
            if not tax_name and not tax_rate:
               raise forms.ValidationError(
                   self.error_messages['required'],
                   code='required',
               )
           return self.cleaned_data

**view.py**
class AddTaxView(LoginRequiredMixin, CreateView):
   template_name = 'invoices/add_tax.html'
   form_class = UserTaxesMultiForm
   success_url = '/add/tax/'

   {WHAT IS THE CODE HERE FOR THE POST METHOD TO SAVE DATA ACORDING DIFFRENT FORM SUBMIT}
               



**HTML**



<form method="POST">
{% form.user_tax_form%}

<input type="submit" value="Submit" />
</form>

<form method="POST">
{% form.user_discount_form%}

<input type="submit" value="Submit" />
</form>

<form method="POST">
{% form.user_shiping_form%}

<input type="submit" value="Submit" />
</form>

PLEASE HELP

Mohammad Aqib

unread,
Sep 7, 2018, 11:20:26 AM9/7/18
to django...@googlegroups.com
Show your models.py.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/45a017a3-9633-426f-81e1-b261189e714a%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


--
Mohd Aqib
Software Engineer
9873141865

Sunil Kothiyal

unread,
Sep 7, 2018, 11:27:00 AM9/7/18
to django...@googlegroups.com
following are my models they are not related to each other.----

class StUserTaxDetails(models.Model):
user = models.ForeignKey(UserModel, on_delete=models.DO_NOTHING, null=False, default=None)
tax_name = models.CharField(max_length=50)
tax_rate = models.FloatField()


def __str__(self):
return self.tax_name

class Meta:
managed = True
db_table = 'st_user_tax_details'


class StUserDiscountDetails(models.Model):
creater = models.OneToOneField(
UserModel, on_delete=models.CASCADE, blank=False)
discount_name = models.CharField(max_length=50)
discount_rate = models.FloatField()

class Meta:
managed = True
db_table = 'st_user_discount_details'


You received this message because you are subscribed to a topic in the Google Groups "Django users" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/django-users/HlJSOz8zgwM/unsubscribe.
To unsubscribe from this group and all its topics, send an email to django-users...@googlegroups.com.

To post to this group, send email to django...@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.

For more options, visit https://groups.google.com/d/optout.


--
Thanks & Regards,

Sunil Kothiyal


Elphas Rop

unread,
Sep 7, 2018, 12:03:38 PM9/7/18
to django...@googlegroups.com
you make the 3 forms then make a view for saving each form then url for each them then in each form action add a url to the view responsible for saving it

On Fri, Sep 7, 2018, 14:27 Elphas Rop <kimr...@gmail.com> wrote:
<form action="link to a url" method="post>
</form>

Sunil Kothiyal

unread,
Sep 7, 2018, 12:13:29 PM9/7/18
to django...@googlegroups.com
Do you have something to save multiform using by one view?/


You received this message because you are subscribed to a topic in the Google Groups "Django users" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/django-users/HlJSOz8zgwM/unsubscribe.
To unsubscribe from this group and all its topics, send an email to django-users...@googlegroups.com.

To post to this group, send email to django...@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.

For more options, visit https://groups.google.com/d/optout.


--

Akshay Gaur

unread,
Sep 7, 2018, 1:47:51 PM9/7/18
to Django users
I think it would be easier to write out a custom form (without using your model classes, just the fields that you will need for all the models) and then in the save method for that form's view, you create model objects using the fields in the POST request.

Anthony Petrillo

unread,
Sep 7, 2018, 1:56:47 PM9/7/18
to Django users
Here is an example. I've cut out some of the code, but I this will give you the general idea. Note, I move the data from the Day form in to the Classes table. But you could just save both sets of data to their respective tables if desired.

in views.py

class ClassesAddView(LoginRequiredMixin,View):
classesFormClass = ClassesRegForm
daysFormClass = DaysForm
template_name = 'qing/classes.html'

def get(self,request,role='NoRole'):
classesForm = self.classesFormClass()
context['form'] = classesForm
daysForm = self.daysFormClass()
context['daysform'] = daysForm
return render(request,self.template_name, context)

def post(self, request, *args, **kwargs):
classesForm = self.classesFormClass(request.POST)
daysForm = self.daysFormClass(request.POST)
if classesForm.is_valid() and daysForm.is_valid():
days = str(request.POST.getlist('days'))
reference = request.POST['reference']
classes = classesForm.save()
classes = Classes.objects.get(reference=reference)
classes.days = days
classes.save()
else:
classesForm = self.classesFormClass(request.POST)
context['form'] = classesForm
daysForm = self.daysFormClass(request.POST)
context['daysform'] = daysForm
context['datavalid'] = False
return render(request, self.template_name, context)
return HttpResponseRedirect(reverse('classesadd',args=(role,)))

in forms.py

class ClassesForm(ModelForm):
class Meta:
model = Classes
fields = ['reference','course','teachers',etc...]

class DaysForm(forms.Form):
OPTIONS = (
("Sunday", "Sunday"),
("Monday", "Monday"),
("Tuesday", "Tuesday"),
("Wednesday", "Wednesday"),
("Thursday", "Thursday"),
("Friday", "Friday"),
("Saturday", "Saturday"),
)
days = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple,
choices=OPTIONS)

Savvey Chauhan

unread,
Sep 8, 2018, 8:29:28 PM9/8/18
to django...@googlegroups.com
First Create 3 Views For each form .
Second Create urls for all 3 views .
THiRD CHANGE ACTION URL ACCORDING TO VIEWS URL
ADD AJAX TO SUBMIT THE FORM 
IF YOU WANT TO DISPLAY A TOAST MESSAGE USE TOASTR ON HTML PAGE.
eg :

 <form action="/YOURFIRSTFORMURL" method="post" id="target">
{% csrf_token %}
<div class="form-group">
<label for="fname">First Name:</label>
<input type="text" class="form-control" id="fname" placeholder="First Name" name="fname">
</div>
<div class="form-group">
<label for="lname">Last Name:</label>
<input type="text" class="form-control" id="lname" placeholder="Last Name" name="lname">
</div>

<div class="form-group">
<label for="lname">Gender:</label>
<input type="text" class="form-control" id="gender" placeholder="Last Name" name="gender">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>

</div>



<script>
$( "#target" ).submit(function( event ) {
var form = $("form").serialize();
$.ajax({
url: '',
data: form ,
success: function (data) {
toastr["success"]("New Student Added !")
}
});
event.preventDefault();
});
</script>

VIEWS.PY


def update(request):
fname = request.GET.get('fname')
lname = request.GET.get('lname')
gender = request.GET.get('gender')
student.objects.create(firstname=fname,lastname=lname,gender=gender)
return JsonResponse ({'Success':'Success'})







--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.

Sunil Kothiyal

unread,
Sep 10, 2018, 5:04:01 AM9/10/18
to django...@googlegroups.com
THIS IS MY FORM. I HOPE IT WILL CLEAR THE CONCEPT.

STLY.png

You received this message because you are subscribed to a topic in the Google Groups "Django users" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/django-users/HlJSOz8zgwM/unsubscribe.
To unsubscribe from this group and all its topics, send an email to django-users...@googlegroups.com.

To post to this group, send email to django...@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.

For more options, visit https://groups.google.com/d/optout.

Devender Kumar

unread,
Sep 12, 2018, 5:49:04 AM9/12/18
to django...@googlegroups.com
Hi,
I made it more simple and I implemented this also This is a solution is a little different from other solution 
you have three model form, one view which is rendering all the form.
If this is the case or somewhat similar then.
simply give name attribute to each submit button 
like: <button name="firstFrom" type="submit">
and in the view.
 if request.POST:
or if you are using class-based views then inpost func.
simply check for 
 if 'firstForm' in request.POST:

you get the idea I think. This will help you recognize which submit button is hit.

Regards 
Dev
Trippister



Everett White

unread,
Sep 19, 2018, 11:09:15 AM9/19/18
to Django users
Hey y’all

Sunil Kothiyal

unread,
Sep 19, 2018, 11:12:14 AM9/19/18
to django...@googlegroups.com

HI Everett White , Please suggest solution i am trying since 3 days, I want Django model update if exist. I will very thankful to you.

Daniel Bojorge (Foros)

unread,
Oct 13, 2018, 3:10:56 PM10/13/18
to Django users
Take a look to my course (in spanish) and go to the last CRUD, there I do a Master-Detail form, the detail form are many models

 DJANGO 2.1  https://goo.gl/oeT5Sx 

Joel Mathew

unread,
Oct 13, 2018, 3:16:28 PM10/13/18
to django...@googlegroups.com
Could you kindly stop spamming your course details over over this discussion group. It's not useful to the majority of us English speaking people.




--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.

Ing.Daniel Bojorge

unread,
Oct 13, 2018, 4:11:43 PM10/13/18
to django...@googlegroups.com
ok

Dios L@s Bendiga

Saludos,

 
 
Mi Blog
Nicaragua

"Si ustedes permanecen unidos a mí, y si permanecen fieles a mis enseñanzas, pidan lo que quieran y se les dará.
(Juan 15:7 DHH)
Bendito el varón que se fía en el SEÑOR, y cuya confianza es el SEÑOR.
(Jeremías 17:7 RV2000)



Reply all
Reply to author
Forward
0 new messages