【问题标题】:linking updateview form with template form in django将updateview表单与django中的模板表单链接
【发布时间】:2017-12-12 17:45:39
【问题描述】:

我希望 CreateView 和 UpdateView 表单在同一页面上,但更新表单仅在按下编辑按钮时才显示,该按钮也在同一页面上 但问题是,当按下编辑按钮时,如果 updateView 的 URL 链接到按钮,并且如果我没有将 updateView 链接到按钮,那么表单不会自动归档要更新。它的解决方案是什么?

class stock_add_view(CreateView):
    model = part_stock
    fields = ['part_id','entry_date','supplier','amount','remaining']
    success_url = reverse_lazy('parts:part_list')

class stock_update_view(UpdateView):
    model = part_stock
    fields = ['part_id','entry_date','supplier','amount','remaining']
    success_url = reverse_lazy('parts:part_list')
    template_name = 'part_detail.html'

网址格式

   url(r'^add_stock$',views.stock_add_view.as_view(),name='stock_add_view'),
url(r'^update_stock/(?P<pk>\d+)/$',views.stock_update_view.as_view(),name='stock_update_view'),

模板:part_detail.html

<script type="text/javascript">
$(function () {
    $('.edit_btn').on('click',pop_up);
    function pop_up() {
        alert("hi")
        $('#update_form').show();
    }
})
</script>
<div>//add form
<form method="post" action="{% url 'parts:stock_add_view'%}">
    {% csrf_token %}
    {{ form.as_p }}
    <input type="submit">
</form>
</div>
<div style="display: none;" id="update_form">//update form
<form method="post" action="{% url 'parts:stock_update_view' stock.id%}">
    {% csrf_token %}
    {{ form.as_p }}
    <input type="submit">
</form>
</div>
//edit button
<a href=""> <button type="button" class="edit_btn" data-id="{{ stock.id }}">Edit</button></a>

【问题讨论】:

    标签: django django-views


    【解决方案1】:

    由于您对两个表单使用相同的字段,而不是两个基于 Class 的 Views ,因此只需使用一个扩展 FormView 并使用 update_or_create 方法的字段

    class stock_add_view(FormView):
        model = part_stock
        template_name = 'part_detail.html'
        success_url = reverse_lazy('parts:part_list') 
    
        def form_valid(self, form):
            part_stock.objects.update_or_create(
                'part_id': form.cleaned_data["part_id"]
                defaults={
                    'entry_date': form.cleaned_data["entry_date"],
                    'supplier': form.cleaned_data["supplier"],
                    'amount': form.cleaned_data['amount'],  
                    'remaining':form.cleaned_data['remainig'],  
                }
            )
            return render(self.request, self.template_name, {'form': form})
    

    这意味着 django 会寻找一个 id=part_id 的对象,如果它存在,它将被更新,否则它将被创建,数据在默认的 dict 中

    【讨论】:

      猜你喜欢
      • 2017-01-02
      • 2021-05-29
      • 2013-11-14
      • 2015-04-17
      • 2016-10-23
      • 2018-05-10
      • 2014-02-01
      • 2021-12-15
      • 1970-01-01
      相关资源
      最近更新 更多