dynamic forms in django
i've built my own dynamic form, kind of following james bennetts example. using the following lines in forms.py
def make_question_form(request):
fields = { 'venue' : forms.CharField(widget=forms.HiddenInput()),
'survey' : forms.CharField(widget=forms.HiddenInput())}
return type('Question_Form',(forms.BaseForm,), { 'base_fields': fields })
and the following in the view to build it (I know its not truely dynamic, i plan to add the dynamics next.
question_form = make_question_form(request)
question_form.base_fields['venue'] = this_venue.name
question_form.base_fields['survey'] = this_survey.name
return render_to_response("survey/questions.html", locals(), context_instance=RequestContext(request))
but im not sure what to dowith it in the template and this is the bit that isn't really covered in the tutorials.
i've worked out that the following works
{% for base_field in question_form.base_fields %}
{{ base_field.type }}
{% endfor %}
but i thought the point of building it as a form was to be able to do something 开发者_如何学编程like
question_form.as_p
and wrap it in my own form tags.
have i missed the point or should as_p work (it doesn't).
You haven't instantiated the form in your view. make_question_form
returns a new form class - normally when you use a form class in your view you do form = MyFormClass()
or form = MyFormClass(request.POST)
.
So you need to do form = question_form()
before the render_to_response
, then you'll be able to do {{ form.as_p }}
in the template.
精彩评论