3 回答
TA贡献1860条经验 获得超8个赞
我现在将它与元类(而不是方法)一起使用,因为Django 1.3否则会显示一些怪异之处。
class MyModelAdmin(admin.ModelAdmin):
form = MyCustomForm
def get_form(self, request, obj=None, **kwargs):
ModelForm = super(MyModelAdmin, self).get_form(request, obj, **kwargs)
class ModelFormMetaClass(ModelForm):
def __new__(cls, *args, **kwargs):
kwargs['request'] = request
return ModelForm(*args, **kwargs)
return ModelFormMetaClass
然后重写MyCustomForm.__init__如下:
class MyCustomForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
self.request = kwargs.pop('request', None)
super(MyCustomForm, self).__init__(*args, **kwargs)
然后,您可以使用ModelFormwith的任何方法访问请求对象self.request。
TA贡献2016条经验 获得超9个赞
值得一说的是,如果使用的是基于类的视图,而不是基于函数的视图,请get_form_kwargs在编辑视图中覆盖。自定义CreateView的示例代码:
from braces.views import LoginRequiredMixin
class MyModelCreateView(LoginRequiredMixin, CreateView):
template_name = 'example/create.html'
model = MyModel
form_class = MyModelForm
success_message = "%(my_object)s added to your site."
def get_form_kwargs(self):
kw = super(MyModelCreateView, self).get_form_kwargs()
kw['request'] = self.request # the trick!
return kw
def form_valid(self):
# do something
上面的视图代码将request作为关键字的参数之一提供给表单的__init__构造函数。因此,在您ModelForm执行以下操作:
class MyModelForm(forms.ModelForm):
class Meta:
model = MyModel
def __init__(self, *args, **kwargs):
# important to "pop" added kwarg before call to parent's constructor
self.request = kwargs.pop('request')
super(MyModelForm, self).__init__(*args, **kwargs)
添加回答
举报