为Django中相同表单方法中的两个不同提交按钮传递值



让我们把我的template.html看作

<form class="form-horizontal" id="adhoc-form" method="post" action="{% url 'contacts:add_item' item.id %}">

{% csrf_token %}

<fieldset>
<div class="control-group">
<label for="id_item_filename" class="control-label">Items
<span class="text-error">*</span></label>
<div class="controls">
<select placeholder="Item filename" name="item" id="id_item_filename" class="span3" required="required">
<option value="">---------</option>
{% for i in items %}
<option value="{{i.0}}">{{i.1}}</option>
{% endfor %}
</select>
</div>
</div>
</fieldset>
<div id="form-buttons-container" class="form-actions" style="padding-left: 0px;">
<div class="controls">
<input type="hidden" class="btn btn-primary btn-medium" id= 'i_id' name='i_id' value="{{data.0.id}}">
<input type="submit" class="btn btn-primary btn-medium" value="Submit">
<input type="submit" class="btn btn-primary btn-medium" value="Delete">
</div>
</div>
</form>

my url.py is

url(r'^stock/item/add/item_name/(?P<id>d+)/$', login_required(UpdateBarcode.as_view()), name="add_item"),

my views.py is

class UpdateItem(View):
def post(self, request, id):
item_id = request.POST.get('item')
items = Items.objects.get(id=item_id)
try:
JobItems.objects.filter(id=id).update(item_name=items.name)
except:
messages.error(request, 'Cannot update')
return redirect(reverse("contacts:item_list"))

这里单击提交按钮时我们需要更新项目,单击"删除"按钮应该被删除。请告诉我如何在同一个视图中同时进行提交和删除操作

你可以开始更新你的HTML给按钮name字段:

<input type="submit" class="btn btn-primary btn-medium" name="update-item" value="Submit">
<input type="submit" class="btn btn-primary btn-medium" name="delete-item" value="Delete">

现在您可以检查哪个按钮被触发了。(update-itemdelete-item):

def post(self, request, id):
item_id = request.POST.get("item")
items = Items.objects.get(id=item_id)
if "update-item" in request.POST:
try:
JobItems.objects.filter(id=id).update(item_name=items.name)
except:
messages.error(request, "Cannot update")
elif "delete-item" in request.POST:
JobItems.objects.get(id=id).delete()
return redirect(reverse("contacts:item_list"))

注意,我不知道你的逻辑项删除操作,所以你可以在这里更新。

相关内容

  • 没有找到相关文章

最新更新