如何使用POST请求Django更改布尔值 [英] How can I change a boolean value with POST request Django

查看:163
本文介绍了如何使用POST请求Django更改布尔值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看不出我的代码出了什么问题:

I can't see what's wrong with my code:

我的这个表包含以下列的产品:
名称,价格和添加到购物车。

I have this table with products with the following columns: Name, Price and Add to cart.

<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.name }}</td>
      <td>${{ product.price }}</td>
      <td>{% if not product.in_cart %}
              <form action="{% url 'cart' %}" method="POST">
                {% csrf_token %}
                <input type="submit" id="{{ button_id }}" value="Add to cart">
              </form>
          {% else %}
              {{ print }}
          {% endif %}
      </td>
    </tr>
    {% endfor %}
  </table>

这些是我的观点:

def index(request):
    if request.method == 'POST':
            product = Product.objects.get(id=request.POST.get("button_id"))
            product.in_cart = True
            product.save()
    elif 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))


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))

型号:

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

基本上在我的数据库中我有一个名为in_cart的列默认情况下为False,表示产品不在购物车中。
在html中,我在每个产品旁边添加了一个名为添加到购物车的按钮。此按钮是我指定为POST请求的表单的提交。
我这样做,所以在我的views.index上面我有条件说,如果请求是POST,这意味着如果用户点击提交按钮,则in_cart的值变为true。然后在我的views.cart中我有一个名为cart_list的变量,它存储了in_cart值为True的产品,这样当我去购物车/我看到用户选择的产品时。

Basically in my database I have a column called in_cart which is by default False, meaning that the product is not in the cart. In the html, I added a button next to each product called "Add to cart". This button is a submit from a form which I specified as a POST request. I did that so in my views.index above I have a conditional that says if the request is POST, meaning if the user clicks on the submit button, then the value of in_cart becomes true. Then in my views.cart I have a variable called cart_list which stores the products which in_cart value is True, so that when I go to cart/ I see the products that the user selected.

然而这不起作用。

有什么想法吗?

这就是它的样子在localhost中:

This is what it looks like in localhost:

推荐答案

首先,你的如果语句无法访问。因为你之前有返回。当您在函数中调用 return 时, return 之后的下一行函数将不会执行。

First of all, your if statement is not reachable. Because you had a return before it. When you call return in a function, the next lines of function those are after the return will not execute.

所以你应该改变索引函数。
此外,您应该使用您的发布请求发送产品的标识符。标识符可以是模型中的id或任何其他唯一字段。

So you should change the index function. Also, you should send an identifier of the product with your post request. Identifier could be the id or any other unique field in your model.

所以你的代码应该是这样的:

So your code should be something like this:

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()
        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.

我在代码的注释中添加了您需要的所有信息。我认为你应该花更多的时间在python和django文档上。但如果您还有任何疑问,可以在评论中提问。
问题编辑后
如果您不想在表单中使用只读字段,则应在代码中进行两处更改。
首先,您应该在 urls.py 文件中添加一个带 product_id 参数的网址。这样的事情:

I added all information you need in the comments of the code. I think you should spend more time on python and django documents. But if you still have any questions, you can ask in comments. After question edit If you don't want to use a readonly field in your form, you should make two changes in your code. First of all, you should add a url with product_id parameter in your urls.py file. Something like this:

url(r'^add_to_cart/(?P<product_id>[0-9]+)$', 'add_to_cart_view', name='add_to_cart')

然后你应该从添加单独的add_to_cart视图code> index 查看。您的观点应如下所示:

Then you should add separate your add_to_cart view from index view. Your views should be like this:

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()
        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)

现在您应该将表单的操作链接更改为此:

Now you should change the action link of your form to this:

{% url 'add_to_cart' product_id=product.id %}

这篇关于如何使用POST请求Django更改布尔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆