Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Django中的ModelForm_Python_Django - Fatal编程技术网

Python Django中的ModelForm

Python Django中的ModelForm,python,django,Python,Django,模型形式: def __init__(self, *args, **kwargs): self.user = kwargs.pop('user') super(ChapterCreateForm, self).__init__(*args, **kwargs) 不起作用 我想添加self.fieldother。但它不起作用 这是我的代码: class ChapterCreateForm(ModelForm): 类元: 模型=章节 排除=('user','book',) 定义初始

模型形式:

def __init__(self, *args, **kwargs):
    self.user = kwargs.pop('user')
    super(ChapterCreateForm, self).__init__(*args, **kwargs)
不起作用 我想添加
self.field
other。但它不起作用

这是我的代码:

class ChapterCreateForm(ModelForm):
类元:
模型=章节
排除=('user','book',)
定义初始化(self,*args,**kwargs):
self.user=kwargs.pop(“用户”)
super(ChapterCreateForm,self)。\uuuuuuuuuuuuuuu初始值(*args,**kwargs)
def清洁_标题(自我):
title=自清理的_数据['title']
如果Chapter.objects.filter(user=self.user,title=title).exists():
raise forms.ValidationError('本章已编写')
返回标题
但这种形式是有效的:

类BookCreateForm(ModelForm):
类元:
模型=书
排除=('user',)
定义初始化(self,*args,**kwargs):
self.user=kwargs.pop(“用户”)
超级(BookCreateForm,self)。\uuuuuuuuuuuuuuu初始值(*args,**kwargs)
def清洁_标题(自我):
title=自清理的_数据['title']
如果Book.objects.filter(title=title).exists():
如果Book.objects.filter(user=self.user,title=title).exists():
raise forms.ValidationError('您写了这本书')
raise forms.ValidationError('这本书已经写好')
返回标题
请帮帮我。非常感谢


您需要通过覆盖类
UserCreateChapterView
中的
get\u form\u kwargs
来传递表单kwargs中的
user
,如下所示:

class UserCreateChapterView(UserPassesTestMixin, CreateView):
    ...
    ...
    def get_form_kwargs(self):
        kwargs = super(UserCreateChapterView, self).get_form_kwargs()
        kwargs['user'] = self.request.user
        return kwargs
现在,您可以在
章节CreateForm
初始化方法中使用
kwargs.pop('user')
,它应该可以工作


希望有帮助

展示你尝试的东西什么不起作用?您是否收到了错误信息?[1]:[2]:[3]:[4]:[5]:[6]:[7]:[8]:[9]:这是我在图片中的全部代码。@Amit这只适用于答案。它对commentsHoánguy不起作用ễn如果它解决了您的问题,请接受它作为正确答案。