Note_Tech

All technological notes.


Project maintained by simonangel-fong Hosted on GitHub Pages — Theme by mattgraham

Django - Form

Back


HTTP methods: GET and POST


Django Form class


Bound and unbound form instances


Looping over the form’s fields

__ for field in form __
<div class="fieldWrapper">
  __ field.errors __ __ field.label_tag __ __ field __ __ if field.help_text __
  <p class="help">__ field.help_text|safe __</p>
  __ endif __
</div>
__ endfor __

Rendering fields manually

from django import forms


class ContactForm(forms.Form):
    subject = forms.CharField(max_length=100)
    message = forms.CharField(widget=forms.Textarea)
    sender = forms.EmailField()
    cc_myself = forms.BooleanField(required=False)
__ form.non_field_errors __
<!--  the template lookup for errors on each field. -->
<div class="fieldWrapper">
  __ form.subject.errors __
  <label for="__ form.subject.id_for_label __">Email subject:</label>
  __ form.subject __
</div>
<div class="fieldWrapper">
  __ form.message.errors __
  <label for="__ form.message.id_for_label __">Your message:</label>
  __ form.message __
</div>
<div class="fieldWrapper">
  __ form.sender.errors __
  <label for="__ form.sender.id_for_label __">Your email address:</label>
  __ form.sender __
</div>
<div class="fieldWrapper">
  __ form.cc_myself.errors __
  <label for="__ form.cc_myself.id_for_label __">CC yourself?</label>
  __ form.cc_myself __
</div>

Example: Building a form in Django

from django import forms

class NameForm(forms.Form):
    your_name = forms.CharField(label="Your name", max_length=100)
from django.http import HttpResponseRedirect
from django.shortcuts import render

from .forms import NameForm

def get_name(request):
    # if this is a POST request we need to process the form data
    if request.method == "POST":
        # create a form instance and populate it with data from the request:
        form = NameForm(request.POST)
        # check whether it's valid:
        if form.is_valid():
            # process the data in form.cleaned_data as required
            # ...
            # redirect to a new URL:
            return HttpResponseRedirect("/thanks/")

    # if a GET (or any other method) we'll create a blank form
    else:
        form = NameForm()

    return render(request, "name.html", {"form": form})
<form action="/your-name/" method="post">
  __ csrf_token __ __ form __
  <input type="submit" value="Submit" />
</form>

Form Class

Method/Attribute Description
form_name() Constructs an unbound form
form_name(data) Constructs an bound form
get_initial_for_field() Returns the initial data for a form field.
is_bound Whether a form is bounded.
initial Declare the initial value of form fields
fields access the fields of Form instance
Method/Attribute Description
clean() Implement custom validation for fields
is_valid() Run validation and return a boolean
errors Returns errors in a dictionary.
errors.as_data() Returns errors with original ValidationError instances.
errors.as_json() Returns errors serialized as JSON.
errors.get_json_data() Returns errors as a dictionary suitable for JSON
add_error() Ads errors to specific fields
has_error() Whether a field has an error
non_field_errors() the list of errors not associated with any particular field
cleaned_data Return a dictionary contains only the valid fields defined in the Form,
error_css_class CSS class name for field error
required_css_class CSS class name for required field
Method/Attribute Description
has_changed() check if the form data has been changed from the initial data.
changed_data Returns a list of the names of the fields that have been changed.
# exmaple:

f = ContactForm(request.POST, initial=data)
if f.has_changed():
    print("The following fields changed: %s" % ", ".join(f.changed_data))
f.changed_data
Method/Attribute Description
render() The render method is called
get_context() Return the template context
template_name The name of the template rendered
template_name_label The template used to render a field’s <label>,
auto_id control <label> tags nor id attributes
label_suffix append a string after any <label> tags name
Output options Description
as_div wrapped in <div> tags.
as_table wrapped in <table> tags.
as_p wrapped in <p> tags.
as_ul wrapped in <ul> tags.

TOP