如何禁用Django表单中表单输入字段的呈现

时间:2018-07-06 13:57:20

标签: django django-forms django-templates

我有以下表格。我使用以下命令让Django在我的模板中自动为我呈现表单:{{ form.as_p() }}。如您所见,我拥有company字段,但是由于我要用clean_company设置公司,所以这是多余的。公司字段是隐藏的,但我希望它在模板中完全消失。不过,我仍然需要表单,因为我希望能够调用:form.save(commit=True)

是否可以从模板中删除隐藏字段?

class PlantPurchaseForm(forms.ModelForm):
company = forms.CharField(initial="", widget=forms.HiddenInput())
number = forms.IntegerField(initial=10000, min_value=10000, max_value=99999)
date = forms.DateField(widget=forms.DateInput(attrs={"type": "date"}))

class Meta:
    model = PlantPurchase
    fields = (
        "company",
        "number",
        "date",
        "plant",
        "costs",
    )

def __init__(self, company, *args, **kwargs):
    self.company = company
    super(PlantPurchaseForm, self).__init__(*args, **kwargs)

def clean_company(self):
    data = self.cleaned_data["company"]
    data = self.company
    return data

def clean_date(self):
    data = self.cleaned_data["date"]
    data = datetime.combine(data, time(hour=12))
    data = pytz.utc.localize(data)
    return data

PlantPurchase模型:

class PlantPurchase(models.Model):
    company = models.ForeignKey(Company, related_name="plant_purchases")
    number = models.PositiveSmallIntegerField(unique=True, validators=[MinValueValidator(10000),
                                                                       MaxValueValidator(99999)])
    date = models.DateTimeField()
    plant = models.ForeignKey(Plant, related_name="plant_purchase", on_delete=models.PROTECT)
    costs = models.DecimalField(max_digits=8, decimal_places=2)

    class Meta:
        unique_together = ("company", "number")

    def __str__(self):
        text = "Purchase: #{} {}".format(self.number, self.plant)
        return text

2 个答案:

答案 0 :(得分:0)

有几种方法可以做到这一点。

基本上,如果您确定未使用隐藏字段,则可以使用排除从表单中将其删除。您也可以删除init方法。

Toby 2
Thomas 3
Dominic 4
Tom 7
Henry 7

之后,您需要将公司保存到模型实例中。您可以在表单验证后保存它:

class PlantPurchaseForm(forms.ModelForm):

    number = forms.IntegerField(initial=10000, min_value=10000, max_value=99999)
    date = forms.DateField(widget=forms.DateInput(attrs={"type": "date"}))

    class Meta:
        model = PlantPurchase
        fields = [
            'company',
            'number',
            'date',
            'plant',
            'costs',
        ]
        exclude = ["company"]

..或将公司传递到以下格式的保存方法中:

def post(self, request):
    ...
    if form.is_valid():
        plantPurchase = form.save()
        plantPurchase.company = company
        plantPurchase.save()
        ...

答案 1 :(得分:0)

我通过访问init方法中的表单实例解决了我的问题。这样,我可以删除company字段,并且该字段将不再显示在模板中。

class PlantPurchaseForm(forms.ModelForm):
    number = forms.IntegerField(initial=10000, min_value=10000, max_value=99999)
    date = forms.DateField(widget=forms.DateInput(attrs={"type": "date"}))

    class Meta:
        model = PlantPurchase
        fields = (
            "number",
            "date",
            "plant",
            "costs",
        )

    def __init__(self, company, *args, **kwargs):
        super(PlantPurchaseForm, self).__init__(*args, **kwargs)
        self.instance.company = company

    def clean_date(self):
        data = self.cleaned_data["date"]
        data = datetime.combine(data, time(hour=12))
        data = pytz.utc.localize(data)
        return data