重定向Django视图

时间:2015-08-08 23:18:22

标签: django redirect registration reverse profile

用户登录我的应用后,我想将此人重定向到他们的个人资料 但是,我一直收到这个错误:

  

/ app / url / username /
的TypeError   profile()得到了一个意想不到的关键字参数'用户名'

以下是模型:

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    profile_picture = models.ImageField(upload_to='profile_images', blank = True)

        def __str__(self):
            return self.user.username

以下是用户将登录的视图,然后将用户重定向到配置文件:

def user_login(request):


    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')

        user = authenticate(username=username, password=password)

        if user:
           if user.is_active:
               login(request, user)

               url = reverse('profile', kwargs={'username': username})
            return redirect(url)

           else:
               return HttpResponse("Please login.")

         else:
             print("Invalid login details: {0}, {1}".format(username, password))
             return HttpResponse("Invalid login details supplied.")

     else:
         return render(request, 'reviews/login.html', {})

以下是用户个人资料的视图:

@login_required
def profile(request, user):
    user = UserProfile.objects.get(user = request.user)
    return render(request, 'reviews/profile.html', {'username':username})

以下是网址格式:

url(r'^profile/(?P<username>\w+)/$', views.profile, name='profile')

有人可以告诉我如何将登录用户重定向到他们的个人资料吗?

到目前为止尝试了两种方法。我收到了这两个错误:

UserProfile匹配查询不存在。

这是追溯:

Environment:


Request Method: GET
Request URL: http://localhost:8000/app/profile/username/

Django Version: 1.8.3
Python Version: 3.4.3
Installed Applications:
('grappelli',
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'reviews',
 'compressor',
 'cloudinary')
 Installed Middleware:
 ('django.contrib.sessions.middleware.SessionMiddleware',
  'django.middleware.common.CommonMiddleware',
  'django.middleware.csrf.CsrfViewMiddleware',
  'django.contrib.auth.middleware.AuthenticationMiddleware',
  'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
  'django.contrib.messages.middleware.MessageMiddleware',
  'django.middleware.clickjacking.XFrameOptionsMiddleware',
  'django.middleware.security.SecurityMiddleware')


Traceback:
File "/var/www/nurse/lib/python3.4/site-   packages/django/core/handlers/base.py" in get_response
132.                     response = wrapped_callback(request,   *callback_args, **callback_kwargs)
File "/var/www/nurse/lib/python3.4/site-  packages/django/contrib/auth/decorators.py" in _wrapped_view
22.                 return view_func(request, *args, **kwargs)
File "/var/www/nurse/nurseapp/reviews/views.py" in profile
165.      user=UserProfile.objects.get(user = request.user)                       
File "/var/www/nurse/lib/python3.4/site-packages/django/db/models/manager.py" in manager_method 127.                   return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/var/www/nurse/lib/python3.4/site-packages/django/db/models/query.py" in get 334.                 self.model._meta.object_name

Exception Type: DoesNotExist at /app/profile/username/
Exception Value: UserProfile matching query does not exist.

2 个答案:

答案 0 :(得分:2)

我在您的代码中看到两个可能的问题:

首先,在user_login函数中,在使用reverse()创建重定向网址时,您应该在username而不是args中传递kwargs值:

url = reverse('profile', args=(username,))

第二件事,似乎您将配置文件网址中的参数命名为username,这意味着它将被传递到具有相同名称的相应视图功能,因此您应将user重命名为username在视图中更新您的逻辑如下:

@login_required
def profile(request, username):
    p = UserProfile.objects.get(user__username=username)
    return render(request, 'reviews/profile.html', 
        {'username': username, 'user': p.user, 'profile': p})

请注意,对于每个User对象,必须有一个UserProfile对应。如果您在新用户注册后未创建UserProfile对象,则可以尝试将User对象发送到您的模板:

@login_required
def profile(request, username):
    user = User.objects.get(username=username)
    return render(request, 'reviews/profile.html', 
        {'username': username, 'user': user})

这是一种不好的做法,但在user_login视图中,如果用户登录后,您可以尝试创建UserProfile

def user_login(request):
    ...
    user = authenticate(username=username, password=password)   
    if user:
        if user.is_active:
            UserProfile.objects.get_or_create(user=user)
            ...
    ...

答案 1 :(得分:1)

您的视角和正则表达式不匹配。将用户参数更改为用户名,我还更改了您的上下文以包含正确的变量。我还将您的重定向更改为HttpResponseRedirect,因为它更容易。您不需要更改任何其他内容。但如果您需要更多帮助,请随时发表评论。

from django.views.shortcuts import HttpResponseRedirect

def user_login(request):
   if request.method == 'POST': 
      username = request.POST.get('username')
      password = request.POST.get('password') 
      user = authenticate(username=username, password=password)   
        if user: 
            if user.is_active: 
              login(request, user)
              return HttpResponseRedirect('/profile/{0}/').format(username)
            else:
               return HttpResponse("Please login.") 
      else: 
         print("Invalid login details: {0}, {1}".format(username, password)) 
         return HttpResponse("Invalid login details supplied.") 
   else:
         return render(request, 'reviews/login.html', {})

@login_required
def profile(request, username):   
     user=User.objects.get(user = request.user)                       
     return render(request, 'reviews/profile.html', {'username':user})