บทความนี้สอนใช้ Widgets ใน Django Form Widgets ช่วยปรับปรุง Frontend ให้ดียิ่งขึ้น Widgets คือ HTML Elements ที่ render จาก Django Form เช่น textarea, input, password input
ตัวอย่าง
สร้างโปรเจกต์ "tutorial14" และแอป "djangoFormWidget"
เพิ่มแอปใน settings.py include urls
สร้างไฟล์พื้นฐาน: Templates, home.html, forms.py
ใน urls.py ของแอป:
from django.urls import path, include
from . import views
urlpatterns = [
path('', views.home, name="home")
]
ใน views.py:
from django.shortcuts import render
from .forms import CommentForm
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def home(request):
if request.method == 'POST':
form = CommentForm(request.POST)
if form.is_valid():
form.save()
commentform = CommentForm()
return render(request, 'home.html', {"commentform": commentform})
ใน models.py:
from django.db import models
class CommentModel(models.Model):
comment = models.CharField(max_length=500)
ใน home.html:
<!DOCTYPE html> <html>
<head> <title>TUT</title> </head>
<body>
{% for fm in commentform %}
<form method="post">
{% csrf_token %}
{{fm.errors}}<br>
{{fm.label}}:{{fm}}<br>
{% endfor %}
<button type="submit">Submit</button>
</form>
</body> </html>
ใน forms.py ใช้ Widget:
from django import forms
from .models import CommentModel
class CommentForm(forms.Form):
comment = forms.CharField(widget=forms.Textarea(attrs={'class': 'comment', 'title': 'add comment'}))
# ใช้ TextArea widget กำหนด class และ title ผ่าน attrs
def save(self):
data = self.data
modelRef = CommentModel(comment=data['comment'])
modelRef.save()
เอาต์พุต
