Using several different forms on the same page (Crispyforms in Django 1.7)

I am trying to display multiple forms on one page for my university management website. The idea is that the instructor should be able to enter all the labels for the group in a group assessment on the same page. The view should display the shape of the group item, followed by multiple shapes for the individual items (group size may vary).

Django's documentation is a little short on the idea of ​​form prefixes, so I'm not entirely sure if this is the right approach. I would like to make shapes with crispy shapes. Will this approach work or is there a better way to achieve the goal I mean?

views.py
--------
# Generate the forms for the template
group_form = GroupForm(prefix='group')
student_forms = []
for student in students_in_group:
    student_form = StudentForm(initial={...}, prefix=student.student_id)
    student_forms.append(student_form)
...
# Processing post request
if request.method == 'POST':
    group_form = GroupForm(request.POST, prefix='group')
    if group_form.is_valid():
        group_form.save()
    for student in students_in_group:
        student_form = StudentForm(request.POST, prefix=student.student_id)
        if student_form.is_valid():
            student_form.save()


group_feedback.html
-------------------
{% crispy group_form %}
{% for form in student_forms %}
{% crispy form %}
{% endfor %}

      

+3


source to share


1 answer


This code looks like it should function as you expect. Though perhaps a cleaner approach to using a formset for a list of forms StudentForm

.

views.py



StudentFormSet = modelformset_factory(Student)

# Processing post request
if request.method == 'POST':
    group_form = GroupForm(request.POST, prefix='group')
    if group_form.is_valid():
        group_form.save()
    formset = StudentFormSet(request.POST, prefix='student')
    if formset.is_valid():
        formset.save()
else:
    # Generate the forms for the template
    group_form = GroupForm(prefix='group')
    formset = StudentFormSet(queryset=Student.objects.filter(whatever gives you students_in_group), prefix='student')

      

I haven't tested how the forms will play with crispyforms for what it's worth.

+1


source







All Articles