有两个ForeignKeys时保存表单,

时间:2017-04-05 14:05:38

标签: django forms django-models django-views foreign-keys

我有两个模型,如下所示

class college(models.Model):
    name = models.CharField(max_length=256)
class education(models.Model):
    author = models.ForeignKey('auth.User')
    school = ForeignKey(college)
    field = models.CharField(max_length=200)
    startyear = models.IntegerField(blank =True,null = True)
    endyear = models.IntegerField(blank =True,null = True)

视图如下所示

class EducationListView(ListView):
    template_name = 'education.html'

    def get_queryset(self):
        return education.objects.filter(author__username=self.request.user.username).order_by('-startyear')
class EducationCreate(CreateView):
    model = dupeducation
    fields = ('school','field','startyear','endyear')
    template_name = 'education_form.html'
    def form_valid(self, form):
        form.instance.author = self.request.user
        obj,created = college.objects.get_or_create(name=form['school'])
        obj.save()
        form.instance.school = obj
        return super(EducationCreate, self).form_valid(form)
class EducationUpdate(UpdateView):
    model = education
    fields = ('school','field','startyear','endyear')
    template_name = 'education_form.html'
    def form_valid(self, form):
        form.instance.author = self.request.user
        return super(EducationUpdate, self).form_valid(form)
class EducationDelete(DeleteView):
    model = education
    success_url = reverse_lazy('education')

我无法保存表单。它正在向学校领域抛出错误,如“选择一个有效的选择。这个选择不是可用的选择之一。”。

我的目标是为学校字段输入输入并使用get_object_or_create检查该字段。如果该对象不存在,请创建它并将其附加到学校字段。

1 个答案:

答案 0 :(得分:0)

如果您进行调试,则会看到未找到save()。您的问题出在Field validation

您需要做的是覆盖在保存任何对象之前调用的clean_<field>()方法。

您可以在此处详细了解:Django how to override clean() method in a subclass of custom form?

在覆盖clean_school()时,您可以将值添加到数据库中,稍后在save()中,只需进行归因即可。