我希望在同一页面上有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>
答案 0 :(得分:0)
由于您对两个表单使用相同的字段,而不是两个基于类的视图,只需使用一个扩展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中有数据