django get_absolute_url搜索结果

时间:2018-05-02 02:55:52

标签: python django url django-queryset

我在Django = 1.11上构建棋盘Web应用程序,并尝试找出它的搜索查询。我关注了url.pymodels.py,'views.py`和结构

结构

blog--- blog
     |    |- urls.py
     |    |- setting.py
     |
     |- boards
           |- models.py
           |- views.py
           |- templates
                 |- search.html

urls.py

url(r'^search/$', boards_views.search_list, name="search"),
url(r'^boards/(?P<pk>\d+)/$', TopicListView.as_view(), name="board_topics"),
url(r'^boards/(?P<pk>\d+)/topics/(?P<topic_pk>\d+)/$',PostListView.as_view(), name="topic_posts"),

models.py

class Board(models.Model):
    name = models.CharField(max_length=50)

class Topic(models.Model):
    subject = models.CharField(max_length=255)
    board = models.ForeignKey(Board, related_name='topics', on_delete=models.DO_NOTHING)
    views = models.PositiveIntegerField(default=0)

class Post(models.Model):
    tag = models.CharField(max_length=300)
    message = models.CharField(max_length=1000, default="")
    topic = models.ForeignKey(Topic, related_name='posts', on_delete=models.DO_NOTHING)
    def get_absolute_url(self):
        return reverse("blog:topic_posts", args=[self.id])

views.py

class PostListView(ListView):
    model = Post
    context_object_name = 'posts'
    template_name = 'topic_posts.html'
    paginate_by = 5 

    def get_context_data(self, **kwargs):
        session_key = 'viewed_topic_{}'.format(self.topic.pk)
        if not self.request.session.get(session_key, False):
            self.topic.views += 1
            self.topic.save()
            self.request.session[session_key] = True
        kwargs['topic'] = self.topic
        return super().get_context_data(**kwargs)

    def get_queryset(self):
        self.topic = get_object_or_404(Topic, board__pk=self.kwargs.get('pk'), pk=self.kwargs.get('topic_pk'))
        queryset = self.topic.posts.order_by('created_at')
        return queryset

class TopicListView(ListView):
    model = Topic
    context_object_name = 'topics'
    template_name = 'boards/topics.html'
    paginate_by = 5 

    def get_context_data(self, **kwargs):
        kwargs['board'] = self.board
        return super().get_context_data(**kwargs)

    def get_queryset(self):
        self.board = get_object_or_404(Board, pk=self.kwargs.get('pk'))
        queryset = self.board.topics.order_by('-last_updated').annotate(replies=Count('postss') - 1)
        return queryset

def search_list(req):
    Post_list = Post.objects.all()
    topic = Topic.objects.all()
    q = req.GET.get('q', '')
    if q:
        post_list = post_list.filter(post__icontains=q)
    context = {
        "filter" : post_list,
        "q" : q,
        "topics": topic,
    }
    return render(req, "search.html", context)

search.html

{% if q %}
{% for post in filter %}
<a href="{{ post.get_absolute_url }}">{{ post.topic }}</a>



我在我的网络应用程序中有搜索功能,一旦我进行搜索,它就会显示搜索结果。我试图在每个结果中插入link,以便用户可以直接点击指向该帖子的链接。我认为get_absolute_url可以是简单而好的解决方案,但实施起来没有好运。它会抛出NoReverseMatch at /search'blog' is not a registered namespace。我认为命名空间是我的项目的名称,并传递blog但失败了。然后我传递了我的应用程序board的名称,甚至没有命名空间但仍然失败。我在这里缺少什么?

提前致谢!

1 个答案:

答案 0 :(得分:1)

修改您的get_absolute_url,最好使用其名称调用网址,并使用**kwargs提供所有参数:

self.topic = get_object_or_404(Topic,
    board__pk=self.kwargs.get('pk'), pk=self.kwargs.get('topic_pk'))
  • self.topic.pk因为在您的网址topic_pk中,pk=self.kwargs.get('topic_pk')代表您的观点中所述

  • self.topic.board.id因为您的观点中描述的?P<pk>\d+内容为board__pk=self.kwargs.get('pk'),因此pk必须来自主页

<强>码

def get_absolute_url(self):
    if self.topic:
        return reverse("topic_posts",
                     kwargs={"topic_pk":self.topic.pk,"pk":self.topic.board.id})