【发布时间】:2021-04-01 23:09:47
【问题描述】:
在我的在线商店中,我从两个不同的应用程序中获取所有产品和服务,并将它们列出以供用户创建愿望清单。
每个产品或服务都显示在一个引导卡中,其中包含一个用于计算产品数量的输入字段。
#views.py
def my_products(request):
ip_sensor = Ip_sensor.objects.all().order_by('title')
control_valves = ControlValves.objects.all().order_by('title')
context = {
'ip_sensor': ip_sensor,
'control_valves': control_valves,
}
return render(request, 'users/basket/my_products.html', context)
然后在模板中,它们是这样显示的:
<form method="post" id="add_to_wishlist" data-url="{% url 'my_products' %}">
{% csrf_token %}
{% if ip_sensor %}
{% for item in ip_sensor %}
<div class="card">
<div class="card-body">
<div class="row">
<div class="col-12">
<p class="card-text text-center text-capitalize">{{ item.title }}</p>
</div>
<div class="col-12">
<div class="form-group">
<input type="hidden" name="tag" value="{{ item.type }}"> <!-- what to put in name field of this line -->
<input type="hidden" name="item_id" value="{{ item.id }}"> <!-- what to put in name field of this line -->
<label for="count" class="control-label">count</label>
<input type="text"
id="count"
name="count" <!-- what to put in name field of this line -->
placeholder="Count"
class="form-control"
autofocus/>
</div>
</div>
</div>
</div>
</div>
{% endfor %}
{% endif %}
</form>
问题:
当我通过 POST 方法将每个产品或服务的计数返回到我的views.py 以保存到他的愿望清单时,我不知道如何区分返回的值??
由于项目正在 for 循环中显示,并且我想将每个选定的项目分别保存在 WishListItem 对象(模型)中,我需要分别命名每张卡的输入字段但我不知道如何去做吧。
我可以这样保存每个项目:
if request.method == 'POST':
owner = request.user
count = request.POST.get('count')
tag = request.POST.get('tag')
object_id = request.POST.get('item_id')
wishlist = WishListItem(owner=owner,
content_type=class_types[tag],
object_id=object_id,
tag=tag,
count=count)
wishlist.save()
return redirect('my_products')
【问题讨论】:
标签: html post django-views django-templates http-post