Ravin Kohli
Ravin Kohli

Reputation: 153

request object does not have a user Django

I am making a wallet app so if someone goes to http://127.0.0.1:8000/add_money/ to add money and they press submit the money has to be added to their wallet but after submit there is an error:

AttributeError at /add_money/ 'unicode' object has no attribute 'user'

I have put some checkpoints for better understanding the flow of operations:

Request <WSGIRequest: GET '/add_money/'>
Request  j <WSGIRequest: GET '/add_money/'>
[15/Dec/2016 15:26:34] "GET /add_money/ HTTP/1.1" 200 420
Request <WSGIRequest: POST '/add_money/'>
Request 3
[15/Dec/2016 15:26:37] "POST /add_money/ HTTP/1.1" 500 66535

add_money view

def add_money(request):
    print ("Request %s" % request)
    if request.user:
        if request.POST and request.POST.get('amount'):
            username = request.user.username
            add_amount = request.POST.get('amount')
            wallet = Wallet.objects.filter(username=username).update(add_money(add_amount))
            now = datetime.now()
            trans = Transaction(from_name=username, wallet_id=wallet.id, date=now, amount=add_amount)
            trans.save()
            print ("Request s %s" % request)
            return render(request, 'user_profile.html', {'user': request.user})
        else:
            print ("Request  j %s" % request)
            return render(request, 'add_money.html')
    else:
        print ("Request rf %s" % request)
        return HttpResponseRedirect('/login/?next={}'.format('/add_money/'))

//add_money template

<form method="post">
    Amount:<input type="number" name="amount">
    <input type="submit" value="Submit">
    <button type="button" name="cancel">Cancel</button>
    {% csrf_token %}
</form>

EDIT 1 Traceback:

File "/Users/ravinkohli/env_app_pw/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
  132.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/ravinkohli/PycharmProjects/untitled1/wallet/views.py" in add_money
  18.             wallet = Wallet.objects.filter(username=username).update(add_money(add_amount))
File "/Users/ravinkohli/PycharmProjects/untitled1/wallet/views.py" in add_money
  14.     if request.user:

Exception Type: AttributeError at /add_money/
Exception Value: 'unicode' object has no attribute 'user'

EDIT 2 //urls.py

urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'^', include('django.contrib.auth.urls')),
    url(r'^create-user/$', views.create_user),
    url(r'^accounts/profile/$', user_profile),
    url(r'^add_money/$', add_money),
    url(r'subtract-money/$', subtract_money)
]

i noticed that the third request is unicode but i have no idea why??

Upvotes: 3

Views: 2056

Answers (2)

e4c5
e4c5

Reputation: 53774

Original answer which assumed a middleware error

This is because you have not enabled the AuthenticationMiddleware

Adds the user attribute, representing the currently-logged-in user, to every incoming HttpRequest object. See Authentication in Web requests.

Your settings.py ought to have something like this

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
...
)

Updated answer based on stacktrace

You are calling a django view as an ordinary python function here. add_amount clearly isn't an HttpRequest instance.

 Wallet.objects.filter(username=username).update(add_money(add_amount))

In fact this whole statement doesn't make sense. In django the standard form is

.update(field_name=new_value)

but you are passing the response of a function call to update here. Were you thinking of

wallet = Wallet.objects.filter(username=username).update(amount = add_money)

Or were you perhaps thinking off adding a number to existing value? Then you will have to use a django F expression.

 wallet = Wallet.objects.filter(username=username).update(amount = F('amount') + add_money)

Upvotes: 6

Antwane
Antwane

Reputation: 22688

Since you didn't paste the full stacktrace, it's difficult to give you an answer 100% correct.

You used request.user in many place of the provided code. request variable should contain a HttpRequest object (since you are in a Django view). Please ensure your request is a HttpRequest and not a string object (unicode)

Upvotes: 0

Related Questions