Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DRF SearchFilter in ListAPIViews
I'm working on Django==3.2.7, djangorestframework==3.12.4 and django-filter==21.1. and React for the frontend What I would like to do: Return Job Offer objects that contains words from search (Search fields job_title and localistation) Remove useless words like ('in', 'a', 'an', 'the', 'at', 'for', 'to') in search here an example of the url: {{URL}}/api/v1/job-offers/jobs/?search=Chef in Texas allowed_methods = ['GET'] What I've done so far in my (ListAPIView): class JobOfferListAPIView(generics.ListAPIView): permission_classes = [permissions.IsAuthenticated] queryset = JobOffer.objects.all() serializer_class = JobOfferSerializer filter_backends = [filters.SearchFilter, filters.OrderingFilter, DjangoFilterBackend] search_fields = ['job_title', 'localisation'] ordering_fields = ['user', 'is_active'] filterset_fields = ['user', 'is_active', 'job_title', 'type_of_job', 'start_date', 'salary', 'localisation'] def get_queryset(self, *args, **kwargs): exclude_words = ['in', 'a', 'an', 'the', 'at', 'for', 'to'] keywords = self.request.GET.get('search').split(' ') keywords = [keyword for keyword in keywords if keyword not in exclude_words] if keywords: for keyword in keywords: queryset = queryset.filter( Q(job_title__icontains=keyword) | Q(localisation__icontains=keyword) ) print(queryset) return queryset Problème: When i'm printing queryset i can see filtered Job Offers in terminal but not return in Postman. Terminal Screen: Postman Screen -
ORM query using REGEX in ORM [closed]
I want to write a query using regex. Ex. Id Name 1 Edelweiss Banking and PSU Debt Fund - Regular Plan Growth 2 Edelweiss Small Cap Fund - Direct Plan Growth I have above to recodes in my MF table. we have to get query using name column for Name = edelweiss banking - and PSU Debt Fund - Regular Plan-Growth I thought, have using MF.objects.get(name__regex=r'____') -
Python/Django - radiobutton with submit button instead of buttons
I have a Django application where I want to have a setting: if the email is sent automatically or manually. What I have works, but not in the style that I want it. At the moment I have 2 buttons where you can click them and the setting is set to what you want. But what I would want is radio buttons, that are also already checked or unchecked, depending on the setting. What I have now is: model.py class AutoSendMail(models.Model): auto = models.BooleanField(default=False) manual = models.BooleanField(default=True) send_type = ( ('manual', 'MANUAL'), ('auto', 'AUTO') ) type = models.CharField(max_length=6, choices=send_type, default="manual") forms.py CHOICES = [('manual', 'MANUAL'), ('auto', 'AUTO')] class SendMailSetting(ModelForm): class Meta: model = AutoSendMail fields = ['auto', 'manual', 'type'] widgets = { "manual": forms.RadioSelect(attrs={'class': 'form-control'}), "auto": forms.RadioSelect(attrs={'class': 'form-control'}), 'type': forms.ChoiceField(choices=CHOICES, widget=forms.RadioSelect) } views.py class AutoSendView(generic.TemplateView): template_name = 'core/mailbox/autoSendMail.html' context_object_name = 'autosend' extra_context = {"mailbox_page": "active"} form_class = SendMailSetting def post(self, request, *args, **kwargs): if request.POST.get('manual'): logger.info("Set to: manual email send") AutoSendMail.objects.filter(pk=1).update(auto=True, manual=False, type="manual") elif request.POST.get('auto'): logger.info("Set to auto email send") AutoSendMail.objects.filter(pk=1).update(auto=True, manual=False, type="auto") return HttpResponseRedirect(self.request.path_info) autoSendMail.html <form class="card" action="" method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="card-body"> <h3 class="card-title">Update Mail Settings</h3> <div class="row"> <div class="col-md-6"> <div class="form-group"> <label class="form-label">Send E-mail</label> <button … -
Django many to many filter out itself but other field
I have a UserProfile model as follows: class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) user_ips = models.ManyToManyField(IpAddress, related_name="ip_user_ips", blank=True) and an IpAddress Model as follows: class IpAddress(models.Model): ip = models.CharField(max_length=69) Admin.py: class UserProfileAdmin(admin.ModelAdmin): form = UserProfileForm fieldsets = ( (None, { 'fields': ('user', 'user_ips', 'shared_users',), }), ) list_display = ['user', ] filter_horizontal = ['user_ips',] Forms.py class UserProfileForm(forms.ModelForm): class Meta: fields = '__all__' model = UserProfile shared_users = forms.MultipleChoiceField() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['shared_users'].queryset = # Display Shared Users By The Same IP of all IPs this user have accessed with As of now, "user_ips" displays all ip addresses by a particular user in Admin, I want to filter out and display the username of All users shared by the same ip address of all ip addresses by that user in Admin, Preferably without having to actually create an additional field or model in the database. -
Posting http request after enabeling TLS/SSL
I have a website using Angular for the frontend, Django for the backend and they are being served using Apache. It was working properly until I enabled TLS/SSL using letsencrypt. Since then I was still able to access the website using https, but all my http request to the backend give errors. The error message is: Http failure response for http://backend.IP:8080/api/load_data/: 0 Unknown Error If I call the API function from the browser like this: http://backend.IP:8080/api/load_data/ It works well and returns the expected data from the backend, but when posting http request from the code it gives the previous error. Here is apache configurations for the frontend.conf: <VirtualHost *:80> DocumentRoot "/home/ubuntu/myproject/static/" # Other directives here DirectoryIndex index.php index.htm index.html <Directory "/home/ubuntu/myproject/static"> AllowOverride All Require all granted </Directory> # Logs ErrorLog /var/log/apache2/frontend_error.log CustomLog /var/log/apache2/frontend_access.log combined RewriteEngine on RewriteCond %{SERVER_NAME} =test.myproject.org RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent] </VirtualHost> Here is the frontend-le-ssl.conf: <IfModule mod_ssl.c> SSLStaplingCache shmcb:/var/run/apache2/stapling_cache(128000) <VirtualHost *:443> DocumentRoot "/home/ubuntu/myproject/static/" # Other directives here DirectoryIndex index.php index.htm index.html <Directory "/home/ubuntu/myproject/static"> AllowOverride All Require all granted </Directory> # Logs ErrorLog /var/log/apache2/frontend_error.log CustomLog /var/log/apache2/frontend_access.log combined ServerName test.myproject.org SSLCertificateFile /etc/letsencrypt/live/test.myproject.org/fullchain.pem SSLCertificateKeyFile /etc/letsencrypt/live/test.myproject.org/privkey.pem Include /etc/letsencrypt/options-ssl-apache.conf Header always set Strict-Transport-Security "max-age=31536000" SSLUseStapling on Header always set Content-Security-Policy upgrade-insecure-requests </VirtualHost> … -
Unable to set formset fields in view
I have try to make inlineformsets and it works but I need to set field that are not displayed in formset in the corresponding view. Model Antecedent is linked to Inclusion models with a one-to-many (FK) field (inc). I've tried to do it in is_valid() method but it dosen't work. I manage to set 'parent' (Inclusion) form sai_log field but not related 'childrens' (Antecedent) formsets sai_log fields. I know that Antecedent.objects.filter(inc__pat=self.kwargs["pk"]).update(sai_log=self.request.user.username) is a correct instruction but data is not saved in database. models.py class Inclusion(models.Model): pat = models.ForeignKey('Patient',on_delete = models.CASCADE, related_name='inclusion_patient', db_column='pat') sai_log = models.CharField('Login de l\'utilisateur ayant fait la saisie (AUTO)', max_length=50, null=True, blank=True) class Antecedent(models.Model): ide = models.AutoField(primary_key=True) inc = models.ForeignKey('Inclusion',on_delete = models.CASCADE, related_name='antecedent_inclusion', db_column='inc') sai_log = models.CharField('Login de l\'utilisateur ayant fait la saisie (AUTO)', max_length=50, null=True, blank=True) views.py def form_valid(self, form): context = self.get_context_data() antecedents = context['antecedents'] self.object = form.save(commit=False) if antecedents.is_valid(): self.object.sai_log = self.request.user.username # sai_log set in 'parent' form works self.object.save() # self.kwargs["pk"] => pk of patient Antecedent.objects.filter(inc__pat=self.kwargs["pk"]).update(sai_log=self.request.user.username) # sai_log set in 'childrens' formsets doesn't works antecedents.instance = self.object antecedents.save() else: return render(self.request, self.template_name, context) return super(InclusionCreate, self).form_valid(form) -
django.urls.exceptions.NoReverseMatch: Reverse for 'like_qa' with arguments '('',)' not found
I have a Django app with a like button that I implemented based on that tutorial. The URL differs in my app because I don't put 'id' in my URL but only slug. When clicking on the like button it adds likes to the counter, however, it doesn't show the updated counter until the page is refreshed. I get the following error every time I click on the like button: Traceback (most recent call last): ... django.urls.exceptions.NoReverseMatch: Reverse for 'like_qa' with arguments '('',)' not found. 1 pattern(s) tried: ['like_qa/(?P<slug>[-a-zA-Z0-9_]+)/$'] [17/Mar/2022 12:44:49] "POST /like_qa/how-to-add-products-to-the-catalog/ HTTP/1.1" 500 149900 views.py @login_required def LikeQA(request, slug): article = get_object_or_404(QA, slug=slug) liked = False if article.likes.filter(id=request.user.id).exists(): article.likes.remove(request.user) liked = False else: article.likes.add(request.user) liked = True context = { 'like': article, 'liked': liked, 'total_likes_qa': article.total_likes_qa(), } if request.is_ajax(): html = render_to_string('components/like_section_ajax.html', context, request=request) return JsonResponse({'form': html}) urls.py path('like_qa/<slug:slug>/', views.LikeQA, name='like_qa'), like_section_ajax.html {% if request.user.is_authenticated %} <form action="{% url 'like_qa' qa.slug %}" method="POST"> {% csrf_token %} {% if liked %} <button type="submit" id="like" name="qa_slug", value="{{qa.slug}}" class="btn btn-clicked"><i class='bx bxs-like'></i></button> {% else %} <button type="submit" id="like" name="qa_slug", value="{{qa.slug}}" class="btn btn-to-be-clicked"><i class='bx bx-like'></i></button> {% endif %} {{ total_likes_qa }} like{{ total_likes_qa|pluralize }} </form> {% endif%} QADetail.html <script type="text/javascript"> $(document).ready(function(event){ $(document).on('click', … -
Django How to link a foreign key to many tables
I have n classes and each class contains a column called key like this (where n==3) class class1(models.Model): Id1 = models.AutoField(primary_key=True) key = models.CharField(max_length = 16, blank=True) class class2(models.Model): Id2 = models.AutoField(primary_key=True) key = models.CharField(max_length = 16, blank=True) class class3(models.Model): Id3 = models.AutoField(primary_key=True) key = models.CharField(max_length = 16, blank=True) I want to make the column key as Foreign key between all the n classes? I know how make a foreign key between 2 classes but I want to do that with many classes because I have about 40 classes and some classes has some commun columns -
What are some useful resources to learn model serializers provided by Django Rest Framework?
I am a beginner in learning Django Rest Framework. What are some useful resources to learn model serializers provided by Django Rest Framework? I am learning from some course videos on Youtube, Udemy and Coursera. But most of the videos use templates in views.py file and I want to use DRF with APIView. -
Allow Users to Specify SESSION_COOKIE_AGE in Django at Runtime
I'm specifying a default SESSION_COOKIE_AGE in the main settings.py file; however, I'd like admin users to be able to overwrite this value. This value should persist across server restarts. My initial reaction was to store this in a single-row in a DB table and then write some middleware that would adjust the user's expiry date on each request to match the user-supplied SESSION_COOKIE_AGE; however, that seems like a lot of redundant db queries. Then I went down a signals rabbit hole and am considering creating two signals (post_save and connection_created) to handle: user updates to the user-supplied SESSION_COOKIE_AGE value stored in the DB as well as ensuring SESSION_COOKIE_AGE is updated upon the server starting. And finally I see all of these projects like django-constance, etc. to dynamically update settings constants at runtime. Any suggestions on the most reliable / least error-prone architecture for this? -
Django not keeping session entries after allauth social login/signup
I have an authorized user that is adding a social account to his account. I want the user to be redirected to the specific url after they signed up for this account. next parameter is not working so I decided to go with session way. I've overridden DefaultAccountProfider which checks session for next key. The problem is that there is no such key after signup/login. Please, note that this applies on already logged in User. class MyAccountAdapter(DefaultAccountAdapter): def get_signup_redirect_url(self, request): request.session['next'] # keyerror return super().get_signup_redirect_url(request) # breakpoint here def get_login_redirect_url(self, request): request.session['next'] # keyerror return super().get_login_redirect_url(re..) # breakpoint here - no "next" session How can I make it work? I need the user to be redirected to /some-url but only when next is in the session. -
AttributeError at /cart type object 'Cart' has no attribute 'model'
class Cart(View): def get(self , request): customer_id = request.session['customer'] cart = get_object_or_404(Cart, customer_id= customer_id) return render(request , 'cart.html') I am not able to get the cart object -
NGINX Static Files Over Https?
I have the following docker-compose set up that is working for displaying pictures when deployed locally and without https: NGINX: events{ } http{ server { listen 80; server_name localhost; root /usr/share/nginx/html; location / { proxy_pass http://frontend:3000; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection ""; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; } } } docker-compose: frontend: build: context: ../../ restart: always volumes: - '../../:/app' - '/app/node_modules' ports: - "3000:3000" depends_on: - "backend" environment: - CHOKIDAR_USEPOLLING=true stdin_open: true tty: true nginx: build: context: ../../nginx restart: always ports: - "80:80" - "443:443" volumes: - volume1:/usr/share/nginx/html links: - "backend" - "db" - "frontend" frontend: <img onError={()=>{ console.log("inside the onError function") setImgError(true) }} src={"http://localhost:9000/static/"+comment.file_name} className='commentimage' /> This is not working when using https. Which is to say - / and /api/ work as expected but not /images/. events{ } http{ server { listen 80; server_name localhost lightchan.org www.lightchan.org; root /usr/share/nginx/html; location /.well-known/acme-challenge/ { root /var/www/certbot; } return 301 https://lightchan.org$request_uri; } server { listen 443 default_server ssl http2; listen [::]:443 ssl http2; server_name localhost lightchan.org www.lightchan.org; #ssl_certificate /etc/nginx/ssl/live/lightchan.org/fullchain.pem; #ssl_certificate_key /etc/nginx/ssl/live/lightchan.org/privkey.pem; ssl_certificate /etc/letsencrypt/live/lightchan.org/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/lightchan.org/privkey.pem; location / { proxy_pass http://frontend:3000; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; } location ^~ /api/ { … -
How to put data in the db when you press a link in django
<a href="{% url 'one' one.id_n %}" class="bg-gray-900 shadow-lg rounded p-3 overflow-hidden hover:shadow-xl hover:scale-105 duration-500 transform transition cursor-pointer"> <div class="group relative"> <img class="w-full md:w-72 block rounded" src="{{ one.f1 }}" alt="" /> </div> </a> I'm begginer with django and i want to add data as "one.id_n" to the db when you press the link. -
How to hide/delete recent actions dashboard from django admin panel?
I have removed my model but the history stays the same in the recent actions dashboard. I want to either clean it or delete it. Someone please say that way. -
Django REST Framework ValidationError along with params
The ValidationError raised by Django REST Framework doesn't include params like how Django's Validation error includes it. The REST Framework catches Django's Validation Error and raises it's Validation error which doesn't include params. Is there any way to keep params in the REST Framework ValidationError which are raised by Django's Validation Error? -
How to Hide a "fieldset" if user role changes in admin
Hi I want to hide some fieldsets in admin if user role changes. In get_queryset() I'm changing queryset if role == 'CMS' I also want hide Permission fieldset for same role. Here is my admin: from django.contrib import admin from django.contrib.auth import get_user_model from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from django.contrib.auth.models import Permission from .models import BankAccount from addresses.models import Address User = get_user_model() class AddressInline(admin.TabularInline): model = Address extra = 0 @admin.register(User) class UserAdmin(BaseUserAdmin): list_display = ( 'id', 'full_name', 'email', 'gender', 'role', ) list_filter = ( 'gender', 'is_staff', 'is_superuser', 'is_active', ) list_display_links = ( 'full_name', 'email', ) search_fields = ( 'email', 'first_name', 'last_name', 'phone_number', ) readonly_fields = ( 'created', 'updated', ) ordering = ('first_name', 'email', 'last_name',) fieldsets = ( ('Credentials', {'fields': ('email', 'phone_number', 'password')}), ('Info', {'fields': ('first_name', 'last_name', 'gender', 'role', 'otp', 'profile_pic', 'created', 'updated')}), ('Permissions', {'fields': ('is_vendor', 'is_staff', 'is_superuser', 'is_active', 'groups', 'user_permissions')}), ) add_fieldsets = ( ('Credentials', {'fields': ('email', 'phone_number', 'password1', 'password2')}), ('Info', {'fields': ('first_name', 'last_name', 'gender', 'role', 'profile_pic')}), ('Permissions', {'fields': ('is_vendor', 'is_staff', 'is_superuser', 'groups', 'user_permissions')}), ) inlines = (AddressInline,) def full_name(self, obj=None): return f'{obj.first_name} {obj.last_name}' def get_queryset(self, request): if request.user.role == 'CMS': return self.model.objects.filter( role='CUSTOMER', is_staff=False, is_superuser=False ) else: return self.model.objects.all() admin.site.register(Permission) admin.site.register(BankAccount) In this admin, in get_queryset() … -
Organize folder by date using django filer
I'm using django-filer to be able to reuse the already uploaded images. Everything works fine, except the folder path. I want all FilerImageFields to store images in a structured folder like this (year/month/filename.jpg) : Is there a way to do it? Thanks. -
AttributeError at /cart 'dict' object has no attribute 'append'
class Cart(View): def get(self , request): categories = Category.get_all_categories() productid = request.GET.get('product') product = get_object_or_404(Products, id=productid) sellername = request.GET.get('seller') seller = get_object_or_404(Sellers, name=sellername) productsToShow = [] if('cart' in request.session): productsToShow = request.session['cart'] prices = Price.objects.filter(product=product,seller=seller) for price in prices: product2 = price.product product2.seller = price.seller product2.cost = price.cost product2.quantity = 1 productsToShow.append(product2) request.session['cart'] = productsToShow return render(request , 'cart.html' , {'products' : productsToShow,'categories' : categories} ) session variable wont let me get and set -
How to add URL parameters to Wagtail archive page with filter form?
This is about an archive page in Wagtail CMS where a large number of posts can be filtered by certain properties. The filtering is handled by a form with a few select elements. The form is validated in the serve() method of the page. The queryset is filtered there accordingly as well. Here is some exemplary code to illustrate what I mean: from .forms import ArchivePageFilterForm ... class ArchivePage(Page): ... def pages(self): return SomeModel.objects.live() # exemplary queryset def serve(self, request): filter_form = ArchivePageFilterForm(request.POST or None) if request.method == 'POST': if filter_form.is_valid(): name = filter_form.cleaned_data['name'] category = filter_form.cleaned_data['category'] color = filter_form.cleaned_data['color'] whatever = filter_form.cleaned_data['whatever'] selected_pages = filter_query(self.pages, name, category, color, whatever) # imagine some filtering magic here return render(request, 'pages/archive_page.html', { 'page': self, 'pages': selected_pages, 'form': ArchivePageFilterForm(initial={'name': name, 'category': category, 'color': color, 'whatever': whatever}), }) return render(request, 'pages/archive_page.html', { 'page': self, 'pages': self.pages, 'form': ArchivePageFilterForm(), }) The RoutablePageMixin did not work for me here, because it only works with fixed URL schemes. I wonder how I can add URL parameters only as needed, one by one, depending on the active filters. Exemplary URLs that would be possible with the same page: .../archive/?name=janedoe .../archive/?name=janedoe&type=essay .../archive/?category=essay .../archive/?category=essay&color=green&whatever=foobar ... you get the idea. The … -
How to loop through xlif(xml) to find specifc ids are exists
I have xliff file in below format which located in s3 <xliff xmlns="urn:oasis:names:tc:xliff:document:2.0" srcLang="" version="2.0"> <file original="page_4" trgLang="en-GB"> <group id="chapter0"> <unit id="chapter00__title"> <segment> <source>chapter 01</source> </segment> </unit> <unit id="chapter0__introduction"> <segment> <source /> </segment> </unit> <unit id="chapter0__text"> <segment> <source>hello</source> </segment> </unit> <unit id="uexercise0__answers[0].correct"> <segment> <source>111</source> </segment> </unit> I access it via s3_object = s3.get_object(fileLink) read_file = s3_object['Body'].read() I want to loop through ids and validate if all required ids are available on xliff I have below loop with ids which required, for x in groups: for attribute, value in x.localized_strings: print(attribute) # ex: attribuete = chapter00__title I need to loop over my xliff file and see if all attrbutes are availabe, if it found any missing attribute or new attribute then throw error please advice how to proceed this -
plotly django bar doesn't show chart
if i print df_costo the result of the dataframe is ok, but in html file doesn0t show nothing ''' code ''' def fase_progetto(request): try: qs_costo = CostoFase.objects.all() costo_fase_data =[ { 'Responsabile': x.responsabile, 'Costo': x.costo } for x in qs_costo ] df_costo = pd.DataFrame(costo_fase_data) print(df_costo) fig_costo = px.bar(df_costo, x="Responsabile", y="Costo") gantt_plot_costo = plot(fig_costo, output_type="div") context = {'costo_plot_div': gantt_plot_costo, 'form': form} return render(request, 'progetti/progetti.html', context) except: return render(request, 'progetti/progetti.html', {'form': form}) -
invalid literal for int() with base 10: b'20 Feb'
I am working with Wagtail and I am creating the model of the app. publish_date = models.DateField( max_length=300, blank=True, null=True, default="20 Feb", verbose_name="First publish date", help_text="This shows the first publish date" ) I think the problem is that the field type is a DateField but the value that I am sending is '20 Feb'. Any ideas? -
Django Display ID and Description From Queryset Form into Dropdown
I would like to display data from the table into Django Queryset Form with properly showing value and text of dropdown control. Coding at Form: self.fields['testing_field'].queryset = model_abc.objects.all().values_list('description', flat=True) Result description is also value: <select name="cars" id="cars"> <option value="volvo">Volvo</option> <option value="saab">Saab</option> <option value="mercedes">Mercedes</option> <option value="audi">Audi</option> </select> Result expection can set id as value with existing description: <select name="cars" id="cars"> <option value="1">Volvo</option> <option value="2">Saab</option> <option value="3">Mercedes</option> <option value="4">Audi</option> </select> How to set id as a value within the dropdown form of Django QuerySet ? -
How to invalidate a view cache using django-cacheops
I'm having a view and I cached it in views.py using django-cache(https://github.com/Suor/django-cacheops) @cached_view(timeout=60*15) @csrf_exempt def order(request, usr): ... and the regex for order view in urls.py url(r'^order/(?P<usr>\D+)$', views.order, name='ord') #Example Url: http://127.0.0.1:8000/order/demo (demo is the user name) And I want to invalidate the cached view order inside the below view @login_required def available(request, pk, avail): pk = int(pk) avail = strtobool(avail) if avail: Product.objects.filter(id = pk).update(available = True) else: Product.objects.filter(id = pk).update(available = False) return HttpResponseRedirect(reverse_lazy('yc')) According to docs we can achieve this by doing @login_required def available(request, pk, avail): pk = int(pk) avail = strtobool(avail) if avail: Product.objects.filter(id = pk).update(available = True) order.invalidate("http://127.0.0.1:8000/order/demo", "demo") #it's a dummy url I've handled it dynamically in my code else: Product.objects.filter(id = pk).update(available = False) order.invalidate("http://127.0.0.1:8000/order/demo", "demo") #it's a dummy url I've handled it dynamically in my code return HttpResponseRedirect(reverse_lazy('yc')) But it's not working. Here are my logs using redis-cli **1647434341.849096 [1 [::1]:59650] "GET" "c:af687d461ec8bb3c48f6392010e54778" 1647434341.866966 [1 [::1]:59650] "SETEX" "c:af687d461ec8bb3c48f6392010e54778" "900" "\x80\x04\x95\xfa\b\x00\x00\x00\x00\x00\x00\x8c\x14django.http.response\x94\x8c\x0cHttpResponse\x94\x93\x94)\x81\x94}\x94(\x8c\b_headers\x94}\x94\x8c\x0ccontent-type\x94\x8c\x0cContent-Type\x94\x8c\x18text/html; charset=utf-8\x94\x86\x94s\x8c\x11_closable_objects\x94]\x94\x8c\x0e_handler_class\x94N\x8c\acookies\x94\x8c\x0chttp.cookies\x94\x8c\x0cSimpleCookie\x94\x93\x94)\x81\x94\x8c\x06closed\x94\x89\x8c\x0e_reason_phrase\x94N\x8c\b_charset\x94N\x8c\n_container\x94]\x94B\xed\a\x00\x00<!DOCTYPE html>\n\n<html>\n <head>\n <meta charset=\"utf-8\">\n <title>Buy Products</title>\n <link href=\"https://fonts.googleapis.com/css?family=Peralta\" rel=\"stylesheet\">\n <link rel=\"stylesheet\" href=\"/static/css/bootstrap.min.css\">\n <link rel=\"stylesheet\" href=\"/static/css/app.css\">\n </head>\n <body>\n <div class=\"wrapper\">\n <div class=\"container\">\n <ol class=\"breadcrumb my-4\">\n <li class=\"breadcrumb-item active\" style=\"color: #000;\">Buy Products</li>\n </ol>\n <form method=\"post\">\n <!-- <input type=\"hidden\" name=\"csrfmiddlewaretoken\" value=\"SnsBnyPIwIDejqctR7TMNkITcSafgwiydwsyIiAKQkiSvr3nFA0cm1Tf3Mk6JTPj\"> -->\n <p><label …