将会话数据传递到 ModelAdmin 内的 ModelForm

发布于 2024-09-03 11:37:03 字数 524 浏览 6 评论 0原文

我试图在实例方法中初始化 MyModelAdmin 类的表单属性,如下所示:

class MyModelAdmin(admin.ModelAdmin): 
    def queryset(self, request):
        MyModelAdmin.form = MyModelForm(request.user)

我的目标是根据当前会话自定义 MyModelForm 的编辑表单。然而,当我尝试这样做时,我不断收到错误(如下所示)。这是将会话数据传递给 ModelForm 的正确位置吗?如果是这样,那么可能是什么导致了这个错误?

TypeError at ...

异常类型:TypeError

异常值:issubclass() arg 1 必须是类

异常位置:/usr/lib/pymodules/python2.6/django/forms/models.py in ,第 185 行

I'm trying to initialize the form attribute for MyModelAdmin class inside an instance method, as follows:

class MyModelAdmin(admin.ModelAdmin): 
    def queryset(self, request):
        MyModelAdmin.form = MyModelForm(request.user)

My goal is to customize the editing form of MyModelForm based on the current session. When I try this however, I keep getting an error (shown below). Is this the proper place to pass session data to ModelForm? If so, then what may be causing this error?

TypeError at ...

Exception Type: TypeError

Exception Value: issubclass() arg 1 must be a class

Exception Location: /usr/lib/pymodules/python2.6/django/forms/models.py in new, line 185

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

岁月流歌 2024-09-10 11:37:03

结合 Izz ad-Din Ruhulessin 的回答Cikić Nenad 的建议,我最终得到了一个非常出色且简洁的解决方案,如下所示:

class CustomModelAdmin(admin.ModelAdmin):
    def get_form(self, request, obj=None, **kwargs):
        self.form.request = request #so we can filter based on logged in user for example
        return super(CustomModelAdmin, self).get_form(request,**kwargs)

然后只需为 modeladmin 设置一个自定义表单,例如:

form = CustomAdminForm

并在自定义 modelform 类访问请求中,例如:

self.request #对表单附属的请求做一些事情

Combining the good ideas in Izz ad-Din Ruhulessin's answer and the suggestion by Cikić Nenad, I ended up with a very awesome AND concise solution below:

class CustomModelAdmin(admin.ModelAdmin):
    def get_form(self, request, obj=None, **kwargs):
        self.form.request = request #so we can filter based on logged in user for example
        return super(CustomModelAdmin, self).get_form(request,**kwargs)

Then just set a custom form for the modeladmin like:

form = CustomAdminForm

And in the custom modelform class access request like:

self.request #do something with the request affiliated with the form

不爱素颜 2024-09-10 11:37:03

理论上,您可以重写 ModelAdmin 的 get_form 方法:

# In django.contrib.admin.options.py
def get_form(self, request, obj=None, **kwargs):
    """
    Returns a Form class for use in the admin add view. This is used by
    add_view and change_view.
    """
    if self.declared_fieldsets:
        fields = flatten_fieldsets(self.declared_fieldsets)
    else:
        fields = None
    if self.exclude is None:
        exclude = []
    else:
        exclude = list(self.exclude)
    exclude.extend(kwargs.get("exclude", []))
    exclude.extend(self.get_readonly_fields(request, obj))
    # if exclude is an empty list we pass None to be consistant with the
    # default on modelform_factory
    exclude = exclude or None
    defaults = {
        "form": self.form,
        "fields": fields,
        "exclude": exclude,
        "formfield_callback": curry(self.formfield_for_dbfield, request=request),
    }
    defaults.update(kwargs)
    return modelform_factory(self.model, **defaults)

请注意,这会返回表单类而不是表单实例。

Theoretically, you can override the ModelAdmin's get_form method:

# In django.contrib.admin.options.py
def get_form(self, request, obj=None, **kwargs):
    """
    Returns a Form class for use in the admin add view. This is used by
    add_view and change_view.
    """
    if self.declared_fieldsets:
        fields = flatten_fieldsets(self.declared_fieldsets)
    else:
        fields = None
    if self.exclude is None:
        exclude = []
    else:
        exclude = list(self.exclude)
    exclude.extend(kwargs.get("exclude", []))
    exclude.extend(self.get_readonly_fields(request, obj))
    # if exclude is an empty list we pass None to be consistant with the
    # default on modelform_factory
    exclude = exclude or None
    defaults = {
        "form": self.form,
        "fields": fields,
        "exclude": exclude,
        "formfield_callback": curry(self.formfield_for_dbfield, request=request),
    }
    defaults.update(kwargs)
    return modelform_factory(self.model, **defaults)

Note that this returns a form class and not a form instance.

爱格式化 2024-09-10 11:37:03

如果像我这样的新手经过这里:
我必须定义:

class XForm(forms.ModelForm):    
    request=None    

然后在上一篇文章的末尾

    mfc=modelform_factory(self.model, **defaults)   
    self.form.request=request   #THE IMPORTANT statement   
    return mfc

If some newbie, as myself, passes here:
I had to define:

class XForm(forms.ModelForm):    
    request=None    

then at the end of the previous post

    mfc=modelform_factory(self.model, **defaults)   
    self.form.request=request   #THE IMPORTANT statement   
    return mfc
世界和平 2024-09-10 11:37:03

我使用查询集来过滤记录,也许这个例子可以帮助你:

.....
.....
def queryset(self, request):
    cuser = User.objects.get(username=request.user)

    qs = self.model._default_manager.get_query_set()
    ordering = self.ordering or () # otherwise we might try to *None, which is bad ;)

    if ordering:
        qs = qs.order_by(*ordering)

    qs = qs.filter(creator=cuser.id)

    return qs

i use queryset fot filtering records, maybe this example help you:

.....
.....
def queryset(self, request):
    cuser = User.objects.get(username=request.user)

    qs = self.model._default_manager.get_query_set()
    ordering = self.ordering or () # otherwise we might try to *None, which is bad ;)

    if ordering:
        qs = qs.order_by(*ordering)

    qs = qs.filter(creator=cuser.id)

    return qs
夜还是长夜 2024-09-10 11:37:03

这是 nemesisfixx 解决方案的生产/线程安全变体:

def get_form(self, request, obj=None, **kwargs):
    class NewForm(self.form):
        request = request
    return super(UserAdmin, self).get_form(request, form=NewForm, **kwargs)

Here is a production/thread-safe variation from nemesisfixx solution:

def get_form(self, request, obj=None, **kwargs):
    class NewForm(self.form):
        request = request
    return super(UserAdmin, self).get_form(request, form=NewForm, **kwargs)
陌生 2024-09-10 11:37:03
class CustomModelAdmin(admin.ModelAdmin):

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

现在在 ModelForm 中,我们可以通过

self.request

示例访问它:

class CustomModelForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super(TollConfigInlineForm, self).__init__(*args, **kwargs)
        request = self.request
        user = request.user
class CustomModelAdmin(admin.ModelAdmin):

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

Now in ModelForm, we can access it by

self.request

Example:

class CustomModelForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super(TollConfigInlineForm, self).__init__(*args, **kwargs)
        request = self.request
        user = request.user
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文