简体   繁体   中英

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.

If you want to render the pictureid in GET request, then you can try like this:

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

For GET request, you don't need to override the __init__ method.

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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