django-admin formfield_for_ *根据实例更改默认值 [英] django-admin formfield_for_* change default value per/depending on instance
问题描述
我试图更改外键表单字段的默认值,以根据登录的用户设置其他模型的值。 em>。
但是我正在为此绞尽脑汁...
I'm trying to change the default value of a foreignkey-formfield to set a Value of an other model depending on the logged in user. But I'm racking my brain on it...
这是:在管理站点中更改ForeignKey的默认值将是更改empty_label的选项,但我需要default_value。
This: Changing ForeignKey’s defaults in admin site would an option to change the empty_label, but I need the 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] ...不存在。
Hint: kwargs["default"] ... doesn't exist.
谢谢,尼克
推荐答案
好吧,kwargs ['initial']东西一直都起作用,但是如果给它一个对象,它只会给人一种诅咒(里ke我做了以下操作:kwargs ['initial'] = user.default_company)。
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.
我是这样解决的:
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!
这篇关于django-admin formfield_for_ *根据实例更改默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!