Django - Createview form_valid object.id错误

时间:2017-10-26 12:50:19

标签: django django-models django-forms django-views django-class-based-views

我正在尝试创建一个表单,其中创建的对象(项目)与另一个模型(通道)有关系。问题是我无法锻炼如何调用频道的主要关键项目。

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)

1 个答案:

答案 0 :(得分:0)

首先,您应该使用ModelForm,以便保存它以创建实例。不要在字段中加入channel,因为您要在视图中设置它。

class ProjectForm(forms.ModelForm):
    class Meta:
         model = Project
         fields = ['name', 'description']

然后,假设您的url模式已正确配置为包含频道,您需要做的就是在表单实例上设置channel并调用父类' form_valid方法。

def form_valid(self, form):
    form.instance.channel = Channel.objects.get(id=self.kwargs['channel'])
    return super(ProjectCreate, self).form_valid(form)