I am using context processors for showing total products in cart and other details in my project's header and footer. This is my file for context processors file "custom_context.py"
from models import Event, Ticket_Cart_details
def get_base_content(request):
music_events = Event.objects.all().filter(category='music', status = True).values('id','event_title').order_by('-id')[:4]
sports_events = Event.objects.all().filter(category='sports', status = True).values('id','event_title').order_by('-id')[:4]
experience_events = Event.objects.all().filter(category='experience', status = True).values('id','event_title').order_by('-id')[:4]
lifestyle_events = Event.objects.all().filter(category='lifestyle', status = True).values('id','event_title').order_by('-id')[:4]
The above code does not contain any information about logged in user now i have to write a code in which i have to get data of logged in user.
from models import Event, Ticket_Cart_details
def get_base_content(request):
music_events = Event.objects.all().filter(category='music', status = True).values('id','event_title').order_by('-id')[:4]
sports_events = Event.objects.all().filter(category='sports', status = True).values('id','event_title').order_by('-id')[:4]
experience_events = Event.objects.all().filter(category='experience', status = True).values('id','event_title').order_by('-id')[:4]
lifestyle_events = Event.objects.all().filter(category='lifestyle', status = True).values('id','event_title').order_by('-id')[:4]
if request.user.is_authenticated():
current_cart_products = Ticket_Cart_details.objects.all().filter(user_id=request.user.id, session_id=request.session.session_key)
current_cart_products = Ticket_Cart_details.objects.all().filter(session_id=request.session.session_key)
In the above code "request" will not work, so how can i get records of logged in user using this
You are using request well, but when you work with context processors, you have to return all the data that you want. For example:
def get_base_content(request):
music_events = Event.objects.all().filter(category='music', status=True).values('id','event_title').order_by('-id')[:4]
sports_events = Event.objects.all().filter(category='sports', status=True).values('id','event_title').order_by('-id')[:4]
return {"music_events": music_events,
"sports_events": sports_events ,
}
Additionally, for the problems with user not allowed or not logged in, you have to handle it with a anonymous data or something like this.
def get_base_content(request):
if not request.user:
music_events = 'none'
sports_events = 'none'
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.