2017-06-20 85 views
0

當嘗試添加使用ModelForm和CreateView具有dayplan外鍵的第二個約會(對於相同日期)時,由於DayPlan具有'date'字段是唯一的。Django表格intergrityerror:具有唯一字段的外鍵,唯一約束失敗

使用django-admin創建表單時,此問題不存在。

我試圖從dayplan.date中刪除unique = True以查看會發生什麼 - >每當我添加約會時,即使dayplan.date存在,也會創建新的dayplan。

問題似乎與這些2線:

daydate = DayPlan.objects.filter(date=planned_date) 
    form.cleaned_data['dayplan'] = daydate 

的代碼是在這裏:

class DayPlan(models.Model): 
    date = models.DateField(unique=True, db_index=True) 
    comment = models.TextField(null=True, blank=True) 

    def __str__(self): 
     return 'Planning voor {}'.format(self.date) 

    def get_absolute_url(self): 
     return reverse('organizer_dayplan_detail', kwargs={'pk': self.pk}) 

class Appointment(models.Model): 
    comment = models.CharField(null=True, blank=True, max_length=255) 
    planned_date = models.DateField() 
    doctor = models.ForeignKey(Doctor) 
    visited = models.BooleanField(default=False) 
    dayplan = models.ForeignKey(DayPlan) 

class AppointCreate(CreateView): 
    model = Appointment 
    form_class = AppointmentForm 
    template_name = 'organizer/organizer_appointment_create.html' 
    # initial = {'doctor': 'pk', 'comment': 'test',} 
    def get_initial(self): 
     return { 
      "doctor": self.request.GET.get('doctor') 
     } 

    def form_valid(self, form): 
     planned_date = form.cleaned_data['planned_date'] 
     try: 
      daydate = DayPlan.objects.filter(date=planned_date) 
      form.cleaned_data['dayplan'] = daydate 
      form.instance.save() 


     except: 
      daydate = DayPlan.objects.create(date=planned_date) 
      form.instance.dayplan = daydate 
      form.instance.save() 
     return super(AppointCreate, self).form_valid(form) 

class AppointmentForm(forms.ModelForm): 
    class Meta: 
     model = Appointment 
     fields = {'comment', 'planned_date', 'doctor', 'visited', 'dayplan'} 
     widgets = {'visited': forms.HiddenInput(),} 
     exclude = {'dayplan',} 

附:我意識到我不需要在這裏使用「form.instance.save()」。去除它們沒有效果。

在此先感謝!

回答

0

解決

daydate, created = DayPlan.objects.get_or_create(date=planned_date) 
form.instance.dayplan = DayPlan.objects.get(date=planned_date)