Django - Createview form_valid object.id 错误
Django - Createview form_valid object.id error
我正在尝试创建一个表单,其中创建的对象(项目)与另一个模型(通道)有关系。问题是我不知道如何调用项目关系的频道主键。
Models.py:
class Project(models.Model):
channel = models.ForeignKey(
'Channel',
on_delete=models.CASCADE,
)
Views.py:
class ProjectCreate(CreateView):
model = Project
fields = ['name', 'description']
def form_valid(self, form):
Project = form.save(commit=False)
form.instance.channel = Channel.objects.get(id=self.kwargs['channel'])
Project.channel = channel
return super(ProjectCreate, self).form_valid(form)
我认为 forms.py 文件还需要添加其他内容:
Forms.py:
class ProjectForm(forms.Form):
name = forms.CharField(max_length=50)
description = forms.CharField(widget=forms.Textarea)
首先,你应该使用一个ModelForm
,这样你就可以保存它来创建实例。不要在字段中包含 channel
,因为您将在视图中设置它。
class ProjectForm(forms.ModelForm):
class Meta:
model = Project
fields = ['name', 'description']
然后,假设您的 url 模式已正确配置为包含频道,您需要做的就是在表单实例上设置 channel
并调用父 class ' form_valid
方法。
def form_valid(self, form):
form.instance.channel = Channel.objects.get(id=self.kwargs['channel'])
return super(ProjectCreate, self).form_valid(form)
我正在尝试创建一个表单,其中创建的对象(项目)与另一个模型(通道)有关系。问题是我不知道如何调用项目关系的频道主键。
Models.py:
class Project(models.Model):
channel = models.ForeignKey(
'Channel',
on_delete=models.CASCADE,
)
Views.py:
class ProjectCreate(CreateView):
model = Project
fields = ['name', 'description']
def form_valid(self, form):
Project = form.save(commit=False)
form.instance.channel = Channel.objects.get(id=self.kwargs['channel'])
Project.channel = channel
return super(ProjectCreate, self).form_valid(form)
我认为 forms.py 文件还需要添加其他内容:
Forms.py:
class ProjectForm(forms.Form):
name = forms.CharField(max_length=50)
description = forms.CharField(widget=forms.Textarea)
首先,你应该使用一个ModelForm
,这样你就可以保存它来创建实例。不要在字段中包含 channel
,因为您将在视图中设置它。
class ProjectForm(forms.ModelForm):
class Meta:
model = Project
fields = ['name', 'description']
然后,假设您的 url 模式已正确配置为包含频道,您需要做的就是在表单实例上设置 channel
并调用父 class ' form_valid
方法。
def form_valid(self, form):
form.instance.channel = Channel.objects.get(id=self.kwargs['channel'])
return super(ProjectCreate, self).form_valid(form)