开发者

How do I handle multiple forms in Django with many-to-many relationship

开发者 https://www.devze.com 2023-02-07 09:03 出处:网络
In my view I have a the Booking information, inthe booking I have a many-to-many relationship to the size of the group in the booking and the age. The class (group size, age) has the many-to-many rela

In my view I have a the Booking information, in the booking I have a many-to-many relationship to the size of the group in the booking and the age. The class (group size, age) has the many-to-many relationship. When the booking is made I would like the user to be able to add class details. So a booking can have many classes.

I have tried using inline_formset_factory but it did not like the many-to-many relationship and according to the doc开发者_Go百科s inline_formset_factory is for a ForeignKey relationship (I could easily be wrong here). Also it seems I need a booking instance before I can use the inline_formset_factory (Though again I could be wrong)

So to recap I'm new to django and I'm trying to add many classes to a booking via a form which is with the booking form. I'm just not sure if I'm on the right track.

I hope this made sense. Thanks in advance.


Rather than creating the form yourself, instead use a ModelForm which will tie your form to a model in your app, automatically creating the field types it needs to save or edit an instance of the model it is linked with.


The simplest way to add a Booking instance to you database would be to use a ModelForm:

from django.db import models
from django.forms import ModelForm

class Booking(models.Model):
    ...

class BookingForm(ModelForm):
    class Meta:
        model = Booking

See the Django docs for more information on ModelForms. Next in your view create an instance of the BookingForm passing it in your template context:

def your_view(request):
    if request.method == 'POST':
        form = BookingForm(request.POST)
        if form.is_valid():
            booking = form.save()
            return HttpResponseRedirect('/success/url/')
    else:
        form = BookingForm()

    return direct_to_template(request, 'your/template.html', {
        'form': form
    })

For more information on dealing with forms in your views see using a form in a view in the Django docs. Next in your template you can simply print the entire form (and all the relevant fields) like so:

<form action="" method="post">
    {{ form.as_p }}
    <input type="submit" name="submit" value="submit">
</form>

See displaying a form using a template for more information on forms in templates.

0

精彩评论

暂无评论...
验证码 换一张
取 消