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>
Django forms are created using HTML.
<form><input type="text" placeholder="Search"/><input type="submit" value="Submit" / ></form>"
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 data is sent to the application when the submit
input is clicked.
<input type="submit" value="submit" />
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 datareturn render(request, 'contact.html', {'form': form,})
Form data can be accessed using dot notation and bracket notation.
test_model.field = request.POST["field_from_html"]
The model must be imported into views.py in order to manipulate or create a model instance.
from .models import Model_Namedef 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')
Forms can be created using generic types inside a file named forms.py.
myProject/└── myApp/└── forms.py
Forms must be imported as well as the classes to be used in the application.
from django import formsclass TestForm(forms.ModelForm):# Info for TestForm goes here
Class properties must be assigned to a field from forms
.
from django import formsclass TestForm(forms.ModelForm):class Meta:model = Test
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_Namedef 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'
Multiple forms can be created in forms.py and require a system of organization to keep it easy to read.
myProject/└── myApp/└── forms.py