尝试使用ModelForm和CreateView添加第二个约会(同一日期)时,该约会具有Dayplan外键时,由于DayPlan具有“ date”字段为唯一性,因此唯一性约束失败。
使用django-admin创建表单不存在此问题。
我试图从dayplan.date中删除unique = True以查看会发生什么->每次添加约会时,即使存在dayplan.date,也会创建一个新的dayplan。
问题似乎与以下两行有关:
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()”。删除它们无效。
提前致谢!
最佳答案
解决了
daydate, created = DayPlan.objects.get_or_create(date=planned_date)
form.instance.dayplan = DayPlan.objects.get(date=planned_date)