Django-强制将表单保存到特定模型

时间:2018-07-25 23:02:14

标签: django django-models django-forms django-views django-class-based-views

views.py

class BHA_UpdateView(UpdateView):
    model = BHA_List
    pk_url_kwarg = 'pk_alt'
    form_class = BHA_overall_Form

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)
    depth_out = models.CharField(max_length=111)

如果我在模板中使用{{ form.as_p }}向用户显示表单字段,它将生成一个如下所示的页面:

enter image description here

如何覆盖get()post()方法以从用户那里获取输入,并保存用户输入并更新特定的模型实例?

在我当前使用views.py的情况下,forms的用户输入将不会保存到数据库,因为我的form引用了model = BHA_overall,其中{{1}是我的模型}是views.py。但是由于某些原因,我不想在model = BHA_List中更改模型。

如果我将views.py更改为CBV而不是CreateView,它将为数据库创建一个新的UpdateView实例。但是,如果要更新BHA_overall的特定模型实例,则首先需要BHA_overall一个get()的模型实例,然后通过BHA_overall更新该模型实例。但是我不知道该怎么做。我该怎么办?

编辑:

类似这样的东西:

post()

1 个答案:

答案 0 :(得分:1)

您也可以只使用

from django.views import View

和您的views.py:

from django.views import View
from django.models import Model1, Model2
class UpdateView(View):
      model = Model1
      template_name = 'update.html'

      def post(self, request, id, name , "other-parameters", ..., *kwargs):
          obj1 = self.model1.objects.get_or_404(id=id) # this just example you can past any parameters that you want
          if obj1:
             obj1.name = name # updating name of obj1
             obj1.save() # savin updated object
          obj2 = Model2.objects.get_or_404(id=request.POST.get('id') # you must to pass name='some-id' in your template at input tag
          if obj2:
             obj2.some_field = some_parameter
             obj2.save()
          return redirect('index/') # you must choose only url that exists 

我等待您的反馈