2017-04-05 59 views
0

我有兩個模型如下圖所示保存形式,而有兩個ForeignKeys,

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檢查該字段。如果該對象不存在,請創建它並將其附加到學校字段。

+0

您是使用JavaScript還是簡單地輸入了School字段中不存在的值? –

+0

它應該處理這兩件事(用戶應該能夠從大學的現有對象中進行選擇,或者如果該對象不存在,它應該先創建,然後使用它來協調)。其實,我正在使用文本字段來接受學校的輸入。 –

回答

相關問題