Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to not render django image field currently and clear stuff?

Tags:

django

I took a look at following SO question, but had no luck. I don't know, maybe I didn't understand the answers.

1) How to remove the “Currently” tag and link of a FileInput widget in Django?

2) Django ModelForm ImageField

My form:

class SettingsForm(forms.ModelForm):
    company_logo = forms.ImageField(label=_('Company Logo'),required=False, error_messages = {'invalid':_("Image files only")})
    class Meta:
        model = Settings
        fields = ("company_logo")
    ....

My model:

class Settings(models.Model):
    strg=CustomFileSystemStorage(strict_name='images/company_logo.png',save_format='PNG')
    company_logo=models.ImageField(upload_to='images',blank=True,null=True,storage=strg)
    .....

After rendering:

imagefield

I see from the first link, that the models.ImageField inherits the FileInput and adds the extra stuff, but I do not understand how to overcome this?

Thanks in advance.

like image 604
0xmtn Avatar asked Jan 15 '13 11:01

0xmtn


2 Answers

The solution is:

class SettingsForm(forms.ModelForm):
    company_logo = forms.ImageField(label=_('Company Logo'),required=False, error_messages = {'invalid':_("Image files only")}, widget=forms.FileInput)
    class Meta:
        model = Settings
        fields = ("company_logo")
    ....

I added the widget forms.FileInput, in order to tell the ImageField to use the basic field, not the one inherited from FileInput.

like image 58
0xmtn Avatar answered Sep 22 '22 16:09

0xmtn


@mtndesign, you might also want a "remove" option, which you can place wherever you like in your template.

class MyForm(forms.ModelForm):
    photo = forms.ImageField(required=False, widget=forms.FileInput)
    remove_photo = forms.BooleanField(required=False)

    ...

    def save(self, commit=True):
        instance = super(MyForm, self).save(commit=False)
        if self.cleaned_data.get('remove_photo'):
            try:
                os.unlink(instance.photo.path)
            except OSError:
                pass
            instance.photo = None
        if commit:
            instance.save()
        return instance
like image 44
s29 Avatar answered Sep 22 '22 16:09

s29