1
我試圖將我的function based view
重寫爲class based view
。它提出了這樣的錯誤:類視圖返回對象沒有屬性'rindex'錯誤
.../test/User1
'UserDetailView' object has no attribute 'rindex'
這個問題可能是明顯的,我在class based views
是新。
那麼怎麼做才能使用url .../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)
謝謝,這似乎工作,但它提出了現在另一個錯誤:通用詳細視圖UserDetailView必須以一個對象PK或塞被調用。我想我不能使用用戶名,但如何使用slu??或者是不同的問題? –
您應該在類定義中設置slug_field ='username''和'slug_url_kwarg ='username''。並注意你的'get_object'方法被破壞了,但也沒有意義;你應該刪除它。 –