簡體   English   中英

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

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

在 object“患者”的 DetailView 頁面中,我有一個表格。 填寫並提交表單后,我想創建一個“位置”object。 然后,我想創建一個 ForeignKey 指向我們在 DetailView 中查看的“Patient”object。

如您所見,如果表單有效,我調用 model 構造函數,保存信息並將其連接到患者 object。 但是,當我檢查 Django 管理員時,我看不到創建了新的 object。 我完全即興創作,因為我在網上找不到例子。 這是這樣做的方法嗎?

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)

位置 model

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)

一切似乎都很好。 我真的不明白為什么它沒有寫入數據庫

您是否調用了save方法? Django orm 需要調用save將實例數據寫入數據庫。 請參閱此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)

還建議您查看此文檔以更好地使用表單。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM