Django | Codecademy | Forms


Django Forms vs. HTML Forms


Django Forms look much like HTML forms, but Django uses a model based system to handle the data.

Form Security

<form>
  {% csrf_token %}
  ...
</form>

Form Validation


Form validation is also necessary to help defend out applications from possible attacks that use incorrect data types to cause problems (e.g. SQL attacks). This validation can include ensuring only specific data types are being submitted to protect our database.
views.py에서:

if form.is_valid():
  form = form.save()

Submitting a Form


In Django, we’ll be using the "POST" method when the form is submitted, which means all of the data from the forms will be sent to the POST method in views.py .
to differentiate how the view function should treat a POST request vs rendering the usual form, we use an if statement
  • This if statement checks that the request method is "POST"
  • from .models import Model_Name
     
    def renderTemplate(request):
      if request.method == "POST":
        test_model = Model_Name()
        test_model.field = request.POST["field_name"]
        test_model.save()
      return render(request, "template_with_form.html")
    Steps:
    1. check if the request.method is equal to "POST" .
  • When the method is "POST" , it means that the form was submitted which means that we can grab all the data and use it to create a new model instance.
  • Notice our test_model is a new Model_Name() .
  • We then assign the test_model.field a value of request.POST["field_name"] . This is because in our form, we had an input field with a name set to "field_name" .
  • The request.POST["field_name"] syntax shows that request is treated like a dictionary with a "field_name" property. Once all of the data from request.POST is added to the model, we can save the model and render the form again.
  • If our conditional isn’t met, it usually means that the form is being rendered for the first time, so we can skip the instance creation and just render the form as normal.