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 file:

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

Step 2 : We will create our view in the 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)
            return HttpResponse("UserProfile added")
            return render(request, 'create_profile_forms.html', {'form' : form})
        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 %}
        {{ form.as_table }}
    <p><input type="submit" value="Create" /></p>
{% endblock %}

Step 4 : Now start the development server with the python runserver command and open in your browser.