Django session variables not saving when back button clicked - python

On my page i am trying to implement a recently viewed section on my home page.
The problem is when I append a new item to request.session["recently-viewed"], the item i just viewed gets deleted from the list when i load a new page.
The item view is a page which displays the details about a specific item. I want that particular item to be added and saved into a session variable. When the user visits any other page the session variable "recently-viewed" should be saved. Recently viewed items can then be displayed on the home page.
There is a similar question that has been asked but the only answer was a solution using javascript. If possible could solutions stay away from javascript.
views.py
def item(request, item_id):
if "recently-viewed" not in request.session:
request.session["recently-viewed"] = [item_id]
else:
request.session["recently-viewed"].append(item_id)
when in item view:
request.session["recently-viewed"] = ["item1", "item2"]
when another page is loaded:
request.session["recently-viewed"] = ["item1"]

Django, by default, only saves the session when a key has been deleted or assigned to. Because you are mutating a list you need to tell Django to save the session
request.session["recently-viewed"].append(item_id)
request.session.modified = True

Related

How to download in db zip file in existing view in django?

I want to add download button in existing view.
For example, I have a list board of fruits,
and when I click on them one by one, I move to the detail page,
such as the apple page, the strawberry page, and the grape page.
I want to create a download button for each detail page, and when I press the download button,
I want the user to download the apple.zip, drawberry.zip, and shape.zip files in database.
But I don't know how to do this in a view that's already been created.
My current view is as follows:
class FruitsDetailView(LoginRequiredMixin, DetailView):
template_name = 'fruits/detail.html'
login_url = 'login'
model = Fruits
def get_context_data(self, **kwargs):
pk = self.object.pk
context = super().get_context_data(**kwargs)
...
...
context['list'] = json.dumps(trace)
return context
I'm only exporting the context in this way, can I add a response related to the download here?
In the case of all the articles I looked for, I was creating a separate View exclusively for download.
But that's not the way I want it to be.
I'm a beginner at django, so I don't know where to start.
I'd appreciate if you give me a hint.

Next Page / Previous Page not working for Django pagination

I was hoping someone could help me with a pagination question.
I am trying to use Django pagination following the information on this page (https://docs.djangoproject.com/en/2.2/topics/pagination/). Whilst I have successfully displayed the correct number of items on the first page and the last page works, the next and previous pages keep taking me to the first page.
I think the issue may revolve around the ‘request’ element and I’m not sure if I am picking up an incorrect version. The example states:-
def listing(request):
contact_list = Contacts.objects.all()
paginator = Paginator(contact_list, 25) # Show 25 contacts per page
page = request.GET.get('page')
contacts = paginator.get_page(page)
return render(request, 'list.html', {'contacts': contacts})
The command:
page = request.GET.get(‘page’)
returns “AttributeError: 'Request' object has no attribute 'GET'”
By replacing this code with:
page = request.args.get('page', type=int)
the code successfully renders the first (and last) page but next and previous do not work.
As background I built my system on the Flask megatutorial but I have been unable to use that pagination, I understand because I haven’t used the Flask SQL Alchemy for creating and updating databases. My routes file has
from flask import request
Should I replace this with another utility's “request” and if so, which?
It seems the problem was in a missing () within the HTML file:-
next
listed within the example should have been:
next

Creating a log of all pages visited by the user

I am creating this functionality with a Django application I have. I want to log all pages the user visits and display it to him.
I am using a middleware to achieve it.
class LoggingMiddleware:
"""
Class used to register and fetch pages where the user has been visiting.
"""
def process_template_response(self, request, response):
if request.user.is_authenticated():
UserHistory.objects.create(user=request.user, page_name=request.path, url=request.path)
if response.context_data:
response.context_data['user_history'] = UserHistory.objects.filter(user=request.user)
return response
I want to name these UserHistory entries in the database, instead of just set the url as the name (as it i s now).
I have though of adding a variable to all views I have, in a way that the request object has something like request.page_name.
Can someone think of a better way to do it?

Include authenticated user in dictionary for all views

I am working through the Pyramid authorization tutorial and I have noticed the pattern where
logged_in = request.authenticated_userid
is added to each view dictionary. Can it be avoided? I.e. is there a configuration which automatically ads user id to each view. Or is there a way to create a base, abstract view with the user id and inherit from it?
Part of the code from the tutorial:
#view_config(context='.models.Page', renderer='templates/view.pt', permission='view')
def view_page(context, request):
# not relevant code
return dict(page = context, content = content, edit_url = edit_url,
logged_in = request.authenticated_userid)
#view_config(name='add_page', context='.models.Wiki', renderer='templates/edit.pt',
permission='edit')
def add_page(context, request):
# not relevant code
return dict(page=page, save_url=save_url,
logged_in=request.authenticated_userid)
It's been awhile since I last looked, but I think logged_in in the samples is just an example to use to conditionally check if there is a logged on user or not. You could probably just as easily refer to request.authenticated_userid within any of your views or templates, too, and get the same behavior and not have to explicitly add a status to the response dict. The request object should be available to be referenced in your view templates, too.
Alternatively, I've used their cookbook to add a user object to the request to make a friendly request.user object that I can use to both check for logged in status where needed, plus get at my other user object details if I need to as well.

django: restrict url reachable only from one view

i'm new in Django.
I have a form once filled i keep the datas and redirect to another page, but i notice if i put the correct url i can access to this second page without passing by the first form.
here is my urls:
urlpatterns = patterns('',
url(r'newworkflow/$','access_mgmt.views.newworkflowform'),
url(r'newrole/$','access_mgmt.views.newrole'),
)
So if in my browser url i put /newrole i get the page but i want to have access to it only if the form on the first page "/newworkflow/ is filled.
Is it possible to restrict the access to the second page only if the first form page is filled?
Only by recording somewhere - say in the session - that the user has completed page1, and checking that in the view for page2.

Categories

Resources