django TypeError:required()获得了意外的关键字参数'username'

时间:2018-09-30 13:28:29

标签: python django

代码中没有错误,但是在运行时不起作用。 我有一个具有类似代码的项目,它可以完美运行。

错误:

Traceback (most recent call last):
File "/home/pablo/.local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/home/pablo/.local/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/pablo/.local/lib/python3.6/site-packages/django/core/handlers/base.py", line 124, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
TypeError: required() got an unexpected keyword argument 'username'

这是代码: vews.py:

def profile_view(request, username):
  user = User.objects.get(username=username)
  profile = Profile.objects.get(user=user)
  own_profile = Profile.objects.get(user=request.user)
  if request.method == 'POST':
      if 'follow' in request.POST:
          own_profile.following.add(profile)
          profile.followers.add(own_profile)
      if 'unfollow' in request.POST:
          own_profile.following.remove(profile)
          profile.followers.remove(own_profile)

  posts = Post.objects.all()[:10]
  return render(request, 'accounts/profile.html', {'profile': profile, 'own_profile': own_profile, 'posts': posts})

urls.py:

from django.urls import path
from .views import login, logout, signup, edit_profile, profile_view

app_name = 'accounts'

urlpatterns = [
    path('login/', login, name='login'),
    path('logout/', logout, name='logout'),
    path('signup/', signup, name='signup'),
    path('editprofile/', edit_profile, name='edit_profile'),
    path('<str:username>/', profile_view, name='profile'),
]

1 个答案:

答案 0 :(得分:0)

回溯说的没错:

TypeError: required() got an unexpected keyword argument 'username'

因此,错误出在已知的任何名为required()的函数中(来自问题的注释)。

尽管

我也遇到了类似的错误:

TypeError: user_profile_update() got an unexpected keyword argument 'username'

我发现, 之所以使用关键字参数'username'是因为我在urlpatterns中向path()添加了<str:username>,但是在路径视图中未使用该关键字参数'username'-user_profile_update()

因此,可以通过以下任一方法解决该问题:

  • 更改path()并删除<str:username>

OR

  • 在视图中添加关键字参数“用户名”。
def user_profile_update(request, username):
    ...