You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django ModelForm与CreateView按登录用户过滤Company外键选项

实现方案

要实现仅展示当前登录用户关联的Company选项,需要做两处配套修改:

1. 补全forms.py的过滤逻辑

你需要在__init__方法中先提取传入的用户参数,再重设company字段的查询集,补全后的代码如下:

class EmployeeForm(ModelForm):
    def __init__(self, *args, **kwargs):
        # 提前取出传入的当前用户参数,避免传给父类时触发参数错误
        current_user = kwargs.pop('user', None)
        super().__init__(*args, **kwargs)
        
        # 省略号位置补充以下过滤代码
        self.fields['company'].queryset = Company.objects.filter(reg_user=current_user)
        
        self.fields['name'].widget.attrs['autofocus'] = True

    class Meta:
        model = Employee
        fields = ['company', 'name', 'cuil']

注意:必须用pop方法取出user参数,Django原生ModelForm的初始化方法不接收自定义关键字参数,不提前取出会直接抛异常。如果你的代码里Employee模型的外键关联类实际命名为Empresa,把上述过滤逻辑里的Company替换成对应类名即可。

2. 修改CreateView,向表单传入当前用户

表单本身无法直接获取请求中的登录用户对象,需要在对应的CreateView中重写get_form_kwargs方法传参,示例代码:

from django.views.generic.edit import CreateView
from django.contrib.auth.mixins import LoginRequiredMixin
from .models import Employee
from .forms import EmployeeForm

class EmployeeCreateView(LoginRequiredMixin, CreateView):
    model = Employee
    form_class = EmployeeForm
    # 替换为你自己的创建成功跳转地址
    success_url = '/employees/'

    def get_form_kwargs(self):
        kwargs = super().get_form_kwargs()
        kwargs['user'] = self.request.user
        return kwargs
  • 加上LoginRequiredMixin是为了拦截未登录用户的访问,避免匿名用户触发过滤逻辑时出现异常。

内容的提问来源于stack exchange,提问作者Eugenio

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.28 12:06:51