DEV Community

Serhan77
Serhan77

Posted on

Form submission

Hello everyone, I need some help. Im creating a website and I'd like it when a visitor visits the contact page and fills out a contact form it will go to a email address which will be configured with a hosting company. Any help on this subject will be much appreciated and many thanks in advance

Top comments (1)

Collapse
 
highcenburg profile image
Vicente G. Reyes

One of the easiest ways to create a form is like this:

models.py


from django.db import models

class Contact(models.Model):
    name = models.CharField(max_length=100)
    email = models.EmailField()
    message = models.CharField(max_length=999)

    def __str__(self):
        return self.name

forms.py

from django.forms import ModelForm

class ContactForm(ModelForm):
    required_css_class = "required"

    class Meta:
        model = Contact
        fields = "__all__"

views.py


from .models import Contact

def contactView(request):
    submitted = False
    if request.method == "POST":
        form = ContactForm(request.POST)
        if form.is_valid():
            form.save()
        return HttpResponseRedirect("?submitted=True")
    else:
        form = ContactForm()
        if "submitted" in request.GET:
            submitted = True

    return render(
        request,
        "contact.html",
        {"form": form, "page_list": Contact.objects.filter(), "submitted": submitted},
    )

You can learn more about handling forms on the documentation.