caldf
caldf

Reputation: 71

local variable 'user' referenced before assignment error

I keep getting the error "local variable 'user' referenced before assignment". I'm trying to replicate the user = line of code in this function:

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". 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)". Sorry quite new to django, any help would be massively appreciated!

Thanks

Upvotes: 0

Views: 467

Answers (2)

devcodexyz
devcodexyz

Reputation: 65

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:

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

Upvotes: 0

Artem Bernatskyi
Artem Bernatskyi

Reputation: 4687

Try request.user.username instead of user.username
It should work

Upvotes: 0

Related Questions