Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Calculadora

0

90
Vistas
Add model object to cookie in Django

I have a model

class Journals(models.Model):
    JOURNAL_ID = models.AutoField(primary_key=True)
    Journal_name = models.CharField(max_length=255)
    Journal_slug = models.SlugField(max_length=255)

which I am trying to add to a cookie and then retrieve in other views. I am doing this as follows

journal = request.COOKIES.get('journal')

if journal:
    from_cookie = True
else:
    journal = get_object_or_404(Journals, Journal_slug=journal_slug)
    from_cookie = False

template = [...]

template_context = {
    ...
    'journal': journal,
    'from_cookie': from_cookie,
    ...
}

response = render(request, template, template_context)
response.set_cookie('journal', value=journal)
return response

It seems however that only the Journal_name is added to the cookie rather than the full object. This way I end up having no access to any of its other fields. How do I get so that the full journal object is added and retrieved instead?

8 months ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

First of all, don't use cookies directly. Store things in the session.

Secondly, don't try and store model objects anyway. Store the ID, and retrieve the object via that ID when you need to:

request.session['journal_id'] = journal.pk

...

journal = Journal.objects.get(pk=request.session['journal_id'])
8 months ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar empleo Planes Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2023 PeakU Inc. All Rights Reserved.