将对象ID传递给URL Django Python

时间:2016-03-22 04:08:41

标签: python django

我是Django的新手,所以我很难理解哪些信息最适合尝试并找到我的问题的答案。

我按照教程学习Django。该类创建了一个购物车。我有一个问题,我无法将商品添加到购物车或删除它们。对我来说看起来很可疑的主要事情是,在数据库中,当我查看购物车时,会有一个下拉菜单来选择书籍,而不是书名Book Object。我相信这是问题,但我不确定如何排除故障。
enter image description here

我开始认为这个问题可能是版本的差异。本教程使用的是更高版本。我正在使用

python 2.7.10 django 1.9.4

我认为这取决于我的模型和我的观点

要添加到购物车并删除

的网址
url(r'^add/(\d+)', views.add_to_cart, name='add_to_cart'),  
url(r'^remove/(\d+)', views.remove_from_cart, name='remove_from_cart'),

这是Cart和BookOrder的模型

   from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User

class Author(models.Model):
    first_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=100)

    def __unicode__(self): 
        return "%s, %s" % (self.last_name, self.first_name)


def cover_upload_path(instance,filename):
    return '/'.join(['books',str(instance.id),filename])


class Book(models.Model):
    title = models.CharField(max_length=200)
    author = models.ForeignKey(Author)
    description = models.TextField()
    publish_date = models.DateField(default=timezone.now)
    price = models.DecimalField(decimal_places=2, max_digits=8)
    stock = models.IntegerField(default=0)
    cover_image = models.ImageField(upload_to=cover_upload_path, default='books/empty_cover.jpg')

class Review(models.Model):
    book = models.ForeignKey(Book)
    user = models.ForeignKey(User)
    publish_date = models.DateField(default=timezone.now)
    text = models.TextField()
    latitude= models.FloatField(max_length=20, default="37.41920")
    longitude= models.FloatField(max_length=20, default="122.8574")

class Cart(models.Model):
    user = models.ForeignKey(User)
    active = models.BooleanField(default=True)
    order_date = models.DateField(null=True)
    payment_type = models.CharField(max_length=100, null=True)
    payment_id = models.CharField(max_length=100, null=True)

    def add_to_cart(self, book_id):
        book = Book.objects.get(pk=book_id)
        try:
            preexisting_order = BookOrder.objects.get(book=book, cart=self)
            preexisting_order.quantity += 1
            preexisting_order.save()
        except BookOrder.DoesNotExist:
            new_order = BookOrder.objects.create(
                book=book,
                cart=self,
                quantity=1
                )
            new_order.save()

    def remove_from_cart(self, book_id):
        book = Book.objects.get(pk=book_id)
        try:
            preexisting_order = BookOrder.objects.get(book=book, cart=self)
            if preexisting_order.quantity > 1:
                preexisting_order.quantity -= 1
                preexisting_order.save()
            else:
                preexisting_order.delete()
        except BookOrder.DoesNotExist:
            pass


class BookOrder(models.Model):
    book = models.ForeignKey(Book)
    cart = models.ForeignKey(Cart)
    quantity = models.IntegerField()

以下是添加和删除购物车的视图。

def add_to_cart(request,book_id):
        if request.user.is_authenticated():
            try:
                book = Book.objects.get(pk=book_id)
            except ObjectDoesNotExist:
                pass
            else :
                try:
                    cart = Cart.objects.get(user = request.user, active = True)
                except ObjectDoesNotExist:
                    cart = Cart.objects.create(user = request.user)
                    cart.save()
                    cart.add_to_cart(book_id)
                    return redirect('cart')
                else:
                    return redirect('index')


def remove_from_cart(request, book_id):
    if request.user.is_authenticated():
        try:
            book = Book.objects.get(pk = book_id)
        except ObjectDoesNotExist:
            pass 
        else:
            cart = Cart.objects.get(user = request.user, active = True)
            cart.remove_from_cart(book_id)
        return redirect('cart')
    else:
        return redirect('index')

2 个答案:

答案 0 :(得分:1)

在模型中添加__str__()__unicode__()方法。每当需要对象的字符串表示时,就调用该方法,例如,当您在下拉菜单中显示为选项时看到。

您可以返回任何适合您的字符串。

样品:

class Cart(models.Model):
    ...
    def __str__(self,):
        return str(self.id)
        #OR
        return str(self.user)+str(self.id)

答案 1 :(得分:1)

为了能够查看对象名称而不是查看extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.viewcode', 'sphinx.ext.napoleon', 'sphinx.ext.intersphinx', ] html_theme = 'alabaster' ,您需要在模型中定义Model object方法。

购物车型号:

__unicode__

通过定义此功能,您将能够看到“用户名的购物车”

对于BookOrder模型

class Cart(models.Model):
    ...
    [fields]
    ...

    def __unicode__(self):
        return "%s's cart" % self.user.username

通过定义,您将能够看到书名如“我的书名”。