Hi, I successfully have stored a session key and value called "viewed.
I am trying to get this session’s values in a separate function called “recently_viewed” and store the session values in a field on a Form called RecentlyViewedForm. But the session values are not being saved. Any ideas?
def recently_viewed(request):
if 'viewed' in request.session:
id = request.session['viewed']. # This is working,.
if request.method == 'POST':
view = RecentlyViewedForm(request.POST)
if view.is_valid():
view.instance.user_id = id
view.save() # This is not working. It's not being saved here.
def customerDashboard(request, id):
user = User.objects.get(id=id)
view = RecentlyViewedForm
request.session['viewed'] = id
context = {
'user': user,
'view': view,
}
return render(request,'employees/customer_dashboard.html', context)
.html snippet that is applicable:
<form action="recently-viewed" method='post' >
{%csrf_token%}
{{view}}
</form>
What is RecentlyViewedForm
?
If it’s a ModelForm, see the information about commit=False
in the docs at Creating forms from models | Django documentation | Django for the appropriate method of updating an object being saved by a form.
recently-reviewed activates the recently_viewed function through URLs.py:
path('recently_viewed', views.recently_viewed, name='recently-viewed')
I don’t THINK I can use commit=False because nothing is being typed in the form. It’s just serving to activate the function. So I want to use sessions instead and have that fill in the form’s user_id field with the id from the session.
I tried adding commit=False here:
def recently_viewed(request):
if 'viewed' in request.session:
id = request.session['viewed']
if request.method == 'POST':
view = RecentlyViewedForm(request.POST)
if view.is_valid():
update = view.save(commit=False )
view.instance.user_id = update.id
view.save()
#and
def recently_viewed(request):
if 'viewed' in request.session:
id = request.session['viewed']
if request.method == 'POST':
view = RecentlyViewedForm(request.POST)
if view.is_valid():
update = view.save(commit=False )
view.user_id = update.id
view.save()
To no avail.
You’re submitting data, right? It doesn’t matter whether someone physically typed anything in the form. If you’re submitting form data (hence the reference to request.POST), then saving that form is saving data - and therefore can be used with commit=False
.
(If there’s no data being submitted, then you’ve got something else fundamentally wrong in your approach, and should take a big step back and re-think this from the beginning.)
Regarding your two attempts, you’re modifying the wrong object after the save.
The return value from the call to save is the instance of the object being saved. It’s that object you want to modify, not the form.
Solved. If anyone needs answer, let me know and I will post it.