style django forms with crisp

  1. Import necessary modules and classes:
from django import forms
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Submit
  1. Create a form class, inheriting from forms.Form:
class YourForm(forms.Form):
    your_field = forms.CharField(label='Your Field')
    # Add more fields as needed
  1. Initialize the FormHelper in the form's __init__ method:
class YourForm(forms.Form):
    def __init__(self, args, *kwargs):
        super(YourForm, self).__init__(args, *kwargs)
        self.helper = FormHelper()
        self.helper.form_method = 'post'
        self.helper.add_input(Submit('submit', 'Submit'))
  1. Define the form layout using the Layout class:
class YourForm(forms.Form):
    def __init__(self, args, *kwargs):
        super(YourForm, self).__init__(args, *kwargs)
        self.helper = FormHelper()
        self.helper.form_method = 'post'
        self.helper.add_input(Submit('submit', 'Submit'))

        self.helper.layout = Layout(
            'your_field',
            # Add more fields as needed
        )
  1. In your Django template, load crispy_forms_tags and render the form using {% crispy form %}:
{% load crispy_forms_tags %}

<form method="post" action="{% url 'your_view_name' %}">
    {% csrf_token %}
    {% crispy form %}
</form>

Make sure to replace 'your_view_name' with the actual name of your view.

  1. In your Django view, handle the form submission:
from django.shortcuts import render, redirect
from .forms import YourForm

def your_view(request):
    if request.method == 'POST':
        form = YourForm(request.POST)
        if form.is_valid():
            # Process form data as needed
            return redirect('success_view')
    else:
        form = YourForm()

    return render(request, 'your_template.html', {'form': form})

Replace 'success_view' with the name of the view to redirect to upon successful form submission.