单击CBV
按钮时,我在UpdateView
(Submit
)内使用表单的代码不会保存到DB。我看不出有什么问题。
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
,并且还有另一种通过外键与模型相关的形式。表单字段将显示给用户,并且在单击“提交”按钮后,应将用户输入保存到DB,但不会。怎么了?
答案 0 :(得分:2)
您的ModelForm模型与您的UpdateView模型不匹配
您要使用以下方式声明您的ModelForm:
model = BHA_Overall
您的UpdateView具有:
model = BHA_List
请记住,UpdateViews使用model =执行查询集,因此它们可以将Model实例分配给ModelForm,因为它们是不同的模型,因此很可能不匹配。
此外,如果您不进行额外的验证或修改ModelForm.instance,则无需在UpdateView中覆盖form_valid方法。