Adding a Form to a Page - makersacademy/simpleassettracker GitHub Wiki

Add Form

This project uses bootstrap for fast and simple CSS layouts. Crispyforms is a package that allows easy form creation straight from the model.

Please find below an example of how a form template with bootstrap and crispyforms is written.

< register/register.html >

{% extends 'AssetTracker/base.html' %}

{% block title %}Create an Account{% endblock %}
{% load crispy_forms_tags %}

{% block content %}
    <form method="POST" class="form-group">
	{% csrf_token %}
	{{ form|crispy }}
	<button type="submit" class="btn btn-success">Register</button>
    </form>
{% endblock %}

Explanation of Terms

{% load crispy_forms_tags %} -> allows file to connect to crispy forms with the template pack bootstrap4 (as configured in settings/base.py)

{% csrf_token %} -> Security measure which can prevent CSRF attacks by making it impossible for an attacker to construct a fully valid HTTP request suitable for feeding to a victim user.

{{form|crispy}} -> starts a crispy form by looking in the forms.py file to see what model to use and which feilds to create. (see below)

<forms.py>

from django import forms

from django.contrib.auth.forms import UserCreationForm

from django.contrib.auth.models import User


class RegisterForm(UserCreationForm):
    email = forms.EmailField()

    class Meta:
        model = User
        fields = ("username", "email", "password1", "password2")

So our register.html file will produce a form with 4 feilds, A username, email and two password feilds.

Please nore that registration/login.html is a special case in django that magically knows that it handles logins, and so doesnt require a form.py file to work.

⚠️ **GitHub.com Fallback** ⚠️