Search code examples
python-3.xdjangodjango-modelsdjango-admin

Why the change of the widget inside the get_form method does not reflect the change in the Django admin site


What I want to do:

Show a widget of type forms.widget.FileInput in my admin site but in the model have a field of type model.TextField.

models.py:

    from django.db import models


    class Post(models.Model):
       image_in_base64 = models.TextField(blank=True)

admin.py:

    from django.contrib import admin
    from django.forms.widgets import FileInput
    from .models import Post

    class MyAdminPost(admin.ModelAdmin):

        def get_form(self, request, obj=None, change=False, **kwargs):
            form = super().get_form(request, obj, change, **kwargs)
            form[Post._meta.fields[-1].name].label = 'Main image of the post'
            form[Post._meta.fields[-1].name].widget = FileInput()
            return form


    admin.site.register(Post, MyAdminPost)

The input in the panel is still of type text, why?


Solution

  • The easiest way is likely to specify a form with:

    class PostForm(forms.ModelForm):
        class Meta:
            model = Post
            fields = '__all__'
            labels = {'image_in_base64 ': 'Main image of the post'}
            widgets = {'image_in_base64': forms.FileInput()}

    and then plug this into the ModelAdmin:

    from django.contrib import admin
    
    
    class MyAdminPost(admin.ModelAdmin):
        form = PostForm