1

我正在构建一个需要用户配置文件的小型应用程序,我使用了 Django 的内置用户系统。但是我有一个问题,即使您没有登录,您仍然可以查看个人资料,另一件事是每个用户应该只看到他的个人资料而不是其他人我需要一些提示

视图.py

class UserProfileDetailView(DetailView):
    model = get_user_model()
    slug_field = "username"
    template_name = "user_detail.html"

    def get_object(self, queryset=None):
        user = super(UserProfileDetailView, self).get_object(queryset)
        UserProfile.objects.get_or_create(user=user)
        return user

class UserProfileEditView(UpdateView):
    model = UserProfile
    form_class = UserProfileForm
    template_name = "edit_profile.html"

    def get_object(self, queryset=None):
        return UserProfile.objects.get_or_create(user=self.request.user)[0]

    def get_success_url(self):
        return reverse("profile", kwargs={"slug": self.request.user})
4

3 回答 3

4

Since you are using the Class Based Generic View, you need to add decorator @login_required in your urls.py

#urls.py

from django.contrib.auth.decorators import login_required
from app_name import views

url(r'^test/$', login_required(views.UserProfileDetailView.as_view()), name='test'),
于 2013-10-07T04:24:24.323 回答
0

你检查过login_required装饰器吗?文档在这里

由于您似乎正在使用基于类的视图,因此您需要在 urlconf 中进行装饰,有关更多信息,请参见此处

于 2013-10-07T03:00:19.480 回答
-2

以下是您通常应该做的事情

@login_required
def my_view(request, uid):
    # uid = user id taken from profile url
    me = User.objects.get(pk=uid)
    if me != request.user:
        raise Http404
于 2013-10-07T03:03:33.650 回答