| 316 | |
| 317 | Example View |
| 318 | ~~~~~~~~~~~~ |
| 319 | |
| 320 | Putting this all together, here is a simple view method for the example of our contact form: |
| 321 | |
| 322 | from django.shortcuts import render_to_response |
| 323 | from django import newforms as forms |
| 324 | |
| 325 | class ContactForm(forms.Form): |
| 326 | subject = forms.CharField(max_length=100) |
| 327 | message = forms.CharField() |
| 328 | sender = forms.EmailField() |
| 329 | cc_myself = forms.BooleanField() |
| 330 | |
| 331 | def contact(request): |
| 332 | if request.POST: |
| 333 | f = ContactForm(request.POST) |
| 334 | if f.is_valid: |
| 335 | # ... do something with f.cleaned_data |
| 336 | else: |
| 337 | f = ContactForm() |
| 338 | return render_to_response('contact.html', {'form': f}) |
| 339 | |
| 647 | In the templates |
| 648 | ---------------- |
| 649 | |
| 650 | With the above example, lets put this into a view and show how you can use these |
| 651 | parts from the template designer's point of view. Assuming you start with a view like: |
| 652 | |
| 653 | def contact(request): |
| 654 | form = ContactForm() |
| 655 | if request.method == 'POST': |
| 656 | new_data = request.POST.copy() |
| 657 | form = ContactForm(new_data) |
| 658 | if form.is_valid(): |
| 659 | # do form processing here... |
| 660 | return render_to_response('contact.html', {'form': form}) |
| 661 | |
| 662 | Then you can have a simple template that uses the shortcuts for form.as_ul, form.as_p, or form.as_table. An example ``contact.html`` template:: |
| 663 | |
| 664 | <form method="POST"> |
| 665 | {{ form }} |
| 666 | </form> |
| 667 | |
| 668 | or |
| 669 | |
| 670 | <form method="POST"> |
| 671 | {{ form.as_table }} |
| 672 | </form> |
| 673 | |
| 674 | If you wanted to work with the individual inputs of the form, you can either call out the fields directly, or iterate over them: |
| 675 | |
| 676 | <form method="POST"> |
| 677 | <dl> |
| 678 | {% for field in form %} |
| 679 | <dt>{{ field.label }}</dt> |
| 680 | <dd>{{ field }}</dd> |
| 681 | <dd>{{ field.help_text }}</dd> |
| 682 | {% if field.errors %}<dd class="myerrors">{{ field.errors }}</dd>{% endif %} |
| 683 | {% endfor %} |
| 684 | </dl> |
| 685 | </form> |
| 686 | |
| 687 | Alternately: |
| 688 | |
| 689 | <form method="POST"> |
| 690 | <ul class="myformclass"> |
| 691 | <li>{{ form.sender.label }} {{ form.sender.label }}</li> |
| 692 | <li class="helptext" >{{ form.sender.help_text }}</li> |
| 693 | {% if form.sender.errors %}<ul class="errorlist">{{ form.sender.errors }}</dd>{% endif %} |
| 694 | |
| 695 | <li>{{ form.subject.label }} {{ form.subject.label }}</li> |
| 696 | <li class="helptext" >{{ form.subject.help_text }}</li> |
| 697 | {% if form.subject.errors %}<ul class="errorlist">{{ form.subject.errors }}</dd>{% endif %} |
| 698 | |
| 699 | ... |
| 700 | </ul> |
| 701 | </form> |
| 702 | |
| 703 | |