【发布时间】:2016-08-20 14:22:43
【问题描述】:
当我在管理面板打开 admin 用户时,admin 的 id 是 1。同样michael 的 id 是 2 但是当我点击个人资料图标而不是向我显示管理员个人资料时,我得到了michael 的个人资料。为了获得我使用了user.id 的requested user 的ID。
另外问题是我不能在这样的模型中使用 slug。
餐厅/base.html
{% if user.is_authenticated %}
<li class="nav-item">
<a class="nav-link user-icon" href="{% url 'userprofiles:profile' user.id %}">
<i class="fa fa-user"></i>
</a>
</li>
{% else %}
userprofiles/urls.py
urlpatterns = [
# url(r'^profile/(?P<profile_name>[-\w]+)/(?P<profile_id>\d+)/$', views.profile, name='profile'),
url(
r'^profile/(?P<profile_id>\d+)/$',
views.profile,
name='profile'
),
]
userprofiles/views.py
def profile(request, profile_id):
if profile_id is "0":
userProfile = get_object_or_404(UserProfile, pk=profile_id)
else:
userProfile = get_object_or_404(UserProfile, pk=profile_id)
user_restaurant = userProfile.restaurant.all()
user_order = userProfile.order_history.all()
total_purchase = 0
for ur in user_order:
total_purchase += ur.get_cost()
return render(
request,
'userprofiles/profile.html',
{
'userProfile':userProfile,
'user_restaurant':user_restaurant,
'user_order':user_order,
'total_purchase':total_purchase
}
)
userprofiles/profile.html
{% for user_restaurant in user_restaurant %}
{{user_restaurant.name}}<br/>
{{user_restaurant.address }}
{% endfor %}
userprofiles/models.py
class UserProfile(models.Model):
user = models.OneToOneField(User)
restaurant = models.ManyToManyField(Restaurant)
order_history = models.ManyToManyField(OrderMenu)
# favorites = models.ManyToManyField(Restaurant)
is_owner = models.BooleanField(default=False)
class Meta:
def __str__(self):
return self.user.username
# def get_absolute_url(self):
# return reverse('userprofiles:profile', kwargs={'slug':self.slug, 'id':self.id})
如何将 slug 用于此类模型,以便在管理面板中自动保存该用户的 slug?因为没有post方法。
但主要问题是我正在获取另一个用户的用户资料。
【问题讨论】:
-
如果你创建了第三个 id=3 的用户,你会得到 Michael 吗?
-
有 3 个用户。一个管理员,一个迈克尔,另一个匿名。如果我这样做localhost:8000/userprofiles/profile/1,我会得到 michael 的用户个人资料,/2/ 显示匿名用户个人资料,/3/ 显示 404 错误。
-
在管理面板中,我检查了用户 admin 的 id 为 1,michael 为 2,anonymous 为 3。
标签: python django django-models django-views