Create a simple contact Form in Python Django

HermantoXYZ
2 min readMar 15, 2024

--

Read step by step guide.

  1. Create a models.py for the contact form.
class Contact(models.Model):
name = models.CharField(max_length=100)
email = models.EmailField(max_length=254)
phone_number = models.CharField(max_length=20)
message = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)

def __str__(self):
return self.name

2. Create a form.py for the model

class ContactForm(forms.ModelForm):
class Meta:
model = Contact
fields = ['name', 'email', 'phone_number', 'message']

3. Create view.py for the form contact.

def contact_form(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
form.save()
return redirect('contact_success')
else:
form = ContactForm()
return render(request, 'home/contact.html', {'form': form})

#AND VIEW FOR SUCCES PAGE

def contact_success(request):
return render(request, 'home/succes.html')

4. Create url.py for the view for contact.

 path('contact/', views.contact_form, name='contact_form'),
path('contact/success/', views.contact_success, name='contact_success'),

5. Create templates for the form and the success page

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Contact Form</title>
</head>
<body>
<h1>Contact Us</h1>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit</button>
</form>
</body>
</html>

Now, template for succes form contact

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>Succes Terkirim</h1>
</body>
</html>

List Contact Form..

Succes page html

--

--

No responses yet