article

Thursday, June 18, 2020

Django Crispy Forms Advanced Form Rendering


Django Crispy Forms Advanced Form Rendering

Install it using pip:

pip install django-crispy-forms

Add it to your INSTALLED_APPS and select which styles to use:

settings.py

INSTALLED_APPS = [
    'crispy_forms',
]


CRISPY_TEMPLATE_PACK = 'bootstrap4' views.py
#views.py
from django.shortcuts import render, redirect

from myapp.forms import RegsitrationForm

def home(request):
    if request.method == 'POST':
        form = RegsitrationForm(request.POST)
        if form.is_valid():
            #form.save()
            messages.success(request, 'New success!')
            return redirect('/home')
        else:
            messages.error(request, 'Invalid Please try again.')
    else:
        form = RegsitrationForm()
    return render(request, 'home.html', {'form': form})
 
def form2(request):
    if request.method == 'POST':
        form = RegsitrationForm(request.POST)
        if form.is_valid():
            #form.save()
            messages.success(request, 'New success!')
            return redirect('/form2')
        else:
            messages.error(request, 'Invalid Please try again.')
    else:
        form = RegsitrationForm()
    return render(request, 'form2.html', {'form': form})
settings.py settings.py
#settings.py
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    
    'crispy_forms', #pip install django-crispy-forms
    'myapp',
]

CRISPY_TEMPLATE_PACK = 'bootstrap4'
#forms.py
from django import forms

STATES = (
    ('', 'Choose...'),
    ('CA', 'California'),
    ('AK', 'Alaska'),
    ('AZ', 'Arizona')
)

class RegsitrationForm(forms.Form):
    email = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Email'}))
    password = forms.CharField(widget=forms.PasswordInput())
    address_1 = forms.CharField(
        label='Address',
        widget=forms.TextInput(attrs={'placeholder': '1234 Main St'})
    )
    address_2 = forms.CharField(
        widget=forms.TextInput(attrs={'placeholder': 'Apartment, studio, or floor'})
    )
    city = forms.CharField()
    state = forms.ChoiceField(choices=STATES)
    zip_code = forms.CharField(label='Zip')
    check_me_out = forms.BooleanField(required=False)
urls.py
#urls.py
from django.contrib import admin  
from django.urls import path
from myapp import views  
from django.conf.urls import url

urlpatterns = [
    path('admin/', admin.site.urls),
    path('home/', views.home, name='home'),
    path('form2/', views.form2, name='form2'),
]
templates/home.html
//templates/home.html
{% extends 'base.html' %}
{% block title %}Form Example 1 - Basic Crispy Form Rendering {% endblock %}

{% load crispy_forms_tags %}

{% block content %}
  <h2>Form Example 1 - Basic Crispy Form Rendering</h2>
  <form method="post" novalidate>
    {% csrf_token %}
    {{ form|crispy }}
    <button type="submit">Register</button>
  </form>
{% endblock %}
templates/home.html
//templates/base.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1"/>
 <title>{% block title %}Django Crispy Forms Advanced Form Rendering {% endblock %}</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
  <a class="navbar-brand" href="{% url 'home' %}">Cairocoders</a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>
  <div class="collapse navbar-collapse" id="navbarNavAltMarkup">
    <div class="navbar-nav">
   <a class="nav-item nav-link active" href="">Home <span class="sr-only">(current)</span></a>
      <a class="nav-item nav-link" href="">Form 1</a>
      <a class="nav-item nav-link" href="">Form 2</a>
    </div>
  </div>
</nav>
 <div class="container" style="padding:20px;">
    <div class="col-md-12 well">
        <h3 class="text-primary">Django Crispy Forms Advanced Form Rendering</h3>
        <hr style="border-top:1px dotted #ccc;"/>
  {% block content %} {% endblock %}
    </div>
    </div> 
</body>
</html>
//templates/form2.html
{% extends 'base.html' %}
{% block title %}Form Example 2 - Custom Fields Placement {% endblock %}

{% load crispy_forms_tags %}

{% block content %}
  <h2>Form Example 2 - Custom Fields Placement</h2>
  <form method="post">
    {% csrf_token %}
    <div class="form-row">
      <div class="form-group col-md-6 mb-0">
        {{ form.email|as_crispy_field }}
      </div>
      <div class="form-group col-md-6 mb-0">
        {{ form.password|as_crispy_field }}
      </div>
    </div>
    {{ form.address_1|as_crispy_field }}
    {{ form.address_2|as_crispy_field }}
    <div class="form-row">
      <div class="form-group col-md-6 mb-0">
        {{ form.city|as_crispy_field }}
      </div>
      <div class="form-group col-md-4 mb-0">
        {{ form.state|as_crispy_field }}
      </div>
      <div class="form-group col-md-2 mb-0">
        {{ form.zip_code|as_crispy_field }}
      </div>
    </div>
    {{ form.check_me_out|as_crispy_field }}
    <button type="submit" class="btn btn-primary">Sign in</button>
  </form>
{% endblock %}

Related Post