Django表单字段不显示

2024-06-10 21:50:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在视图中显示简单的搜索表单

forms.py:

from django import forms
from django.utils.translation import gettext_lazy as _

class Vehicle_Search_by_VIN(forms.Form):
    vin = models.CharField(max_length=17)
    first_registration_date = models.DateField()

class Vehicle_Search_by_Plate(forms.Form):
    plate = models.CharField(max_length=7)
    last_four_diggits_of_vin = models.DateField(max_length=4)

视图。py:

from django.shortcuts import render
from django.views import View
from .forms import *


class VehicleSearch(View):
    template = 'vehicle_search_template.html'
    cxt = {
        'Search_by_VIN': Vehicle_Search_by_VIN(),
        'Search_by_Plate': Vehicle_Search_by_Plate()
    }
    def get(self, request):
        return render(request, self.template, self.cxt)

我的模板文件:

<form class="by_vin" method="POST" action="">
        {% csrf_token %}
        {{ Search_by_VIN.as_p }}
    
        <button name='action' value='login' type="submit">Suchen</button>
</form>
    
    <form class="by_plate" method="POST" action="">
        {% csrf_token %}
        {{ Search_by_Plate.as_p }}
    
        <button name='action' value='signup' type="submit">Suchen</button>
    </form>

但因此,视图中仅显示提交按钮。有人知道为什么我的表格没有被呈现吗


Tags: djangofromimportform视图searchbymodels
2条回答

尝试在模板变量中提供完整路径,例如,如果您的应用程序名称是my_app,则template = 'my app/vehicle_search_template.html'

views.py中,我认为在get()函数中缺少了*args**kwargs参数

class VehicleSearch(View):

    template = 'vehicle_search_template.html'

    cxt = {
        'Search_by_VIN': Vehicle_Search_by_VIN(),
        'Search_by_Plate': Vehicle_Search_by_Plate()
    }

    def get(self, request, *args, **kwargs):  # HERE
        return render(request, self.template, self.cxt)

更新

默认情况下,基于类的视图只支持每个视图的单个表单,但根据您的逻辑,您可以使用很少的选项来克服此限制。请参阅此线程Django: Can class-based views accept two forms at a time?

相关问题 更多 >