Forms

Django uses forms are used to get user input and works similarly to HTML forms.

<form action="""" method=""POST""> <input id=""your_input"" type=""text"" name=""your_input"" value=""{{ current_input }}""> <input type=""submit"" value=""OK""> </form>

Form Creation

Django forms are created using HTML.

<form> <input type="text" placeholder="Search"/> <input type="submit" value="Submit" / > </form>"

Form Attributes

The <form>‘s action attribute should be set as "" and the method set as "POST". There must be an input type of "submit" included in the <form> tags.

<form action="" method="POST"> <input id="your_input" type="text" name="your_input" value="{{ current_input }}"> <input type="submit" value="OK"> </form>

Form Submission

Form data is sent to the application when the submit input is clicked.

<input type="submit" value="submit" />

Checking Request Types

Inside the view function, a request method is checked with a conditional statement.

def contact(request): if request.method == 'POST': # Check for method type # Add logic for manipulating form data return render(request, 'contact.html', { 'form': form, })

Getting POST Data

Form data can be accessed using dot notation and bracket notation.

test_model.field = request.POST["field_from_html"]

Using Form Data for Models

The model must be imported into views.py in order to manipulate or create a model instance.

from .models import Model_Name def renderTemplate(request): if request.method == "POST": test_model = new Model_Name() test_model.field = request.POST["field_from_html"] test_model.save() return render(request, 'template_name.html')

Generic Forms

Forms can be created using generic types inside a file named forms.py.

myProject/ └── myApp/ └── forms.py

Import Forms

Forms must be imported as well as the classes to be used in the application.

from django import forms class TestForm(forms.ModelForm): # Info for TestForm goes here

Forms Class

Class properties must be assigned to a field from forms.

from django import forms class TestForm(forms.ModelForm): class Meta: model = Test

Form Redirections

Users can be redirected to a success page after form submission to reduce the chances of a form being submitted more than once.

from .models import Model_Name def renderTemplate(request): if request.method == 'POST': test_model = new Model_Name() test_model.field = request.POST[""field_from_html""] test_model.save() return render(request, 'submit_success.html') return render(request, 'template_name.html'

forms.py Organization

Multiple forms can be created in forms.py and require a system of organization to keep it easy to read.

myProject/ └── myApp/ └── forms.py