Django:get_absolute_url使用reverse

zlwx9yxi  于 2023-06-25  发布在  Go
关注(0)|答案(2)|浏览(98)

未找到“news”的NoReverseMatch at / Reverse。“news”不是有效的视图函数或模式名称。
我正在制作一个新闻网站,我想通过它的蛞蝓或ID获得详细的新闻,但我没有成功,我得到一个错误NoReverseMatch at / Reverse for 'news' not found. 'news' is not a valid view function or pattern name.
views.py

from django.http import Http404
from django.shortcuts import render
from django.views.generic import ListView,DetailView
from .models import Main



class MainListView(ListView):
      queryset = Main.objects.all()
      # temp     = List.objects.all()
      template_name = "news/main_list.html"

      def get_context_data(self, *args, **kwargs):
          context = super(MainListView, self).get_context_data(*args, **kwargs)
          context['queryset'] =  Main.objects.all() 
          return context
class MainDetailSlugView(DetailView):
      queryset = Main.objects.all()
      template_name = "news/detail.html"

class HeadDetailView(DetailView):
      #queryset = Product.objects.all()
      template_name = "head/detail.html"

      def get_context_data(self, *args, **kwargs):
          context = super(ProductDetailView, self).get_context_data(*args, **kwargs)

      def get_object(self, *args, **kwargs):
          request = self.request
          pk = self.kwargs.get('pk')

         instance = Head.objects.get_by_id(pk)
         if instance is None:
            raise Http404("Product doesn't exist")  

         return instance

models.py

import random
import os
from django.core.urlresolvers import reverse
from django.db import models
from django.urls import reverse
from django.db.models.signals import pre_save, post_save
def get_filename_ext(filepath):
    base_name = os.path.basename(filepath)
    name, ext = os.path.splitext(base_name)
    return name,ext

def upload_image_path(instence, filename):
    new_filename = random.randint(1,396548799)
    name, ext = get_filename_ext(filename)
    final_filename = '{new_filename}{ext}'.format(new_filename=new_filename, ext= ext)
   return "card/{new_filename}/{final_filename}".format(new_filename=new_filename,
    final_filename=final_filename)

class MainQuerySet(models.query.QuerySet):
      def active(self):
          return self.filter(active=True)


class MainManager(models.Manager):
      def get_queryset(self):
          return MainQuerySet(self.model, using=self._db)

      def all(self):
          return self.get_queryset().all()

class Main(models.Model):
      title      = models.CharField(max_length=120)
      slug       = models.SlugField(default=True)
      description= models.TextField()
      image      = models.ImageField(upload_to=upload_image_path,null=True, blank=True)
      active     = models.BooleanField(default=True)
      timestamp  = models.DateTimeField(auto_now_add=True)

      objects = MainManager()

      def get_absolute_url(self):
          return reverse('news', kwargs={'pk': self.pk, 'slug': self.slug })
      def __str__(self):
          return self.title

      def __unicode__(self):
          return self.title

urls.py

from django.conf.urls import url


   from .views import(
          MainListView,
          MainDetailSlugView

   )

   urlpatterns = [
         url(r'^$',MainListView.as_view()),
         url(r'^(?P<pk>\d+)(?:/(?P<slug>[\w\d-]+))?/$',MainDetailSlugView.as_view(), name='Main'),
   ]

card.html

<div class="card" style="width: 30rem;">
    {% if instance.image %}
    <img class="card-img-top" src="{{ instance.image.url }}" alt="{{ instance.tile }} logo">
    </a>
    {% endif %}   
<div class="card-body">
<!--    <h5 class="card-title">{{ instance.title }}</h5> -->
<p class="card-text"><h5>{{ instance.description }}</h5></p>
<a href="{{ instance.get_absolute_url }}" class="btn btn-primary">Read more</a> 

</div>
</div>

给予一些关于通过id或slug获取数据的想法。感谢帮助

rqenqsqc

rqenqsqc1#

替换:

def get_absolute_url(self):
      return reverse('news', kwargs={'pk': self.pk, 'slug': self.slug })

有:

def get_absolute_url(self):
      return reverse('Main', kwargs={'pk': self.pk, 'slug': self.slug })
2ledvvac

2ledvvac2#

如果你已经在应用的www.example.com中有了一个路径,那么在模型中使用get_absolute_url的原因是什么urls.py:
url(r'^(?P\d+)(?:/(?P[\w\d-]+))?/$',MainDetailSlugView.as_view(),name='Main')

相关问题