Django:ModelForm Admin的当前用户ID

时间:2015-01-20 05:50:56

标签: django django-admin

我想要使用当前用户过滤ModelChoiceField。我发现了一个非常接近我想做的解决方案,但我不明白 Django: How to get current user in admin forms

接受的答案是

“我现在可以通过访问self.current_user来访问我的forms.ModelForm中的当前用户”

- admin.py

class Customer(BaseAdmin):
form = CustomerForm

def get_form(self, request,obj=None,**kwargs):
    form = super(Customer, self).get_form(request, **kwargs)
    form.current_user = request.user
    return form

- forms.py

class CustomerForm(forms.ModelForm):

default_tax =   forms.ModelChoiceField(queryset=fa_tax_rates.objects.filter(tenant=????)) 
class Meta:
    model   = fa_customers

如何在modelchoice queryset上获取当前用户(tenant = ????) 如何调用modelform(forms.py)中的self.current_user

2 个答案:

答案 0 :(得分:0)

覆盖__init__的<{1}}构造函数:

CustomerForm

表单字段定义中的Queryset可以安全地设置为class CustomerForm(forms.ModelForm): ... def __init__(self, *args, **kwargs): super(CustomerForm, self).__init__(*args, **kwargs) self.fields['default_tax'].queryset = fa_tax_rates.objects.filter(tenant=self.current_user)) all()

none()

答案 1 :(得分:0)

只是总结解决方案,因为我很难完成这项工作并理解可接受的答案

在admin.py

class MyModelForm (forms.ModelForm):

    def __init__(self, *args,**kwargs):
    super (MyModelForm ,self).__init__(*args,**kwargs)
    #retrieve current_user from MyModelAdmin
    self.fields['my_model_field'].queryset = Staff.objects.all().filter(person_name = self.current_user)

#数据库中的人名必须与Django User中的人名相同,否则请使用诸如person_name__contains之类的

class MyModelAdmin(admin.ModelAdmin):
    form = MyModelForm 

    def get_form(self, request, *args, **kwargs):
        form = super(MyModelAdmin, self).get_form(request, *args, **kwargs)
        form.current_user = request.user #get current user only accessible in MyModelAdminand pass it to MyModelForm
        return form