1
votes

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

2
In this line: HttpResponse.set_cookie(key='user', value=id_user, max_age=63072000) is HttpResponse a class or instance of class (object)? - Jakub Jankowski

2 Answers

3
votes

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
-1
votes
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