django-admin formfield_for_* change default value per/depending on instance

霸气de小男生 提交于 2019-12-03 21:54:19
Bernhard Vallant

I think the db_field.formfield method (which is also called by the admin btw) always overwrites your inital value with the default value specified in the model! So you need to specify the right form field yourself:

from django import forms

class EmployeeAdmin(admin.ModelAdmin):
    def formfield_for_dbfield(self, db_field, **kwargs):
        user = kwargs['request'].user
        if db_field.name == "company":
            kwargs['initial'] = user.default_company
            qs = Company.objects.all()
            return forms.ModelChoiceField(queryset=qs, **kwargs)
        return super(EmployeeAdmin, self).formfield_for_dbfield(db_field, **kwargs)

You could also do this customization in a custom form's init, but the problem is, that you cannot access request normally in a form class, but you can see my hack here Django: How to get current user in admin forms on how to get the current user object into the form!

ok, the kwargs['initial'] thing worked the whole time but it just give a damn if you give it an object (like I did with: kwargs['initial'] = user.default_company). But it's working with an Integer.

I solved it like this:

def formfield_for_foreignkey(self, db_field, request=None, **kwargs):
    formfields= super(EmployeeAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)

    if request.user.is_superuser:
        return formfields

    if db_field.name == "company":
        qs= request.user.company.all()
        #determine the default pos of configured default_company
        for index, item in enumerate(qs):
            if item==request.user.default_company:
                kwargs["initial"]  = index+1
                break
        #restrict shown entries in the ModelChoiceField
        kwargs["queryset"] = qs


    return db_field.formfield(**kwargs)

Sorry for the stress and thanks for helping!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!