如何在views.py中创建Django模型?

时间:2020-05-01 15:08:57

标签: python django django-class-based-views

在对象“患者”的DetailView页面中,我有一个表单。填写并提交表单后,我想创建一个“ Location”对象。然后,我要创建一个ForeignKey,指向我们在DetailView中查看的“ Patient”对象。

如您所见,如果表单有效,我将调用模型构造函数,保存信息并将其连接到患者对象。但是,当我检查Django Admin时,看不到创建的新对象。我完全即兴,因为我无法在线找到示例。是这样吗?

class PatientDetailView(DetailView, FormMixin):
    model=Patient
    form_class = PastLocationForm
    #template_name = 'patient_detail.html'

    def get_success_url(self):
        return reverse('patient_detail', kwargs={'pk': self.object.pk})

    def post(self, request, *args, **kwargs):
        if not request.user.is_authenticated:
            return HttpResponseForbidden()
        self.object = self.get_object()

        form = self.get_form()

        if form.is_valid():
            pastLocationDetail = Location()
            setattr(pastLocationDetail,'location',str(form.cleaned_data['location']).split(',')[0])
            setattr(pastLocationDetail,'address',str(form.cleaned_data['location']).split(',')[1].split(', ')[0])
            setattr(pastLocationDetail,'district',str(form.cleaned_data['location']).split('District: ')[1].split(',')[0])
            setattr(pastLocationDetail,'grid_x',str(form.cleaned_data['location']).split('Coordinates: (')[1].split(', ')[0])
            setattr(pastLocationDetail,'grid_y',str(form.cleaned_data['location']).split('Coordinates: (')[1].split(', ')[1][:-1])
            setattr(pastLocationDetail,'date_from',form.cleaned_data['date_from'])
            setattr(pastLocationDetail,'date_to',form.cleaned_data['date_to'])
            setattr(pastLocationDetail,'details',form.cleaned_data['details'])
            setattr(pastLocationDetail,'patient', self.object)

            return self.form_valid(form)
        else:
            return self.form_invalid(form)

位置模型

class Location(models.Model):
    patient = models.ForeignKey(Patient, related_name='locations', on_delete=models.CASCADE, null=True, blank=True)
.
.

注意:我同时打印了两个对象

print(type(self.object))
print(pastLocationDetail)

一切似乎都很好。我真的不明白为什么不将其写入数据库

1 个答案:

答案 0 :(得分:2)

您调用了save方法吗? Django orm需要调用save才能将实例数据写入数据库。请参见此Django model instance docs

if form.is_valid():
    pastLocationDetail = Location()
    ...
    pastLocationDetail.save()  # this line required for writing model instance to database 
    return self.form_valid(form)
else:
    return self.form_invalid(form)

还建议您查看this document以更好地使用表格。