在 __init__ 中设置字段的 QuerySet 后表单无效

问题描述 投票:0回答:1

通过访问

Workorder
页面并创建工单来创建新的
Building
。这又会在新页面上显示
WorkOrderForm
。 查看此表单时,我只想显示与建筑物关联的设备,而不是所有设备。

我尝试覆盖表单的

__init__
来设置
queryset
MultipleChoiceField
,它按预期显示与建筑物相关的设备,但是在提交表单时,
form.is_valid()
失败了,但还有没有显示错误。

我有3个型号

Building
WorkOrder
Equipment
如下:

建筑

class BuildingDetail(models.Model):
location_Code = models.CharField(primary_key=True, max_length=15, help_text='Enter a location code.', unique=True)

civic_Address = models.CharField(max_length=100, help_text='Enter the civic address of the location.')

current_Tenant = models.ForeignKey(Tenant, on_delete=models.CASCADE, help_text='Select a Tenant.')

landlord = models.ForeignKey(Landlord, on_delete=models.CASCADE, help_text='Select a Landlord.')

工单

class WorkOrder(models.Model):
id = models.CharField(primary_key=True, max_length=7, default=increment_workorder, verbose_name="ID")

building_Code = models.ForeignKey(BuildingDetail, on_delete=models.CASCADE)

issue_Date = models.DateField(blank=True, null=True, default=datetime.date.today())

completion_Date = models.DateField(blank=True, null=True)

tenant_Issue = models.TextField(help_text="Enter the issue description.")

scope_Of_Work = models.TextField(help_text="Enter the Scope of Work required.")

contact_name = models.CharField(max_length=50, help_text='Enter the contact Name.', blank=True, default="")

contact_number = models.CharField(max_length=11, help_text='Enter the contact Phone Number.', blank=True, default="")

rebill_Invoice = models.TextField(max_length=50, help_text='Enter the Devco Rebill Invoice number.', blank=True, default="")

rebill_Date = models.TextField(blank=True, null=True)

tenant = models.ForeignKey(Tenant, on_delete=models.CASCADE, null=True)

equipment = models.ManyToManyField(Equipment, blank=True, null=True, help_text='Select Equipment associated to this work order. Hold CTRL to select multiple.')

设备

class Equipment(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text='Unique ID for equipment.')

name = models.CharField(max_length=150, help_text='Enter a name for this piece of equipment.')

make = models.CharField(max_length=100, blank=True, help_text='Enter the Make of the item.')

model = models.CharField(max_length=100, blank=True, help_text='Enter the model of the item.')

serial = models.CharField(max_length=100, blank=True, help_text='Enter the serial number of the item.')

cost = models.DecimalField(max_digits=15, decimal_places=2, help_text='Enter the cost before GST.', blank=True, default=0)

building = models.ForeignKey(BuildingDetail, on_delete=models.CASCADE)

Forms.py

class WorkOrderForm(ModelForm):

class Meta:
    model = WorkOrder
    fields = '__all__'
    widgets = {
        "issue_Date": DatePickerInput(),
        "completion_Date": DatePickerInput(),
    }
def __init__(self, *args, **kwargs):
    building = kwargs.pop('building', None)
    super(WorkOrderForm, self).__init__(**kwargs)
    self.fields['equipment'].queryset = Equipment.objects.filter(building__location_Code=building)

Views.py

def CreateWorkOrder(request, building_code):
if building_code == "none":
    workOrderForm = WorkOrderForm()
    associatedCostsForm = AssociatedCostsForm()
    context = {
        'workOrderForm': workOrderForm,
        'associatedCostsForm': associatedCostsForm,
    }
else:
    building = BuildingDetail.objects.get(location_Code=building_code)
    equipment = Equipment.objects.filter(building=building)
    currentTenant = building.current_Tenant
    workOrderForm = WorkOrderForm(building=building_code, initial={
        'building_Code': building,
        'tenant': currentTenant})


    associatedCostsForm = AssociatedCostsForm()

    context = {
        'workOrderForm': workOrderForm,
        'associatedCostsForm': associatedCostsForm,
        'building_code': building_code,
        'building': building,
    }


if request.method == "POST":
    form = WorkOrderForm(request.POST)
    if 'submit-workorder' in request.POST:
        if form.is_valid():
            form.clean()
            workorder = form.save(commit=False)
            workorder.save()
            added_workorder = WorkOrder.objects.get(id=workorder.id)
            building = added_workorder.building_Code
            print(added_workorder)
            print("You have submitted a Work Order.")
            return redirect('view_building', building)
        else:

            print(form.errors)

return render(request, 'workorders\\workorder_form.html', context)
python django django-forms
1个回答
0
投票

您忘记将

*args
传递给超级 init,其中将包含
request.POST
数据:

class WorkOrderForm(ModelForm):
    class Meta:
        model = WorkOrder
        fields = '__all__'
        widgets = {
            'issue_Date': DatePickerInput(),
            'completion_Date': DatePickerInput(),
        }

    def __init__(self, *args, **kwargs):
        building = kwargs.pop('building', None)
        super().__init__(*args, **kwargs)
        self.fields['equipment'].queryset = Equipment.objects.filter(
            building__location_Code=building
        )

注意:自 PEP-3135 [pep] 起,如果第一个参数是定义方法的类,第二个参数是方法,则无需带参数调用

super(…)
函数的第一个参数(通常为
self
)。

© www.soinside.com 2019 - 2024. All rights reserved.