本文介绍了Django-UpdateView表单无法保存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 CBV UpdateView )中使用表单的代码在单击<$ c时不会保存到数据库中$ c>提交按钮。我看不出有什么问题。

My code for using forms inside CBV(UpdateView) won't save to DB when clicking Submit button. I don't see what's wrong.

views.py

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

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        api = get_well_api(self.request)
        context['single_well_bha_list'] = BHA_List.objects.filter(well=api)
        return context

    def form_valid(self, form):
        self.object = form.save()
        return super().form_valid(form)

models.py

class WellInfo(models.Model):
    api = models.CharField(max_length=100, primary_key=True)
    well_name = models.CharField(max_length=100)
    status = models.CharField(max_length=100)

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>

forms.py

from django import forms
from contextual.models import BHA_overall

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

model = BHA_List ,还有另一种通过外键与模型相关的形式。表单字段将显示给用户,单击提交按钮后,应将用户输入保存到数据库,但不会。

So there is a model = BHA_List, and there is another form that is related to the model by a foreign key. The form fields will be displayed to the users, and upon clicking a submit button, it should save the user input to DB, but it doesn't. What's wrong?

推荐答案

您的ModelForm模型与您的UpdateView模型不匹配

Your ModelForm model doesn't match your UpdateView Model

您使用以下方式声明您的ModelForm:

You are declaring your ModelForm with:

model = BHA_Overall

您的UpdateView具有:

Your UpdateView has:

model = BHA_List

请记住,UpdateViews使用model =执行查询集,因此它们可以将Model实例分配给ModelForm,最可能的是不匹配,因为它们是不同的型号。

Do remember that UpdateViews execute a queryset with model= so they can assign a Model instance to the ModelForm, most likely there is not match as they are different models.

此外,如果您不进行额外的验证或修改ModelForm.instance,则无需在UpdateView中覆盖form_valid方法。

Also, if you are not doing extra validations or modifyng the ModelForm.instance you don't need to override form_valid method in the UpdateView.

这篇关于Django-UpdateView表单无法保存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 16:23