类视图返回对象没有属性' rindex'错误

时间:2016-04-25 16:58:17

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

我试图将function based view重写为class based view。它引发了这个错误:

.../test/User1
  

' UserDetailView'对象没有属性' rindex'

问题可能很明显,我是class based views中的新人。

那么如何使用网址.../test/username获取任何个人资料?

我的新观点:

class UserDetailView(DetailView):
    model = User
    def get_object(self, queryset=None):
        return get_object_or_404(self.model, pk=self.kwargs["pk"])

URLS.PY:

url(r'^test/(?P<username>[a-zA-Z0-9]+)/$', views.UserDetailView(),name="user_detail"),

模板:

{% extends "base.html" %}

{% block content %}

{{ userprofile.as_p }}
{% endblock %}

我的观点是:

def get_user_profile(request, username):
    user = User.objects.get(username=username)

    jobs = user.jobs.all()
    table = MyJobsTable(jobs)

    context = {
        'my_jobs': table,
        "user": user
    }
    return render(request, 'auth/profiles/my-profile.html', context=context)

和HTML:

{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% load render_table from django_tables2 %}
{% block content %}
    {% if user.is_authenticated %}
        <h3>{% if user.userprofile.is_translator %} Prekladateľský účet: {% else %} Štandardný
            účet: {% endif %}{{ user.username }} </h3>
        <ul>
            <li>Username: {{ user.username }}</li>
            <li>First name: {{ user.first_name }}</li>
            <li>Last name: {{ user.last_name }}</li>
            <li>Email: {{ user.email }}</li>
            <li>Telephone: {{ user.userprofile.telephone }}</li>
            <li>Languages: {{ user.userprofile.languages.as_p }}</li>
            {#            TODO: DOPLNIT ATRIBUTY + ked je aj translator#}
        </ul>
        {% if user.jobs %}
            <p>My Jobs</p>
            {% render_table my_jobs %}
        {% else %}
            <p>You have no jobs</p>
        {% endif %}
        <form class="navbar-form navbar-right" action="/edit-profile" method="get">
            <button type="submit" class="btn btn-success">Edit Your Profile</button>
        </form>
        <form class="navbar-form navbar-right" action="/register-as-translator" method="get">
            <button type="submit" class="btn btn-success">Become A Translator</button>
        </form>
    {% endif %}
{% endblock %}

URLS.PY:

url(r'^profile/(?P<username>[a-zA-Z0-9]+)/$', views.get_user_profile)

1 个答案:

答案 0 :(得分:1)

问题出在您的urls.py中。使用基于类的视图,您始终需要使用as_view classmethod

url(r'^test/(?P<username>[a-zA-Z0-9]+)/$', views.UserDetailView.as_view(), name="user_detail"),
相关问题