Django 2.1.2-AttributeError:“ UserProfile”对象没有属性“ object”

时间:2018-10-29 20:03:54

标签: django python-3.x django-models django-templates django-views

我在使用名为SearchView(ListView)的类时遇到了问题,该类用于显示搜索查询。此类“ SearchView”是从UserProfile视图继承的,因此用户可以使用个人资料视图中的搜索栏搜索任何帖子。当我尝试加载路由/ users ///时,出现以下错误:'UserProfile'对象没有属性'object。我猜这是因为我要覆盖get_context_data()方法。

这是SearchView类的代码:

class SearchView(ListView):
    model = Post

    def get_context_data(self, *args, **kwargs):
        context = super().get_context_data(**kwargs)
        try:
            context['list_result'] = self.result
        except:
            messages.error(self.request, 'test')
        finally:
            return context


def get(self, request, *args, **kwargs):
    if request.GET.get('search'):
        search_query = request.GET.get('search', None)
        self.result = Post.objects.filter(title__icontains=search_query).order_by()
        if not self.result:

            messages.error(request, f'No results found for {search_query}')
    return super().get(request, *args, **kwargs)   

这是UserProfile视图的代码:

@method_decorator(login_required, name='dispatch')
class UserProfile(SearchView, DetailView):
    model = User
    context_object_name = 'user_object'

    def get_context_data(self, **kwargs):
        data = super().get_context_data(**kwargs)
        try:
            relevant_post = Post.objects.filter(author_id=self.kwargs.get('pk')).order_by('-rating')[0]
            data['relevant_post'] = relevant_post
        except IndexError:
            pass
        finally:
            return data

这是搜索模板:

{% extends 'blog/base.html' %}
{% load static %}
{% block content %}
<form class="align-middle w-50" type="GET" style="margin: 0">
<span class="fa fa-search form-control-feedback"></span>
<input type="text" class="form-control" name="search" 
placeholder="Search ..">
</form>
{% if list_result %}
<h2>Results: </h2>
{% for result in list_result %}
<div class="container"> 
<article class="media content-section">
<div class="media-body">
     <div class="article-metadata">
        <img class="rounded-circle article-img" src="{{ result.author.profile.image.url }} "/>
        <a class="mr-2" href="{% url 'profile' result.author.id result.author.username %}">{{ result.author }}</a>
        <small class="text-muted">{{ result.post_date|date:"N d, o" }} .   </small>
        <div  class="float-right mt-1">
          <img src="{% static 'blog/rating_icon.svg' %}" alt="Ratings">
          <div></div>
          <medium class="ml-2">{{ result.rating }}</medium>
      </div>
        <h2><a class="article-title" href="{% url 'post-detail' result.id result.title %}">{{ result.title }}</a></h2>
        <a href="{% url 'post-detail' result.id result.title%}">
          Click here for more details.
        </a>  
      </div>
    </div>
  </article>
 </div>
{%endfor%}
{%endif%}
{%endblock%}

谢谢。

1 个答案:

答案 0 :(得分:1)

尝试将self.object = self.get_object()添加到get_context_data。因为DetailView需要一个object属性