Django Forms

Django Forms

Welcome to my .py series where I take you through what I learn weekly at She Code Africa Mentorship program Cohort 2-Python track. You can check below for other episodes.

This episode is about Django Forms

It's beautiful that Django always has a way to make our work easy. It is true that Django is a framework for developers with deadlines. In this article, we will be going through Django forms basics and how to create a simple Django form to post articles for a blog app.

Let's think HTML format of forms for a second,

In HTML, a form is a collection of elements inside <form>...... </form> that allows a visitor to do things like entering text, select options, manipulate objects or controls, and so on, then send that information back to the server.

Django's form functionality simplifies and automates vast portions of handling form in a secure way.

You can code your own form, but using Django forms makes your work secure and faster.

Django handles three distinct parts of the work involved in forms:

  • Preparing and restructuring data to make it ready for rendering

  • Creating HTML forms for the data

  • Receiving and processing submitted forms and data from the client.

Now let's create a simple form for creating articles in a blog app. Remember Django makes things really easy for us. Let's utilize that here instead of coding from scratch. We are going to be using Django's generic based editing view (used to provide the foundation for editing content) called CreateView.

CreateView is a view that displays a form for creating an object, redisplaying the form with validation errors (if there are any), and saving the object.

Step 1

Navigate to the views.py file under app

from django.shortcuts import render
from .models import Article
from django.views.generic import CreateView
from django import forms

class CreateArticle(CreateView):
    model = Article
    template_name = 'blog/form.html'
    fields = ['title', 'text']

    def form_valid(self, form):
        # This method is called when valid form data has been POSTed
        form.instance.author = self.request.user
        return super().form_valid(form)

Step 2

Create a URL pattern for the view, navigate to the urls.py file under app

from django.urls import path
from .views import CreateArticle

urlpatterns = [
   path('CreateArticle/', CreateArticle.as_view(success_url = '/')) 
]

Step 3

Create a template to render the view. Navigate to the templates folder under app and create a file, form.html

{% extends "blog/base.html" %}

{% block content %}

<div class="container">
      <h1 class="my-4 ml-4">Share Your Experience</h1>

      <form method = "POST">
          {% csrf_token %}
          {{ form.as_p }}
          <button type = "submit" class = "submit ml-4" >Submit</button>
      </form>

</div>
{% endblock %}

The csrf_token template tag provides easy-to-use protection against Cross-Site Request Forgeries. This type of attack occurs when a malicious website contains a link or a form button intended to perform some actions on your website, using the credentials of a logged-in user who visits the malicious website in their browser.

{{ form.as_p }} indicates that all the form's fields and attributes will be unpacked into the HTML markup form.

Step 4

Run server to see the beautiful create article form like mine:

python manage.py runserver

a123.png

Thanks for reading!

References