Rashomon
Rashomon

Reputation: 6772

set_cookie() missing 1 required positional argument: 'self'

In Django, Im trying to render a template and send a cookie at the same time with this code:

template = loader.get_template('list.html')
context = {'documents': documents, 'form': form}

if ('user') not in request.COOKIES:
    id_user =  ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.ascii_lowercase + string.digits) for _ in range(30))
    HttpResponse.set_cookie(key='user', value=id_user, max_age=63072000)

return HttpResponse(template.render(context, request))

But I get the Error:

TypeError at /myapp/list/

set_cookie() missing 1 required positional argument: 'self'

I have checked the documentation, but I dont find the solution. Help me please :)

Upvotes: 1

Views: 2828

Answers (2)

Sanjar
Sanjar

Reputation: 1

def setcookie(request):
    html=HttpResponse( '<h1>Salom Django</h1>')
    html.set_cookie(key='user',value='Hello,you just configured your first Cookie',max_age=None)
    return html

Upvotes: -1

Jmons
Jmons

Reputation: 1786

Close - HttpResponse is the class, not the instance of the class. The last line is creating one and returning it - so your earlier line needs to act on that instance...

try (untested code):

myResponse = HttpResponse(template.render(context, request))
myResponse.set_cookie(...)
return myResponse

Upvotes: 4

Related Questions