0

I have a model with an __init__ method:

class Foo(models.Model):
    name = models.CharField(max_length=50)

    def __init__(self, *args, **kwargs):
        self.bar = kwargs.pop('bar', False)
        super(Foo, self).__init__(*args, **kwargs)
        if self.bar:
            # do something
            pass

Now, i need to create a specific ModelForm:

class FooForm(ModelForm):

    class Meta:
        model = Foo(bar='something')
        fields = ('name',)

That does not work apparently:

TypeError: 'Foo' object is not callable

Is there any way i can overcome this?

Update

More information on what i want to achieve: I have an Image model with an ImageField. It has different storage methods depending on the form that uses it.

The model:

class Image(models.Model):
    image = models.ImageField(upload_to=imageUploadTo)
    user = models.ForeignKey('auth.User')

    def __init__(self, *args, **kwargs):
        self.overwrite = kwargs.pop('overwrite', False)
        super(Image, self).__init__(*args, **kwargs)
        if self.overwrite:
            self.image.storage = OverwriteStorage()

Now i want to be able to create forms that overwrite the old image and forms that use the default behavior. What's the best way to achieve this?

1
  • i updated my question with more background information
    – Alp
    Jun 24, 2012 at 13:15

1 Answer 1

3

No, that's not how it works at all, and this has nothing to do with your custom init. You don't call things inside Meta. In your case, you pass the parameter when you initialize the form in your view.

4
  • how are the parameters for the form passed to the model initialization?
    – Alp
    Jun 24, 2012 at 10:57
  • 1
    form = ArticleForm(instance=article) But take a look at docs.djangoproject.com/en/dev/topics/forms/modelforms you won't lose your time.
    – Zashas
    Jun 24, 2012 at 11:51
  • currently i have: form = ArticleForm(request.POST, request.FILES) - how can i combine that with your approach of initializing the instance beforehand?
    – Alp
    Jun 24, 2012 at 13:10
  • 1
    form = ArticleForm(request.POST, request.FILES, instance=Image(overwrite=True)) Jun 24, 2012 at 13:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.