【问题标题】:Why FormView not saving data within a DetailView?为什么 FormView 不在 DetailView 中保存数据?
【发布时间】:2020-09-18 06:14:34
【问题描述】:

我有一个基于模型 (A) 的 DetailView,并且在同一个模板上我有一个来自模型 B 的 ModelFormView,它对模型 (A) 有 FK

表单中的数据不会保存到数据库中。

这是DetailView

class LocationView(DetailView):

    template_name = "base/stocks/location.html"
    model = LocationStock

    def get_context_data(self, **kwargs):

         context = super(LocationView, self).get_context_data(**kwargs)
         context['form'] = OutsModelForm
         return context

    def get_object(self):

         id_ = self.kwargs.get("id")
         return get_object_or_404(LocationStock, id=id_)

这是FormView

  class OutsAdd(FormView):

       form_class = OutsModelForm
       success_url = reverse_lazy('base:dashboard')

       def form_valid(self, form):

           return super().form_valid(form)

这是 url.py

    path('locations/<int:id>', LocationView.as_view(), name='location-detail'),
    path('locations/outs', require_POST(OutsAdd.as_view()), name='outs-add'),

这是模板

<form method="POST" action="{% url 'outs-add' %}" >

<div class="modal-content">
        {% csrf_token %} 
          {% render_field form.quantity placeholder="Quantity"%}
          {% render_field form.id_year placeholder="Year"%}
          {% render_field form.id_location placeholder="ID Location"%}

  </div>
  <div class="modal-footer">
    <input class="modal-close waves-effect waves-green btn-flat" type="submit" value="Save">
  </div>
</form>

数据在 /locations/outs 中发布,但未保存到实际数据库中。如何保存?

【问题讨论】:

    标签: django django-class-based-views formview detailview


    【解决方案1】:

    Django 的FormView 的功能实际上只是在 GET 请求上显示表单,在 form_invalid 的情况下显示表单错误,如果表单有效则重定向到新 URL。为了将数据持久化到数据库中,您有两种选择。首先,您可以在FormView 中简单地调用form.save()

    class OutsAdd(FormView):
        form_class = OutsModelForm
        success_url = reverse_lazy('base:dashboard')
    
        def form_valid(self, form):
            form.save()
            return super().form_valid(form)
    

    或者,您可以使用通用的CreateView。 Django 的CreateView 类似于FormView,只是它假定它正在使用ModelForm 并在幕后为您调用form.save()

    【讨论】:

    • @titpoettt 这个答案对你有帮助吗?还有什么我可以进一步扩展的吗?
    猜你喜欢
    • 1970-01-01
    • 2022-01-25
    • 2014-01-18
    • 2012-06-07
    • 1970-01-01
    • 2013-05-31
    • 2020-09-26
    • 2023-03-13
    相关资源
    最近更新 更多