Colin
Colin

Reputation: 3752

construct attribute value of django form

How do I pass in a value to an attribute constructor in a django form?

In other words, I have a form like so, and I'd like to set SOMETHING when I instantiate the form.

class ImageUploadFileForm(forms.ModelForm):
    class Meta:
        model = Photo
        fields = [ 'image' ]
    image = cloudinary.forms.CloudinaryJsFileField({ 'public_id': SOMETHING })

i.e. in the view:

uploadform = ImageUploadFileForm(instance=whatever, something='BLAHBLAHBLAH')

I have the suspicion that I'm thinking about this wrongly...


Thx Shang Wang!

For all of you searching in CloudinaryJSFileField, don't forget to add 'options', like so:

class ImageUploadFileForm(ModelFormControlMixin):
    class Meta:
        model = Photo
        fields = [ 'image' ]

    def __init__(self, *args, **kwargs):
        self.public_id = kwargs.pop('public_id')
        super(ImageUploadFileForm, self).__init__(*args, **kwargs)
        self.fields['image'] = cloudinary.forms.CloudinaryJsFileField(options={ 'public_id': str(self.public_id) })

Upvotes: 1

Views: 69

Answers (1)

Shang Wang
Shang Wang

Reputation: 25539

class ImageUploadFileForm(forms.ModelForm):
    class Meta:
        model = Photo
        fields = [ 'image' ]

    def __init__(self, *args, **kwargs):
        self.something = kwargs.pop('something')
        super(ImageUploadFileForm, self).__init__(*args, **kwargs)
        self.fields['image'] = cloudinary.forms.CloudinaryJsFileField({ 'public_id': self.something })

Then

uploadform = ImageUploadFileForm(instance=whatever, something='BLAHBLAHBLAH')

Pretty standard way of passing arguments to form constructor.

Upvotes: 2

Related Questions