ในบทความนี้ เราจะมาดูวิธีการใช้วิดเจ็ตในรูปแบบ Django วิดเจ็ตอาจช่วยทำให้ฟรอนท์เอนด์ดีขึ้นได้ วิดเจ็ตคือองค์ประกอบ html ที่แสดงผลจากแบบฟอร์ม Django, textarea, อินพุต, การป้อนรหัสผ่าน ฯลฯ ทั้งหมดเป็นวิดเจ็ต
ขั้นแรก มาสร้างโปรเจ็กต์ Django และแอพกันก่อน ฉันสร้างโครงการด้วยชื่อ "tutorial14" และแอปชื่อ "djangoFormWidget" .
เพิ่มแอปใน settings.py และรวม URL ของแอปในโครงการ urls.py.
สร้างไฟล์และโฟลเดอร์พื้นฐานทั้งหมด เช่น เทมเพลต home.html, form.py
ตัวอย่าง
ใน urls.py ของแอป −
from django.urls import path,include
from . import views
urlpatterns = [
path('',views.home,name="home")
] มันจะสร้าง URL พื้นฐานสำหรับการแสดงผลมุมมอง
ใน views.py −
from django.shortcuts import render
from .forms import CommentForm
# Create your views here.
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}) ที่นี่ เรานำเข้าแบบฟอร์มของเราและจัดการคำขอ POST และ GET
ใน POST เราบันทึกข้อมูลและใน GET เราจะส่งแบบฟอร์มไปยังส่วนหน้า
ใน models.py −
from django.db import models # Create your models here. 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> เป็น frontend แบบง่ายๆ ที่เราใช้แสดงแบบฟอร์ม
ใน forms.py −
from django import forms
from .models import CommentModel
class CommentForm(forms.Form):
comment=forms.CharField(widget=forms.Textarea(attrs={'class':'comment','title':'add comment'})) # this is the line which is used for widget, here I added TextArea widget you can see we also assigned class to widget using attrs attribute.
def save(self):
data=self.data
modelRef=CommentModel(comment=data['comment'])
modelRef.save() เป็นที่ที่เราสร้างแบบฟอร์มของเรา เราใช้วิดเจ็ตแบบฟอร์ม Django ในตัวเพื่อแสดงพื้นที่ข้อความในแบบฟอร์ม
ผลลัพธ์
