Django 中的表單小元件


在本文中,我們將瞭解如何在 Django 表單中使用小元件。小元件對於改進前端非常有幫助。小元件是 Django 表單呈現的 html 元素,文字框、輸入框、密碼輸入框等,都是小元件。

首先,讓我們建立一個 Django 專案和一個應用程式。我使用名稱“tutorial14”建立了該專案,並使用名稱“djangoFormWidget”建立了該應用程式。

settings.py中新增應用程式,並在專案的urls.py中包含應用程式的 URL。

建立所有基本檔案和資料夾,如 Templates、home.html、forms.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>

這是一個簡單的前端,我們在此呈現我們的表單。

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 表單小部件來呈現表單中的文字區域。

輸出

更新於: 25-8-2021

942 次瀏覽

開啟您的職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.