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?
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'])