Django:从管理员的 form.clean() 访问请求对象 [英] Django: Access request object from admin's form.clean()

查看:21
本文介绍了Django:从管理员的 form.clean() 访问请求对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题与这个问题非常相似:如何在表单的 clean() 方法中访问请求对象或任何其他变量?

My question is very similar to this one: How do I access the request object or any other variable in a form's clean() method?

除此之外,我对管理表单也有同样的问题.所以我看不到自己初始化表单的方法,因此 - 将请求传递给它.

Except, I have the same problem with admin form. So I can't see a way to init the form myself, therefore - to pass a request to it.

先谢谢了.

推荐答案

确实有办法解决您的问题!

您需要ModelAdmin.get_form()提供的子类表单并覆盖它:

You will need to subclass form provided by ModelAdmin.get_form() and override it:

class BusinessDocumentCommentForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request', None)
        # Voila, now you can access request anywhere in your form methods by using self.request!
        super(BusinessDocumentCommentForm, self).__init__(*args, **kwargs)
        if self.request.GET.get('document_pk', False):
            #Do something
    def clean(self):
        # Do something with self.request
        # etc.    
    class Meta:
        model = BusinessDocumentComment

class BusinessDocumentCommentAdmin(admin.ModelAdmin):

    form = BusinessDocumentCommentForm     

    def get_form(self, request, obj=None, **kwargs):

        AdminForm = super(BusinessDocumentCommentAdmin, self).get_form(request, obj, **kwargs)

        class AdminFormWithRequest(AdminForm):
            def __new__(cls, *args, **kwargs):
                kwargs['request'] = request
                return AdminForm(*args, **kwargs)

        return AdminFormWithRequest

这篇关于Django:从管理员的 form.clean() 访问请求对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆