我正尝试将产品和会话中的当前用户外键用户一起添加到购物车中。我知道通常您可以执行self.request.user,但是在这种情况下添加self.request.user无法正常工作。我也尝试使用self作为参数之一来运行它。
例如:
def cart(request, self, product_id):
我还测试了不使用:
curr_user = get_object_or_404(User,user=self.request.user)
,相反:
owned_by=self.request.user
或
owned_by=request.user
用于添加到购物车以及all_posts,但均不起作用。
我收到以下代码屏幕截图的错误:
NameError at /mycart/6
name 'self' is not defined
Request Method: GET
Request URL: http://127.0.0.1:8000/mycart/6
Django Version: 2.1.3
Exception Type: NameError
Exception Value: name 'self' is not defined
Exception Location: mysrc/cart/views.py in cart, line 25
Python Executable: env/bin/python
Python Version: 3.7.0
Python Path:
views.py
#Create your views here.
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from .models import Cart
from shop.models import Products
@login_required
def cart(request, product_id):
cart = Cart(request)
product = get_object_or_404(Products,id=product_id)
curr_user = get_object_or_404(User,user=self.request.user)
cart = Cart(item=product, quantity=1, price=product.price, owned_by=curr_user)
cart.save()
all_posts = Cart.objects.filter(owned_by=curr_user)
context = {'all_posts':all_posts}
return render(request,'cart/mycart.html')
models.py
from django.db import models
from shop.models import Products
from users.models import User
from django.urls import reverse
# Create your models here.
class Cart(models.Model):
item = models.ForeignKey(Products, on_delete=models.CASCADE)
book_name = models.CharField(max_length=50)
quantity = models.IntegerField(blank=False, default=1)
price = models.DecimalField(max_digits=5, decimal_places=2, default = 0)
owned_by = models.ForeignKey(User, on_delete=models.CASCADE, default= False)
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.cart, name='cart-cart'),
path('mycart/<product_id>', views.cart, name ='cart-cart'),
]
模板文件:
{% extends "shop/base.html" %}
{% block content %}
<h3>Search Result</h3>
{% for post in posted %}
<article class="media content-section">
<div class="media-body">
<div class="article-metadata">
<small><a class="mr-2" href="{% url 'profile' %}">{{ post.seller }}</a></small>
<small class="text-muted">{{ post.date_posted }}</small>
</div>
<h3><a class="article-title">{{ post.book_name }} <span style="font-size:14px;">by {{post.author}}</span></a></h3>
<p class="article-content">{{ post.course }} | {{ post.dept_id }}</p>
<p class="article-content"><b>${{ post.price }}</b></p>
<div class="media">
<img class="rounded-circle account-img" src="{{ shop.book_img.image.url }}">
</div>
<form action="{% url 'cart-cart' product_id=post.pk %}" method="post">
<p>Unique Item ID: {{ post.pk }}</p>
<a class="btn btn-outline-info" href="{% url 'cart-cart' product_id=post.pk%}">add to cart</a>
</form>
</div>
</article>
{% endfor %} {% endblock content %}
答案 0 :(得分:0)
cart
是一个类中的方法,第一个参数必须为self
,它是该类的实例。
将cart
的签名更改为def cart(self, request, product_id)
,它应该可以工作。