【问题标题】:Type error with django class based view使用基于 django 类的视图键入错误
【发布时间】:2014-01-29 19:37:23
【问题描述】:

我收到这个错误

/author/list/4 处的类型错误 super(type, obj): obj 必须是 type 的实例或子类型

异常位置:/home/ronald/best/A2/0124/vort/larb/views.py 在 get_context_data 中,第 140 行

context = super(AuthorCreate, self).get_context_data(**kwargs)

url.py

url(r'^author/list/(?P<user_id>\d+)$', AuthorList.as_view(), name='author_list' ),

列表视图的views.py

class AuthorList(LoginRequiredMixin, ListView):
    template_name = 'authorList.html'
    queryset = Author.objects.all()

    def get_context_data(self, **kwargs):
        context = super(AuthorCreate, self).get_context_data(**kwargs)
        if int(self.kwargs['user_id']) != self.request.user.id:
            raise PermissionDenied
        return context

作者列表.html

   {{ request.user.username}} 

    <ul>
        {% for author in object_list %}
            <li>{{ author.firstName }}
                 <a href="{% url "author_update" author.id %}">{{ author.firstName }}</a>
                 <a href="{% url "author_delete" author.id %}">delete</a>
            </li>
         {% endfor %}
    </ul>

【问题讨论】:

    标签: django django-views django-class-based-views


    【解决方案1】:

    代码应该是这样的:

    class AuthorList(LoginRequiredMixin, ListView):
        template_name = 'authorList.html'
        queryset = Author.objects.all()
    
        def get_context_data(self, **kwargs):
            context = super(AuthorList, self).get_context_data(**kwargs)
            if int(self.kwargs['user_id']) != self.request.user.id:
                raise PermissionDenied
            return context
    

    在 context = Super(...).get_context_data 中,我将其从 AuthorCreate 更改为 AuthorList

    【讨论】:

    • 我仍然收到错误消息。 /author/list/4 处的 NoReverseMatch 使用参数“(1,)”和关键字参数“{}”反转“author_update”。尝试了 1 种模式:['author/(?P\\d+)/(?P\\d+)$']
    • 我相信这个问题与你在这篇文章中提出的问题无关。要诊断问题,需要更多有关它的信息.. 例如来自视图和 url 的代码以及错误堆栈跟踪
    • 如果你能帮助我解决我的其他问题,我已经检查了你的答案,谢谢。
    • 我已经回答了——如果有帮助请告诉我:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-07
    • 2014-01-21
    • 2014-02-16
    • 1970-01-01
    • 2018-05-14
    相关资源
    最近更新 更多