【问题标题】:user profile of other user shows up显示其他用户的用户资料
【发布时间】:2016-08-20 14:22:43
【问题描述】:

当我在管理面板打开 admin 用户时,admin 的 id 是 1。同样michael 的 id 是 2 但是当我点击个人资料图标而不是向我显示管理员个人资料时,我得到了michael 的个人资料。为了获得我使用了user.idrequested 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


【解决方案1】:

只需在您使用profile_id的任何地方添加1

def profile(request, profile_id):
    if profile_id is "0": # Is profile_id a string or integer?
        userProfile = get_object_or_404(UserProfile, pk=(profile_id+1)) # What does this do?
    else:
        userProfile = get_object_or_404(UserProfile, pk=(profile_id+1))
        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 })

我怀疑您的代码中的某处存在 n-1 问题(即计算机从 0 开始计数,但人类从 1 开始计数)。我还没有找到它的确切位置,但在此期间这可能会用作绷带解决方案。

另外,我不确定if 在您的代码中做了什么,如果profile_id 是一个整数,它似乎永远不会被使用。

【讨论】:

  • 如果我用 slug 代替 id 怎么办?但我认为如果我使用 slug,我必须使用 pre_save 信号以 user.username 的名称保存 slug。我说的对吗?
  • 好的,在这种情况下,您将在模型中创建一个 slug 字段,您可以在保存实例的任何位置设置 slug,如果您愿意,可以在 pre_save 中进行。您还必须让 url 路由器将 slugs 传递给您的视图,而不是整数。
  • 我在答案中发布了我的新解决方案,但我将您的答案标记为已回答。感谢您的帮助。
【解决方案2】:

我使用 slug 而不是 id,对于使用 slug,我使用了 pre_save 信号,其中 slug 值取自用户名。

def profile(request, profile_slug):
    if profile_slug is None:
        userprofile = get_object_or_404(UserProfile,slug=profile_slug)
    else:
        userprofile = get_object_or_404(UserProfile, slug=profile_slug)
        user_restaurant = userprofile.restaurant.all()
        user_order = userprofile.order_history.all()
        total_purchase = userprofile.total_purchase
    return render(request, 'userprofiles/profile.html', {'userprofile':userprofile, 
                                                        'user_restaurant':user_restaurant,
                                                        'user_order':user_order,
                                                        'total_purchase':total_purchase})

我是这样填充slug的值的。

def create_slug(instance, new_slug=None):
    print('instance',instance.user)
    slug = slugify(instance.user.username)
    if new_slug is not None:
        slug = new_slug
    qs = UserProfile.objects.filter(slug=slug).order_by("-id")
    exists = qs.exists()
    if exists:
        new_slug = "%s-%s" %(slug, qs.first().id)
        return create_slug(instance, new_slug=new_slug)
    return slug


def pre_save_post_receiver(sender, instance, *args, **kwargs):
    if not instance.slug:
        instance.slug = create_slug(instance)

from django.db.models.signals import pre_save
pre_save.connect(pre_save_post_receiver, sender=UserProfile)

【讨论】:

    猜你喜欢
    • 2019-11-29
    • 2021-03-09
    • 1970-01-01
    • 1970-01-01
    • 2015-05-14
    • 1970-01-01
    • 1970-01-01
    • 2013-05-12
    • 2021-06-26
    相关资源
    最近更新 更多