Django 3 : Create a Django form

Louis SanchezAugust 15th 2021, 7:25

Django forms work with an object that inherits from the Form class. This object will handle much of the work we have done manually in the previous post.

Step 1 : Add the following URL to your urls.py file:

path('create-profile-forms', views.create_profile_forms, name="create_profile_forms"),

Step 2 : We will create our view in the views.py file with the following lines:

from django.shortcuts import render
from myproject.models import UserProfile
from django.http import HttpResponse
from django import forms


class Form_inscription(forms.Form):  
    name = forms.CharField(label="Name", max_length=30)
    login      = forms.CharField(label="Login", max_length=30)
    password   = forms.CharField(label="Password", widget=forms.PasswordInput)
def create_profile_forms(request):
    if request.POST:
        form = Form_inscription(request.POST)
        if form.is_valid():
            name          = form.cleaned_data['name']
            login         = form.cleaned_data['login']
            password      = form.cleaned_data['password']
            new_profile = UserProfile(name=name, login=login, password=password)
            new_profile.save()
            return HttpResponse("UserProfile added")
        else:
            return render(request, 'create_profile_forms.html', {'form' : form})
    else:
        form = Form_inscription()
        return render(request, 'create_profile_forms.html', {'form' : form})

Step 3 : We set the template for this view. The template will be much shorter. The following is our template in template/create_profile_forms.html

{% extends "base.html" %}
{% block title_html %}
    Create Profile
{% endblock %}
{% block h1 %}
    Create Profile
{% endblock %}
{% block content %}
    <form method="post" action="{% url "create_profile_forms" %}" >
    {% csrf_token %}
        <table>
        {{ form.as_table }}
        </table>
    <p><input type="submit" value="Create" /></p>
  </form>
{% endblock %}

Step 4 : Now start the development server with the python manage.py runserver command and open http://127.0.0.1:8000/create-profile-forms in your browser.