How I Created a Easy Contact Web page in Python Django – Be on the Proper Facet of Change

Advertisements

[ad_1]

Excessive-Degree Method

Making a contact web page in Django entails creating a brand new app, including it to the undertaking settings, and defining a mannequin for the contact kind. You then create a kind for the mannequin, a view to deal with kind submission and show, and a URL for the view. Lastly, you create templates for the shape and successful web page, and run the server to view your contact kind.

Right here’s a step-by-step information:

Step 1: Create a brand new Django app

First, it’s essential to create a brand new Django app. In your terminal, navigate to your Django undertaking listing and run the next command:

python handle.py startapp contact

This may create a brand new Django app named ‘contact‘.

Step 2: Add the app to your undertaking settings

Open your Django undertaking’s settings file (normally settings.py) and add your new app to the INSTALLED_APPS listing:

INSTALLED_APPS = [
    ...
    'contact',
    ...
]

Step 3: Create a mannequin for the contact kind

Within the fashions.py file of your new app, create a mannequin for the contact kind. This mannequin will outline the fields of the shape.

Right here’s a fundamental instance:

from django.db import fashions

class Contact(fashions.Mannequin):
    title = fashions.CharField(max_length=100)
    e-mail = fashions.EmailField()
    message = fashions.TextField()

Step 4: Create a kind for the mannequin

In the identical listing, create a brand new file named varieties.py and outline a kind to your mannequin:

from django import varieties
from .fashions import Contact

class ContactForm(varieties.ModelForm):
    class Meta:
        mannequin = Contact
        fields = ['name', 'email', 'message']

Step 5: Create a view for the shape

Within the views.py file of your app, create a view to your kind:

from django.shortcuts import render
from .varieties import ContactForm

def contact_view(request):
    if request.technique == 'POST':
        kind = ContactForm(request.POST)
        if kind.is_valid():
            kind.save()
            return render(request, 'contact/success.html')
    else:
        kind = ContactForm()
    return render(request, 'contact/contact.html', {'kind': kind})

This view will show the contact kind when the web page is visited, and it’ll save the shape information when the shape is submitted.

Step 6: Create a URL for the view

Within the urls.py file of your app, create a URL to your view:

from django.urls import path
from .views import contact_view

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

Step 7: Create templates for the shape and the success web page

In your app’s templates listing (you may must create it), create a brand new listing named ‘contact’ and inside it, create two HTML information: contact.html and success.html. The contact.html file ought to include the shape, and the success.html file ought to include a message that shall be displayed when the shape is efficiently submitted.

Step 8: Run the server

Lastly, run your server with python handle.py runserver and go to http://localhost:8000/contact/ to see your contact kind.

Bear in mind to interchange ‘contact‘ with the precise title of your app if it’s totally different. Additionally, this can be a very fundamental instance. In a real-world utility, you’d in all probability wish to add extra options, like sending an e-mail when the shape is submitted, validating the shape information, and many others.

Instance: Portfolio Web site Django

We’ll create a contact web page so anybody who desires to move info or recommendations can attain us. We’ve got already created a contact web page whereas constructing a portfolio web site utilizing Django. Please undergo that tutorial for extra rationalization as a result of we are going to do precisely what we did there.

Add this Contact class to your fashions.py file:

from datetime import datetime

class Contact(fashions.Mannequin):
    title = fashions.CharField(max_length=50)
    topic = fashions.CharField(max_length=200)
    e-mail = fashions.EmailField()
    submitted_on = fashions.DateTimeField(default=datetime.now)
    message = fashions.TextField()

    def __str__(self):
        return self.title

Carry out migrations and proceed to create a ContactForm class in your varieties.py file.

class ContactForm(varieties.ModelForm):
    title = varieties.CharField(widget=varieties.TextInput(attrs={'placeholder': 'Title'}))
    e-mail = varieties.EmailField(widget=varieties.TextInput(attrs={'placeholder': 'E mail'}))
    topic = varieties.CharField(widget=varieties.TextInput(attrs={'placeholder': 'Topic'}))
    message = varieties.CharField(widget=varieties.Textarea(attrs={'placeholder': 'Message'}))

    class Meta:
        mannequin = Contact
        fields = ('title', 'e-mail', 'topic', 'message')

For the admin interface, let’s create the category in admin.py file.

class ContactAdmin(admin.ModelAdmin):
    list_display = ('title', 'e-mail', 'topic', 'message')

admin.web site.register(Contact, ContactAdmin)

Make sure to import all the mandatory modules. For the view operate:

from django.views.generic import CreateView
from django.contrib.messages.views import SuccessMessageMixin
from .varieties import ContactForm
from django.contrib import messages
from django.http import HttpResponseRedirect
from django.urls import reverse_lazy

class ContactView(SuccessMessageMixin, CreateView):
    form_class = ContactForm
    success_url = reverse_lazy('index')
    template_name="contact.html"
    success_message="Your message was submitted efficiently"

    def form_invalid(self, kind):
        message.error(self.request, 'An unknown error has occurred!')
        return HttpResponseRedirect('')

let’s now create the template utilizing the title we specified within the ContactView class.

{% extends 'base.html' %}

{% block content material %}

<div class="col-md-8 card mb-4 mt-3">
      <h1 align="middle">Contact Type</h1>
      <hr>
      <p>We wish to hear from you. Please fill out this contact kind for recommendations.</p>
      <hr>
      <br>
      <kind technique="submit">
        {% csrf_token %}
        {{ kind.as_p }}
        <button sort="submit" class="btn btn-primary btn-lg">Submit</button>
     </kind>
 </div>
{% endblock %}

You might be free to make use of the Django crispy varieties as demonstrated in that undertaking. For the endpoint, it will likely be like this:

path('contact', ContactView.as_view(), title="contact"),

[ad_2]