django-admin formfield_for_* 根据实例更改默认值

问题描述 投票:0回答:2

我正在尝试更改外键表单字段的默认值以设置其他模型的值取决于登录的用户。 但我正在绞尽脑汁……

这个:在管理站点中更改ForeignKey的默认值可以选择更改empty_label,但我需要default_value。

#Now I tried the following without errors but it didn't had the desired effect:
class EmployeeAdmin(admin.ModelAdmin):
    ...

    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":
            # This is the RELEVANT LINE
            kwargs["initial"]  = request.user.default_company
        
        return db_field.formfield(**kwargs)

    
admin.site.register(Employee, EmployeeAdmin)

##################################################################
# REMAINING Setups if someone would like to know it but i think
# irrelevant concerning the problem
##################################################################
from django.contrib.auth.models import User, UserManager
class CompanyUser(User):
    ...
    objects = UserManager()
    company = models.ManyToManyField(Company)
    default_company= models.ForeignKey(Company, related_name='default_company')
    #I registered the CompanyUser instead of the standard User, 
    #   thats all up and working
    ...

class Employee(models.Model):
    company = models.ForeignKey(Company)
    ...

提示:kwargs["default"] ...不存在。

预先感谢,尼克

django django-models django-admin default-value foreign-keys
2个回答
2
投票

我认为

db_field.formfield
方法(顺便说一句,也由管理员调用)总是用模型中指定的默认值覆盖您的初始值! 所以你需要自己指定正确的表单字段:

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)

您也可以在自定义表单的init中进行此自定义,但问题是,您无法在表单类中正常访问

request
,但您可以在这里看到我的黑客Django:如何在管理中获取当前用户forms 如何将当前用户对象放入表单!


0
投票

好吧,kwargs['initial'] 东西一直在工作,但如果你给它一个对象,它就会产生该死的效果(就像我所做的那样:kwargs['initial'] = user.default_company)。但它使用的是整数。

我是这样解决的:

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)

抱歉给您带来压力,感谢您的帮助!

© www.soinside.com 2019 - 2024. All rights reserved.