I have a form.py file with the form data and some validations, but in my template file, i use my manual html file without render it from the form.py, after post the data from the template, how can i return all the data to the template when the data is not valid(validate in the form.py) in the view.py.
sorry, my question is not so clearly, my qestion is how can i render the data back to the manual template in the views.py after errors found.
the following is the code example:
form.py (i have many fields in the form and some validations)
class Project_f(forms.Form):
slug=forms.CharField(max_length=100)
......
views.py
def post_view(request, *args, **kwargs):
Pr_form=Project_f(request.POST,request.FILES)
if Pr_form.is_valid():
.........
return HttpResponseRedirect('/admin/mpm/project/')
'''when Pr_form is not valid'''
c={'form': Pr_form}
c.update(csrf(request))
return render_to_response('project_form.html',c)
template
manual template without using form.py,al开发者_如何转开发l the element is the same with that in the form.py, but the format/widget different, such as with some js.
Just because you didn't send the form object to the template, you can still validate against the data. Whatever view you are submitting to, you just need to test for request.POST then do the old myForm = MyForm(data=request.POST) followed by myForm.is_valid(). Just make sure that the form you created in HTML has their respected "name" element set to what you have in your form class.
class MyForm(forms.Form):
foo = forms.CharField()
bar = forms.CharField()
def myView(request):
if request.POST:
myForm = MyForm(data=request.POST)
if myForm.is_valid():
""" do stuff """
else:
""" do stuff with errors """
else:
""" print a page or somthing """
Q: how can i render the data back to the manual template in the views.py after errors found?
I assume post_view
is to process the Pr_form
on POST
request, although both GET
and POST
can be processed in the same view.
A: When a Pr_form.is_valid()
returns False
the Pr_form
instance will be populated with the appropriate error messages and the data entered by the user, so if you return the same Pr_form
instance which failed validation, to your template, it should show you the error messages and the data entered by the user, unless you have customized the way you show the Pr_form
in the template, if so then include {{Pr_form.slug.errors}}
as shown here
精彩评论