简体   繁体   English

表格问题 - 设置初始值

[英]Form Problems - Setting Initial Value

I am trying to set the initial value of a field on a form. 我试图在表单上设置字段的初始值。 The field is not part of the model, but when I try and set it to a value the field is blank. 该字段不是模型的一部分,但是当我尝试将其设置为值时,该字段为空。 From my research it could be because the form is "bound" which makes some sense to me, but in this case the field is not part of the model. 从我的研究中可能是因为形式是“绑定”,这对我来说是有意义的,但在这种情况下,该字段不是模型的一部分。

My form: 我的表格:

#Form for editing profile
class CatForm(forms.ModelForm):
    pictureid = forms.CharField()

    class Meta:
        model = Cat
        fields = ['name']

    def __init__(self, *args, **kwargs):
        picid = kwargs.pop("pictureid")
        print(picid)
        super(CatForm, self).__init__(*args, **kwargs)
        self.fields['pictureid'] = forms.CharField(initial=picid, required=False)

The model: 该模型:

class Cat(models.Model):
    name = models.CharField(max_length=34,null=False)

From the view it is called like this: 从视图来看,它被称为:

catform = CatForm(request.POST, pictureid=instance.id)

I was expecting it to set the field to the value of the initial attribute, but it doesn't. 我期望它将字段设置为初始属性的值,但事实并非如此。 I have tried testing it by directly adding a string, but doesn't set. 我试过通过直接添加字符串来测试它,但没有设置。

This is what seems to be working for me: 这似乎对我有用:

class CatForm(forms.ModelForm):

    class Meta:
        model = Cat
        fields = ['name']

    def __init__(self, *args, **kwargs):
        picid = kwargs.pop("pictureid")
        super(CatForm, self).__init__(*args, **kwargs)
        self.fields['pictureid'] = forms.CharField(initial=picid)

I also needed to drop the "request.POST" from the call to this when initiating the form. 我还需要在启动表单时从调用中删除“request.POST”。

If you want to render the pictureid in GET request, then you can try like this: 如果你想在GET请求中渲染pictureid,那么你可以尝试这样:

catform = CatForm(initial={'pictureid': instance.id})

For GET request, you don't need to override the __init__ method. 对于GET请求,你不需要重写__init__方法。

But, if you want to use the Catform in POST request, to use the value of pictureid somewhere else(lets say in save method), then you will need to override __init__ method here. 但是,如果你想在POST请求中使用Catform ,要在其他地方使用pictureid的值(比如在save方法中),那么你需要在这里覆盖__init__方法。

class CatForm(forms.ModelForm):
    pictureid = forms.CharField()

    class Meta:
        model = Cat
        fields = ['name']

    def __init__(self, *args, **kwargs):
        picid = kwargs.pop("pictureid")
        print(picid)
        super(CatForm, self).__init__(*args, **kwargs)
        self.pictureid = picid

    def save(self, *args, **kwargs):
        print(self.pictureid)  # if you want to use it in save method
        return super().save(*args, **kwargs)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM