dnestoff
11/16/2016 - 3:50 AM

Python: Django Forms

# rango/views.py

# below process both GET and POST requests
def add_category(request):
    # a POST request?
    if request.method == 'POST':
        form = CategoryForm(request.POST)

        if form.is_valid():
            form.save(commit = True)
            return index(request)
        else:
            print(form.errors)
    else:
        form = CategoryForm()

    return render(request, "rango/add_category.html", {'form': form})
# rango/forms.py

from django import forms
from rango.models import Category, Page

class CategoryForm(forms.ModelForm):
  name = forms.CharField(max_length=128, help_text="Please enter a category name")
  views = forms.IntegerField(widget=forms.HiddenInput(), initial = 0)
  likes = forms.IntegerField(widget=forms.HiddenInput(), initial = 0)
  slug = forms.CharField(widget=forms.HiddenInput(), required=False)

  class Meta:
    model = Category
    # tuple specifying the classes we want to use
    fields = ('name', )

class PageForm(forms.ModelForm):
  title = forms.CharField(max_length=128, help_text="Please enter the title of the page.")
  url = forms.URLField(max_length=200, help_text="Please enter the URL of the page.")
  views = forms.IntegerField(widget=forms.HiddenInput(), initial=0)

  class Meta:
    model = Page
    # excluding the category foreign key field from the form
    exclude = ('category', )
<!-- templates/rango/add_category.html-->

<body>
    <h1>Add a Category</h1>

    <form id="category_form" method="post" action="/rango/add_category/">

        {% csrf_token %}
        {% for hidden in form.hidden_fields %}
            {{ hidden }}
        {% endfor %}

        {% for field in form.visible_fields %}
            {{ field.errors }}
            {{ field.help_text }}
            {{ field }}
        {% endfor %}

        <input type="submit" name="submit" value="Create Category" />
    </form>
</body>

(If you haven’t already got one, create a forms.py file within your Django application’s directory to store form-related classes.)

  1. Create a ModelForm class for each model that you wish to represent as a form.
  2. Customise the forms as you desire.
  3. Create or update a view to handle the form - including displaying the form, saving the form data, and flagging up errors which may occur when the user enters incorrect data (or no data at all) in the form.
  4. Create or update a template to display the form.
  5. Add a urlpattern to map to the new view (if you created a new one).