【发布时间】:2021-04-23 16:42:11
【问题描述】:
我有一个 ListView 用于显示产品列表。在每个产品/行的右侧,我想要一个“归档”按钮,单击该按钮会将数据库中产品的“归档”字段从 True 更改为 False。
我想只使用 Django 来做到这一点,我认为这是可能的,但我很难找出方法。
我正在尝试使用表单来执行此操作,但我不知道如何将当前对象(在循环中)的 pk 发送回视图以进行更改。
这是我的模板(相关部分):
{% for product in product_list %}
<tr>
<th scope="row">{{ product.pk }}</th>
<td>
<a href="{% url 'accounts:products_edit' pk=product.pk %}">
{{ product.title }}</a
>
</td>
<td class="d-flex justify-content-between">
<form action="" method="POST">
{% csrf_token %}
<button type="submit"><i class="fas fa-trash" style="color: grey"></i></button>
</form>
</td>
</tr>
{% endfor %}
这是我的看法:
class ProductsListView(ListView, LoginRequiredMixin):
template_name = "accounts/products/products_list.html"
model = Product
def get_context_data(self, **kwargs):
# ...
return context
def post(self, request, *args, **kwargs):
# modify object from pk here
return HttpResponseRedirect(self.request.path_info)
我看过几篇类似情况的帖子,但没有找到完全适合我的情况的解决方案。任何帮助将不胜感激!
【问题讨论】:
标签: python html django database django-templates