Django-UpdateView不保存到数据库

时间:2018-07-24 05:43:33

标签: django post django-models django-forms

单击提交按钮后,我的UpdateView不会保存到本地数据库。

views.py

class BHA_UpdateView(UpdateView):
    template_name = 'bha_test.html'
    context_object_name = 'bha'
    model = BHA_overall
    success_url = reverse_lazy('well_list')
    pk_url_kwarg = 'pk_alt'
    form_class = BHA_overall_Form

    def get_object(self, queryset=None):
        pk = self.kwargs.get(self.pk_url_kwarg)
        api = get_well_api(self.request)
        current_bha = BHA_List.objects.filter(well=api, id=pk)[0]
        return current_bha

forms.py

class BHA_overall_Form(forms.ModelForm):
    class Meta():
        model = BHA_overall
        fields = '__all__'

models.py

class BHA_List(models.Model):
    well = models.ForeignKey(WellInfo, 'CASCADE', related_name='bha_list')
    bha_number = models.CharField(max_length=100)

class BHA_overall(models.Model):
    bha_number = models.ForeignKey(BHA_List, 'CASCADE', related_name='bha_overall')
    drill_str_name = models.CharField(max_length=111)
    depth_in = models.CharField(max_length=111)

bha_test.html

<form method="POST">
  {% csrf_token %}
  {{ form.as_p }}
  <input type="submit" class='btn btn-primary' value="Submit">
</form>

有人告诉我,在UpdateView中,模型和表单应引用相同的内容。所以我做到了,但仍然无法正常工作。这是我的original question

如何修改代码,以便将表单保存到数据库中?

更新

BHA_List包含BHA对象的列表。每个BHA对象都有许多子对象,BHA_overall是其中之一。

我的网址看起来像这样:

re_path(r'^bha/(?P<pk_alt>[-\w]+)$', base_views.BHA_UpdateView.as_view(), name='bha')

理想情况下,pk_url_kwarg = 'pk_alt'应该在BHA_List中查找对象,并导航到一个页面,您可以在其中更新有关BHA_List中该特定对象的信息。您可以更新的字段包括BHA_overall中的字段。

所以看起来像这样:

You can now edit [ BHA 2 ]: # url = .../bha/2

    BHA Overall Information - 
    Drill_str_name: []
    Depth_in: []
    ...

    Other Child Model - 
    other_field: []
    other_field: []

我需要pk_url_kwarg = 'pk_alt'来查询BHA_List实例以生成唯一的url,并且我需要BHA_overall_Form显示用户可以编辑的输入字段,并将该用户输入保存到D B。那我还要在这里使用什么CBV?

1 个答案:

答案 0 :(得分:1)

您的get_object方法返回BHA_list对象。但是您的视图和表单的模型是BHA_overall。因此,get_object还应该返回要更新的BHA_overall实例:

def get_object(self, queryset=None):
    pk = self.kwargs.get(self.pk_url_kwarg)
    api = get_well_api(self.request)
    bha_number = BHA_List.objects.filter(well=api, id=pk)[0]
    current_bha = BHA_overall.objects.filter(bha_number=bha_number)[0]
    return current_bha