Django URL翻倍

时间:2018-12-10 14:15:10

标签: python django django-models django-urls

当我单击锚标记进入产品的详细视图时,URL会加倍。

http://127.0.0.1:8000/products/products/t-shirt/

我认为应该是这样的:

http://127.0.0.1:8000/products/t-shirt/

List.html

{% for object in object_list  %}
<a href="{{ object.get_absolute_url }}">{{object.title}}</a>
<br>
{{object.description}}
<br>
{{object.price}}
<br>
<br>
{% endfor %}

models.py

class Product(models.Model):
title = models.CharField(max_length=120)
slug = models.SlugField(blank=True, unique=True)
description = models.TextField()
price = models.DecimalField(decimal_places=2, max_digits=19, default=39.99)
image = models.ImageField(upload_to=upload_image_path, null=True, blank=True)
featured = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)

# For url when you click a product
def get_absolute_url(self):
    return "products/{slug}/".format(slug=self.slug)


def __str__(self):
    return self.title

urls.py

from django.conf.urls import url

从products.views导入(product_view,                             product_detail_view,                             product_featured_view,                             )

urlpatterns = [
url(r'products/$', product_view),
url(r'products/(?P<slug>[\w-]+)/$', product_detail_view),
url(r'featured/$', product_featured_view),

]

view.py

from django.shortcuts import render, get_object_or_404, Http404

from .models import Product

def product_view(request):
    queryset = Product.objects.all()
    context = {
        'object_list': queryset,
        # 'featured': fqueryset
    }
    return render(request, 'products/list.html', context)


def product_detail_view(request, slug=None, *args, **kwargs):
    try:
        instance = get_object_or_404(Product, slug=slug)
    except Product.DoesNotExist:
        raise Http404("Not Found..")
    except Product.MultipleObjectsReturned:
        queryset = Product.objects.filter(slug=slug)
        instance = queryset.first()

    context = {
        'object': instance
    }
    return render(request, 'products/detail.html', context)


def product_featured_view(request):
    queryset = Product.objects.filter(featured=True)
    context = {
    'object_list': queryset
    }
    return render(request, 'products/featured-list.html', context)

1 个答案:

答案 0 :(得分:2)

您需要以不同的方式声明Product.get_absolute_url

def get_absolute_url(self):
    return "/products/{slug}/".format(slug=self.slug)

我也建议您通过reverse进行声明,如此处get_abosolute_url所示。