简体   繁体   中英

Django formset - Creating a formset of just ONE form

I'm trying to implement a formset of just one form that will be edited with an user input. Currently I can only add all the forms I've currently declared but I only need one of those.

Im doing this:

    def oneForm(request):
Formset = formset_factory(testingForms)
form1 = Formset()
print(form1)

This is my forms.py:

class testingForms(forms.Form):
first = forms.DecimalField()
second = forms.CharField(max_length = 4)
third = forms.CharField(max_length = 1)

I want it to just be filled with the third form. So that when I use it in a template with the as_table() function, it prints out only the third form. I'm trying to avoid creating another class just for that... I don't feel like its done right.

If you only need 1 form, why use a formset instead of a single form?

In case you really do, just set max_num and min_num and extra to 1 and validate them.

Formset = formset_factory(testingForm, max_num=1, min_num=1, extra=1, validate_min=True, validate_max=True)

EDIT : Here's one solution.

forms.py

class FormA(forms.Form):
    first = forms.DecimalField()
    second = forms.CharField(max_length = 4)

class FormB(forms.Form):
    third = forms.CharField(max_length = 1)

views.py

from my_app.forms import FormA, FormB
from django.forms import formset_factory
from django.shortcuts import render_to_response, RequestContext

def your_view(request):
     form = FormA()
     # figure out how many instances of the third field you want
     number_of_forms = 3 # however you like
     FormsetFactory = formset_factory(FormB, min_num=number_of_forms, max_num=number_of_forms,extra=0,validate_min=True,validate_max=True)
     formset = FormsetFactory()
     if request.POST:
         # do something with post

     return render_to_response('your_template.html',{'form':form,'formset':formset}, RequestContext(request))

You just need to assign the formset_factory generator dynamically after figuring out the number needed.

There's more to rendering formsets properly, so take a look at the documentation .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM