重定向 Django 视图

Redirect a Django view

用户登录我的应用程序后,我想将此人重定向到他们的个人资料。
但是,我不断收到此错误:

TypeError at /app/url/username/
profile() got an unexpected keyword argument 'username'

这是模型:

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 模式:

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.

我发现您的代码中存在两个可能的问题:

第一个,在 user_login 函数中创建 url 以使用 reverse() 进行重定向时,您应该在 args 中传递 username 值而不是 kwargs:

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

其次,您似乎将配置文件 url 中的参数命名为 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)
            ...
    ...

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

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})