简体   繁体   中英

Reverse for 'update_cart' with arguments '('',)' not found. 1 pattern(s) tried: ['cart/(?P<slug>[\\w-]+)/']

I am a novice in Dejango and I want to have a shopping cart, but whatever I do, this error will not be fixed. and give me following eror. please help me.

Reverse for 'update_cart' with arguments '('',)' not found. 1 pattern(s) tried: ['cart/(?P[\\w-]+)/']

cart model.py

class Cart (models.Model):
    products=models.ManyToManyField("seabookapp.Book",null=True,blank=True)
    total=models.IntegerField( default=0)
    timestamp=models.DateTimeField(auto_now_add=True,auto_now=False)
    updated=models.DateTimeField(auto_now_add=False,auto_now=True)
    active=models.BooleanField(default=True)
    def __unicode__(self):
        return "Cart id : %s"%(self.id)

book model.py

class Book (models.Model):
    BookID= models.AutoField(primary_key=True)
    Titel=models.CharField(max_length=150 )
    Author=models.ForeignKey('Author',on_delete=models.CASCADE)
    Publisher=models.ForeignKey('Publisher',on_delete=models.CASCADE)
    slug=models.SlugField(unique=True)
    GenerName=models.ForeignKey('category',on_delete=models.CASCADE)
    Price= models.IntegerField(null='true',blank='true')
    Discount= models.IntegerField(null='true',blank='true')
    AfterDiscount= models.IntegerField(null='true',blank='true')

veiw.py

def show_Book(request,BookID):
    template_name = 'showBook.html'
    showBook=get_object_or_404(Book,BookID=BookID)
    commentss = showBook.comments.filter(active=True)
    comments = showBook.comments.filter(active=True).order_by('-Created_on')[0:4]
    new_comment = None
    name = None
    book =None
    is_favorite=False
    if showBook.favorit.filter(id=request.user.id).exists():
        is_favorite=True

    # Comment posted
    if request.method == 'POST':
        comment_form = BookCommentForm(data=request.POST)

        if comment_form.is_valid():

            # Create Comment object but don't save to database yet
            new_comment = comment_form.save(commit=False)

            # Assign the current post to the comment
            new_comment.post = comments
            # Save the comment to the database
            comment_form.instance.name = name
            comment_form.instance.book = request.book
            new_comment.save()
    else:
        comment_form = BookCommentForm()

    return render (request , 'showBook.html', {
                                            'showBook':showBook ,
                                            'comments': comments,
                                            'new_comment': new_comment,
                                            'comment_form': comment_form,
                                            'commentss':commentss,
                                            'book':book,
                                            'is_favorite':is_favorite,

                                            })

def view (request):
    cart=Cart.objects.all()[0]
    products=Book.objects.all()
    context={"cart":cart,'products':products}
    template="view.html"
    return render (request,template, context)
def update_cart(request,slug):
    cart=Cart.objects.all()[0]
    try:
        product=Book.objects.get(slug=slug)
    except Book.DoesNotExist:
        pass
    except:
        pass
    if not product in cart.products.all():
        cart.products.add(product)
    else:
        cart.products.remove(product)
    new_total=0
    for item in cart.products.all():
        new_total += item.Price
    cart.total=new_total
    cart.save()
    return HttpResponseRedirect(reverse('cart'))

showbook.html

{% if showBook.Price is not None %}

                <li id="sell"><a href="{% url 'update_cart' product.slug %}">add to card<i class="fas fa-cart-plus"></i></a>    </li>
            
            {% else %}
                <li id="sell"><a href="{{Book.filebook}}" download="{{Book.filebook}}">download  <i class="fas fa-cloud-download-alt"></i></a>  </li>
            {% endif %}

url.py

path('books/<int:BookID>', views.show_Book, name='show_book'),
    url('cart/', views.view,name='cart'),
    url('cart/(?P<slug>[\w-]+)/',views.update_cart,name='update_cart')

I would define the urls.py this way:

from django.urls import path, re_path


urlpatterns = [
    path('books/<int:BookID>', views.show_Book, name='show_book'),
    path('cart/', views.view, name='cart'),
    re_path(r'^cart/(?P<slug>[\w-]+)/$',views.update_cart, name='update_cart')
]

Note I slightly changed the last URL regex patter - I bet you version was not a correct regex and you didn't mark it as regex with r'' and $ at the end of a matching pattern.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM