Home > OS >  Addition of css class on widget file input has no effect
Addition of css class on widget file input has no effect

Time:01-19

Try to add a css class into a forms.ImageField, has no effect.

model.py:-

class ProductImages(models.Model):
    ...    
    image_file_w200_png = models.ImageField(
        
        verbose_name = "Imagens",
        upload_to=upload_to_image_file_w200_png,
        null=True,
        blank=True,
        default='magickhat-profile.jpg'
    )
    ...

forms.py:-

class ProductImagesForm(ModelForm):
    image_file_w200_png = forms.ImageField(widget=forms.FileInput(attrs={'class': 'image_add_product'}))

    class Meta:
        model = ProductImages
        fields = ['image_file_w200_png']

That code has no effect, what is missing?

Edit:

admin.py

class UsersAdminSite(admin.AdminSite):
    site_header = 'Painel Administrativo'
    index_title = 'Painel Administrativo'
kadmin = UsersAdminSite(name='kadmin')
   
class AdminProductImages(admin.TabularInline):
    model = ProductImages
    extra = 1
    max_num = 10
    list_display = ('image_file_w200_png',)
    fieldsets = (
        (None, {'fields': ('image_file_w200_png',)}),
    )
    add_fieldsets = (
        (None, {
            'fields': ( 'image_file_w200_png'),
        }),
    )
kadmin.register(User, UserAdmin)
kadmin.register(Product, AdminProductModel)

CodePudding user response:

Change the name of your image_file = forms.ImageField() to be image_file_w200_png. What you are doing there currently is defining a new field rather than changing your existing field because the names are not the same.

You could also define it in a different way in your class Meta: section. You can add a dictionary called widgets and write it like this:

class Meta:
   model = ProductImages
   fields = ['image_file_w200_png']
   widgets = {'image_file_w200_png':forms.FileInput(attrs={'class':'image_add_product'})}

Edit: The original poster was trying to add a css class to their admin.TabularInline class in their admin.py file. This can be done by using the same form definition above in my answer and specifying in the admin.TabularInline class what form is used. Example:

class ModelInline(admin.TabularInline):
   model = #Model Class Name Here
   form = #Form class Name Here
  •  Tags:  
  • Related