I want to pass the user which is logged in to my form and save it automatically.
In addition I want the admin page to show an icon, I saved as base64 string on the admin page. I tried this, but it did not help me in the end.
models.py:
class Comment(Model):
desc = TextField(max_length=512)
created = DateTimeField(auto_now_add=True)
updated = DateTimeField(auto_now=True)
user = ForeignKey(User, on_delete=CASCADE)
class Meta:
abstract = True
class Screen(Comment):
name = CharField(unique=False, max_length=64)
screen_type = IntegerField()
icon = TextField(blank=True)
admin.py:
class ScreenAdminForm(forms.ModelForm):
image_file = forms.ImageField(required = False, label = "Icon")
class Meta:
model = Screen
fields = ["name", "screen_type", "image_file", "desc",]
readonly_fields = ["user",]
def __init__(self, *args, **kwargs):
self.request = kwargs.pop('request') # <--- KeyError
super().__init__(*args, **kwargs)
def clean_image_file(self):
cleaned_data = super().clean()
if "image_file" in self.changed_data:
...
return cleaned_data
def clean(self):
"""
general clean method has to be used, because "icon" is not invoked in "fields" so, "clean_icon" would not be called otherwise.
"""
cleaned_data = super().clean()
if "image_file" in self.changed_data:
self.instance.icon = self.cleaned_data["image"]
return cleaned_data
@admin.register(Screen)
class ScreenAdmin(admin.ModelAdmin):
form = ScreenAdminForm
def get_form_kwargs(self):
print("this method was called") # <-- never called
kwargs = super().get_form_kwargs()
kwargs["request"] = self.request
return kwargs
def change_view(self, request, object_id, form_url = "", extra_context = None):
"""
Adding the icon preview in the admin panel
"""
print("change_view is called")
extra_context = extra_context or {}
try:
img = Screen.objects.get(pk = object_id).icon
extra_context['icon'] = format_html(f"""<img src="{img}">""")
except:
pass
return super().change_view(request, object_id, form_url, extra_context = extra_context)
First I tried to use get_form
inside of ScreenAdmin
but that resulted in the form being called twice, second time giving me a TypeError
. Then I tried it with the get_form_kwargs()
method and now I am out of ideas. What did I miss?
Goal: I want to save the user who edited the ScreenAdminForm
automatically and make it non-editable even for the admin.
The “show icon” part is just mentioned because it makes use of the change_view()
method, it is already implemented and working.