top of page

Example of How to Create a form in Django. - codeswithpankaj


First, make sure you have Django installed. You can install it using pip:



pip install Django

Once you have Django installed, follow these steps to create a form:


Step 1: Create a Django project and app

Open your terminal or command prompt and navigate to the desired directory where you want to create your Django project. Then run the following command to create a new Django project:


django-admin startproject myproject

Navigate into the project directory:


cd myproject

Next, create a new Django app using the following command:


python manage.py startapp myapp
Step 2: Define the form

Open the `myapp` directory and create a new file called `forms.py`. In this file, define your form using Django's `forms.Form` class. Here's an example of a simple contact form:



from django import forms

class ContactForm(forms.Form):
    name = forms.CharField(max_length=100)
    email = forms.EmailField()
    message = forms.CharField(widget=forms.Textarea)

In this example, we have a form with three fields: `name`, `email`, and `message`.


Step 3: Create a view

Open the `views.py` file in the `myapp` directory and define a view function to handle the form submission. Here's an example:


from django.shortcuts import render
from .forms import ContactForm

def contact(request):
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            # Process the form data
            name = form.cleaned_data['name']
            email = form.cleaned_data['email']
            message = form.cleaned_data['message']
            # Do something with the form data (e.g., save to database)
            # ...
            # Redirect to a success page
            return render(request, 'success.html')
    else:
        form = ContactForm()
    
    return render(request, 'contact.html', {'form': form})
    

In this example, we check if the request method is POST, which indicates that the form has been submitted. If the form is valid, we can access the cleaned data using `form.cleaned_data` and perform any desired actions with it (e.g., save it to a database). If the form is not valid, it will be redisplayed with validation errors.


Step 4: Define URL patterns

Open the `urls.py` file in the project directory (`myproject`) and add a URL pattern for the `contact` view. Here's an example:


from django.urls import path
from myapp.views import contact

urlpatterns = [
    path('contact/', contact, name='contact'),
]

Step 5: Create templates

Create two HTML templates: `contact.html` and `success.html`. In the `contact.html` template, you can display the form using Django template tags. Here's an example:



<form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">Submit</button>
</form>

The `form.as_p` method will render the form fields as paragraphs.


In the `success.html` template, you can display a success message or any other content you want to show after the form has been successfully submitted.


That's it! You've created a form in Django. You can run the development server using the following command:



python manage.py runserver

Then you can access the form in your browser by visiting `http://localhost:8000/contact/`.


Remember to replace `myproject` and `myapp` with your project and app names, respectively.

Related Posts

See All

Django CRUD (Create, Retrieve, Update, Delete)

Step 1: Create the Django project and app Open your terminal (or command prompt) and run the following commands: # Create the Django project django-admin startproject crud_project cd crud_project # C

Commentaires


bottom of page