简体   繁体   English

分配错误之前引用了本地变量“用户”

[英]local variable 'user' referenced before assignment error

I keep getting the error "local variable 'user' referenced before assignment". 我不断收到错误“分配前已引用本地变量'user'”。 I'm trying to replicate the user = line of code in this function: 我正在尝试在此函数中复制user =代码行:

def profile_view(request, username):
    user = get_object_or_404(User, username=username)

withing this function, as you can see on on the bottom line: 具有此功能,如您在底行上看到的:

def like_user(request, id):
    pending_like = get_object_or_404(User, id=id)
    user_like, created = UserLike.objects.get_or_create(user=request.user)
    user = get_object_or_404(User, username=user.username)

however as im not passing through username into the function, so I'm trying to use user.username but i get the error "local variable 'user' referenced before assignment". 但是,因为即时消息没有通过用户名传递给函数,所以我尝试使用user.username,但是出现错误“分配前引用了本地变量'user'”。 What is the best way round this? 最好的办法是什么? am i do it completely wrong? 我做错了吗? should i try and pass in username, because when i do i get the error "like_user() takes exactly 3 arguments (2 given)". 我应该尝试传递用户名吗,因为执行此操作时会出现错误“ like_user()恰好接受3个参数(给定2个)”。 Sorry quite new to django, any help would be massively appreciated! 抱歉,django刚起步,对您的帮助将不胜感激!

Thanks 谢谢

Try request.user.username instead of user.username 尝试使用request.user.username而不是user.username
It should work 它应该工作

def profile_view(request, username):
    user = get_object_or_404(User, username=username)

if this is a view function and your intention is to see someone else profile then you have to make changes in urls.py: 如果这是一个查看功能,并且您打算查看其他人的个人资料,那么您必须在urls.py中进行更改:

urlpatterns = [
    url(r'^profile/(?P<username>[\w]+)$', profile_view), 
    # you have to pass the parameter in the url
]

otherwise is hard to understand what you want to do 否则很难理解你想做什么

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM