Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Admin Form: Set the default value of a readonly field

Tags:

python

django

THE GOAL: Display a request-specific, read-only user_id on a django admin form when creating and updating a resource.

This display should be a readonly field (readonly, NOT disabled). The user_id displayed is derived from the requesting user (request.user) so the initial value is set from that.

Following this post, we should simply set it in the get_form method like so:

def get_form(self, request, obj=None, *args, **kwargs):
    form = super(ProfileAdmin, self).get_form(request, *args, **kwargs)
    form.base_fields['user'].initial = request.user
    return form

However, user is no longer on the base_fields when it is readonly. In fact, I can't find it anywhere. Any thoughts?

Other posts suggest on save, which I intend to do, but I need it to show on the form before then.

like image 335
jbodily Avatar asked Oct 09 '18 23:10

jbodily


1 Answers

You are right that making the field readonly excludes it from the base_fields.As mentioned in the docs :

Any fields in this option (which should be a list or tuple) will display its data as-is and non-editable; they are also excluded from the ModelForm used for creating and editing.

You could have define a method for it just like list_display but since you need to set user from the request, we need to have the request object, which isn't available in the method.

So for your use case, we can use formfield_for_foreignkey method as :

def formfield_for_foreignkey(self, db_field, request, **kwargs):
    if db_field.name == 'lend_by':
        # setting the user from the request object
        kwargs['initial'] = request.user.id
        # making the field readonly
        kwargs['disabled'] = True
    return super().formfield_for_foreignkey(db_field, request, **kwargs)

Hope it helps.

like image 70
not2acoder Avatar answered Sep 20 '22 13:09

not2acoder