简体   繁体   English

如何在 views.py 中创建 Django model?

[英]How can I create a Django model in views.py?

In a DetailView page for object "Patient", I have a form.在 object“患者”的 DetailView 页面中,我有一个表格。 When the form is filled and submitted, I want to create a "Location" object.填写并提交表单后,我想创建一个“位置”object。 Then, I want to create a ForeignKey pointing to the "Patient" object that we are looking at in the DetailView.然后,我想创建一个 ForeignKey 指向我们在 DetailView 中查看的“Patient”object。

As you can see, if the form is valid, I call the model constructor, save the information and connect it to the patient object.如您所见,如果表单有效,我调用 model 构造函数,保存信息并将其连接到患者 object。 However when I check Django Admin, I can't see a new object created.但是,当我检查 Django 管理员时,我看不到创建了新的 object。 I totally improvised as I couldn't find examples online.我完全即兴创作,因为我在网上找不到例子。 Is this the way to do it?这是这样做的方法吗?

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)

Location model位置 model

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

Note: I printed out both the objects注意:我打印了两个对象

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

And everything seems fine.一切似乎都很好。 I really don't understand why it is not written to the database我真的不明白为什么它没有写入数据库

Did you call save method?您是否调用了save方法? Django orm need call save to write instance data into database. Django orm 需要调用save将实例数据写入数据库。 See this Django model instance docs .请参阅此Django model 实例文档

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)

It is also recommended that you view this document to better use form.还建议您查看此文档以更好地使用表单。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM