ใน Django สร้าง Contact Form ได้ง่าย แต่ต้องจัดการหลายอย่าง: forms, views, models, register admin บทความนี้ใช้แพ็กเกจสำเร็จรูปสำหรับ Contact Form ที่เก็บข้อมูลในโมเดลสำเร็จรูป
จะสร้าง Contact Form ที่เก็บข้อมูลในโมเดลโดยไม่เขียนโค้ดใน models.py, views.py หรือ html ใดๆ
ตัวอย่าง
สร้างโปรเจกต์และแอป
ติดตั้ง django-contactforms:
pip install django-contactforms
ใน settings.py:
INSTALLED_APPS+=["contactforms"]
ใน urls.py ของโปรเจกต์:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('contactforms.urls')),
path("aftercontact", include('MyForm.urls'))
]
สร้าง 2 URL endpoints: หนึ่งสำหรับ contact form อีกหนึ่ง redirect หลัง submit
ใน urls.py ของแอป:
from django.urls import path, include
from . import views
urlpatterns = [
path('', views.home, name="home"),
]
ใน views.py:
from django.shortcuts import render
def home(request):
return render(request, "home.html")
สร้างโฟลเดอร์ templates/contact/contact.html:
<!DOCTYPE html> <html>
<body>
<div class="row">
<form action="{% url 'contact' %}" method="post">
<h3>Send a Message</h3>
{% csrf_token %}
<div class="form-group">
{% if messages %}
{% for message in messages %}
<span{% if message.tags %} class="{{ message.tags }}"{% endif %} style="color: green">
{{ message }}
</span>
{% endfor %} {% endif %}
</div>
<div class="form-group">{{ forms.name }}</div>
<div class="form-group">{{ forms.email }}</div>
<div class="form-group">{{ forms.subject }}</div>
<div class="form-group">{{ forms.message }}</div>
<button class="btn btn-primary" type="submit">Submit</button>
</form>
</div>
</body> </html>
สร้าง templates/home.html (นอกโฟลเดอร์ contact):
<!DOCTYPE html> <html>
<head><title>tut</title></head>
<body>
<h3>Successfull</h3>
</body> </html>
เอาต์พุต
