pythondjangohttpcookie

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 :)


Solution

  • 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