Python 如何使用POST请求Django更改布尔值
编辑: 我的目标是创建一个小型电子商务。 在我的索引中,我有一个产品列表,其中一个属性是一个称为In_cart的布尔值,它表示产品是否在购物车中。 默认情况下,所有布尔值都为false。在我的模板中有一个包含所有产品的表,在该表旁边我放置了一个按钮“添加到购物车”,该按钮重定向到购物车模板。但是,当我单击add to cart时,所讨论的布尔值不会更改为true。有什么想法吗Python 如何使用POST请求Django更改布尔值,python,django,html-table,boolean,Python,Django,Html Table,Boolean,编辑: 我的目标是创建一个小型电子商务。 在我的索引中,我有一个产品列表,其中一个属性是一个称为In_cart的布尔值,它表示产品是否在购物车中。 默认情况下,所有布尔值都为false。在我的模板中有一个包含所有产品的表,在该表旁边我放置了一个按钮“添加到购物车”,该按钮重定向到购物车模板。但是,当我单击add to cart时,所讨论的布尔值不会更改为true。有什么想法吗 <table> <tr> <th>List of c
<table>
<tr>
<th>List of car parts available:</th>
</tr>
<tr>
<th>Name</th>
<th>Price</th>
</tr>
{% for product in products_list %}
<tr>
<td>{{ product.id }}</td>
<td>{{ product.name }}</td>
<td>${{ product.price }}</td>
<td>{% if not product.in_cart %}
<form action="{% url 'add_to_cart' product_id=product.id %}" method="POST">
{% csrf_token %}
<input type="submit" id="{{ button_id }}" value="Add to cart">
</form>
{% else %}
{{ print }}
{% endif %}
</td>
</tr>
{% endfor %}
</table>
<a href="{% url 'cart' %}">See cart</a>
型号:
class Product(models.Model):
name = models.CharField(max_length=200)
price = models.IntegerField()
in_cart = models.BooleanField(default=False)
ordered = models.BooleanField(default=False)
def __str__(self):
return self.name
网址
urlpatterns=[
路径(“”,views.index,name='index'),
路径('cart/',views.cart,name='cart')
re_路径(r'^add_to_cart/(?P[0-9]+)$),views.add_to_cart,name='add_to_cart')
]
我的终端出错
File "/Users/Nicolas/code/nicobarakat/labelachallenge/products/urls.py", line 8
re_path(r'^add_to_cart/(?P<product_id>[0-9]+)$', views.add_to_cart, name='add_to_cart')
^
SyntaxError: invalid syntax
文件“/Users/Nicolas/code/nicobarakat/labelaschallenge/products/url.py”,第8行
re_路径(r'^add_to_cart/(?P[0-9]+)$),views.add_to_cart,name='add_to_cart')
^
SyntaxError:无效语法
这是localhost中的外观:
首先,您的
if
语句无法访问。因为前面有一个返回。在函数中调用return
时,将不会执行return
后面的函数行
因此,您应该更改索引
函数。
此外,您应该在post请求中发送产品的标识符。标识符可以是模型中的id或任何其他唯一字段
所以你的代码应该是这样的:
def index(request):
if request.method == 'POST': # Request is post and you want to update a product.
try:
product = Product.objects.get(unique_field=request.POST.get("identifier")) # You should chnage `unique_field` with your unique filed name in the model and change `identifier` with the product identifier name in your form.
product.in_cart = True
product.save()
return HttpResponse('', status=200)
except Product.DoesNotExist: # There is no product with that identifier in your database. So a 404 response should return.
return HttpResponse('Product not found', status=404)
except Exception: # Other exceptions happened while you trying saving your model. you can add mor specific exception handeling codes here.
return HttpResponse('Internal Error', status=500)
elif request.method == "GET": # Request is get and you want to render template.
products_list = Product.objects.all()
template = loader.get_template('products/index.html')
context = {'products_list': products_list}
return HttpResponse(template.render(context, request))
return HttpResponse('Method not allowed', status=405) # Request is not POST or GET, So we should not allow it.
url(r'^add_to_cart/(?P<product_id>[0-9]+)$', 'add_to_cart_view', name='add_to_cart')
def index(request):
if request.method == "GET":
products_list = Product.objects.all()
template = loader.get_template('products/index.html')
context = {'products_list': products_list}
return HttpResponse(template.render(context, request))
return HttpResponse('Method not allowed', status=405)
def cart(request):
cart_list = Product.objects.filter(in_cart = True)
template_cart = loader.get_template('cart/cart.html')
context = {'cart_list': cart_list}
return HttpResponse(template_cart.render(context, request))
def add_to_cart(request, product_id):
if request.method == 'POST':
try:
product = Product.objects.get(pk=product_id)
product.in_cart = True
product.save()
return HttpResponse('', status=200)
except Product.DoesNotExist:
return HttpResponse('Product not found', status=404)
except Exception:
return HttpResponse('Internal Error', status=500)
return HttpResponse('Method not allowed', status=405)
我在代码的注释中添加了您需要的所有信息。我认为您应该在python和django文档上花费更多的时间。但如果你还有任何问题,你可以在评论中提问。
问题编辑后
如果不想在表单中使用只读字段,则应在代码中进行两项更改。
首先,您应该在url.py
文件中添加一个带有product\u id
参数的url。大概是这样的:
def index(request):
if request.method == 'POST': # Request is post and you want to update a product.
try:
product = Product.objects.get(unique_field=request.POST.get("identifier")) # You should chnage `unique_field` with your unique filed name in the model and change `identifier` with the product identifier name in your form.
product.in_cart = True
product.save()
return HttpResponse('', status=200)
except Product.DoesNotExist: # There is no product with that identifier in your database. So a 404 response should return.
return HttpResponse('Product not found', status=404)
except Exception: # Other exceptions happened while you trying saving your model. you can add mor specific exception handeling codes here.
return HttpResponse('Internal Error', status=500)
elif request.method == "GET": # Request is get and you want to render template.
products_list = Product.objects.all()
template = loader.get_template('products/index.html')
context = {'products_list': products_list}
return HttpResponse(template.render(context, request))
return HttpResponse('Method not allowed', status=405) # Request is not POST or GET, So we should not allow it.
url(r'^add_to_cart/(?P<product_id>[0-9]+)$', 'add_to_cart_view', name='add_to_cart')
def index(request):
if request.method == "GET":
products_list = Product.objects.all()
template = loader.get_template('products/index.html')
context = {'products_list': products_list}
return HttpResponse(template.render(context, request))
return HttpResponse('Method not allowed', status=405)
def cart(request):
cart_list = Product.objects.filter(in_cart = True)
template_cart = loader.get_template('cart/cart.html')
context = {'cart_list': cart_list}
return HttpResponse(template_cart.render(context, request))
def add_to_cart(request, product_id):
if request.method == 'POST':
try:
product = Product.objects.get(pk=product_id)
product.in_cart = True
product.save()
return HttpResponse('', status=200)
except Product.DoesNotExist:
return HttpResponse('Product not found', status=404)
except Exception:
return HttpResponse('Internal Error', status=500)
return HttpResponse('Method not allowed', status=405)
现在,您应该将表单的操作链接更改为:
{% url 'add_to_cart' product_id=product.id %}
您不能这样做,因为在模板呈现之后,django无权更改任何内容。你可以改为使用javascript并用它处理该功能。我只是尝试在html中使用一个表单提交按钮处理POST请求,然后在我的视图中说如果request.method='POST',那么product.in_cart=True。应该工作吗?不,是的。它将工作,但在不重新生成模板的情况下不会更改模板。我认为你的问题不清楚。如果你编辑它并添加所有你想要的东西和所有相关信息,也许我可以帮助你。但现在还不清楚你到底想要什么。只是添加了更多信息,谢谢:)它不会有任何效果!由于您必须有卡的型号,然后,在用户登录时,您必须根据会话或登录用户创建卡。然后,您必须根据产品型号创建新的记录卡项目。但现在,在成功保存产品后,您将拥有所有用户的THSI产品。非常感谢!!所以我想我不用jQuery也能做到这一点,这太棒了。我将唯一字段更改为“in_cart”,将标识符更改为“buttonID”。不管用,这就是你的意思吗?(刚刚编辑了我的第一篇文章,以便您可以查看更新的表)否。您应该用产品ID替换唯一_字段
。标识符
是表单中的一个字段,其值等于产品ID。例如,如果要将id=5的产品添加到购物车,则表单中应该有一个只读字段。如果您不能这样做,请在问题中添加模板和模型代码。如果你做得对,你可以选择这个答案作为正确答案。我听说使用只读字段是个坏主意。没有别的办法吗?只是修改了索引和表格,也许你可以看看。谢谢你,这很有意义!url语句出现语法错误。可能是因为它的视图部分。应使用项目中视图的正确路径替换该零件。我刚给你留了一个样品。