Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Django – จัดการหลาย Form ใน View เดียว


บางครั้งต้องจัดการหลาย Forms ในฟังก์ชันหรือ View เดียว บทความนี้สอนเขียนฟังก์ชันจัดการ 2 Forms พร้อมกันใน View เดียว ใช้ได้กับมากกว่า 2 Forms ด้วย

ตัวอย่าง

สร้างโปรเจกต์ "multipleFormHandle" และแอป "formhandlingapp"

ตั้งค่าพื้นฐาน เพิ่มแอปใน INSTALLED_APPS include urls

สร้าง forms.py และโฟลเดอร์ templates/home.html

ติดตั้ง multi-form_view:

pip install multi_form_view

ใน urls.py ของแอป:

from django.urls import path, include
from . import views
urlpatterns = [
    path('', views.SchoolData.as_view(), name='home'),
]

ใช้ ViewSet เป็น View

ใน models.py:

from django.db import models
class StudentData(models.Model):
    name = models.CharField(max_length=100)
    standard = models.CharField(max_length=100)
    section = models.CharField(max_length=100)

class TeachertData(models.Model):
    name = models.CharField(max_length=100)
    ClassTeacherOF = models.CharField(max_length=100)
    Salary = models.CharField(max_length=100)

สร้าง 2 โมเดล สำหรับบันทึกข้อมูลฟอร์ม

ใน forms.py:

from django import forms
from .models import TeachertData, StudentData

class StudentForm(forms.ModelForm):
    class Meta:
        model = StudentData
        fields = "__all__"

class TeacherForm(forms.ModelForm):
    class Meta:
        model = TeachertData
        fields = "__all__"

ใน home.html:

<!DOCTYPE html> <html>
<head> <title>tut</title> </head>
<body>
    <form method="post" enctype="multipart/form-data">
        {% csrf_token %}
        <label><h3>Teacher</h3></label>
        {{ forms.teacher_form.as_p }}
        <label><h3>Student</h3></label>
        {{ forms.student_form.as_p }}
        <input type="submit" value="submit"/>
    </form>
</body> </html>

Render 2 Forms ภายใต้ form element เดียว ปุ่ม submit เดียว

ใน views.py:

from django.shortcuts import render
from .forms import StudentForm, TeacherForm
from django.views.generic.list import ListView
from django.urls import reverse
from multi_form_view import MultiModelFormView

class SchoolData(MultiModelFormView):
    form_classes = {
        'student_form': StudentForm,
        'teacher_form': TeacherForm,
    }
    template_name = 'home.html'
    def get_success_url(self):
        return reverse('home')
    def forms_valid(self, forms):
        student = forms['student_form'].save(commit=False)
        teacher = forms['teacher_form'].save(commit=False)
        return super(SchoolData, self).forms_valid(forms)

สร้าง ViewSet กำหนด 2 forms template success_url และ forms_valid สำหรับบันทึกและตรวจสอบ

เอาต์พุต

Django – จัดการหลาย Form ใน View เดียว