Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to remove the "#" symbol from the url
I have a link that takes me to another section of the same page like this: //this is the section with the id = "about" <section class="page-section bg-primary" id="about"> </section> //this the call to that id: <a class="nav-link" href="#about">About</a> and everytime i click it takes me to that section but it shows up like this in the url bar: http://127.0.0.1:8000/home/#about i want my link to be clean and shows up like this: //link without "#" http://127.0.0.1:8000/home/about -
Audio input on web
I am building a website where it converts speech to text. I wants to know some examples of accessing the microphone, recording a audio and saving it. I don't want anything super complicated, just a simple method. 😁 -
Django Rest Framework can't get CSRF Token by React
I've spent six hours on it and I still can't handle getting CSRF Token and Session ID. I have these two simple functions: @api_view(["GET"]) @ensure_csrf_cookie def getCsrf(request): return Response({'success': get_token(request)}) @method_decorator(csrf_exempt, name='post') class LoginView(views.APIView): permission_classes = (AllowAny,) def post(self, request, format=None): serializer = LoginSerializer(data=self.request.data, context={ 'request': self.request }) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] login(request, user) return Response(None, status=status.HTTP_202_ACCEPTED) I have corsheaders installed and I have these settings: CORS_ALLOWED_ORIGINS = [ 'http://127.0.0.1:3000', 'http://localhost:3000', 'http://127.0.0.1:8000', 'http://localhost:8000', ] CSRF_TRUSTED_ORIGINS = [ 'http://127.0.0.1:3000', 'http://localhost:3000', 'http://127.0.0.1:8000', 'http://localhost:8000', ] CORS_ALLOW_HEADERS = ('Access-Control-Allow-Origin', 'Access-Control-Allow-Credentials', 'Authorization', 'Content-Type', 'Cache-Control', 'X-Requested-With', 'x-csrftoken') CORS_ALLOW_CREDENTIALS = True CSRF_COOKIE_HTTPONLY = False SESSION_COOKIE_HTTPONLY = False CSRF_USE_SESSIONS = False CSRF_COOKIE_SECURE = False SESSION_COOKIE_SECURE = False SESSION_COOKIE_SAMESITE = 'None' CSRF_COOKIE_SAMESITE = 'None' So, both of those cookies appear in the responses. Neither of them are written in the browser. I've tried everythong I found. This is my React part axios.defaults.withCredentials = true; useEffect(() => { axios.get(`http://127.0.0.1:8000/csrf/`) .then(response => { Cookies.set('csrftoken', response['data']['csrf']); }) .catch(error => { console.log(error); }); }, []); function onSubmit(e) { e.preventDefault(); let data = { username: e.target.username.value, password: e.target.password.value }; const config = { headers: { 'content-type': 'application/json', 'Access-Control-Allow-Credentials': 'true', 'Access-Control-Allow-Origin': 'http://localhost:8000', 'X-CSRFToken': Cookies.get('csrftoken') }, withCredentials: true, crossDomain: true } axios.post(`http://127.0.0.1:8000/login/`, JSON.stringify(data), config) .then(response => … -
How should I change all my products' availability to true in django oscar?
I'm slowly getting familiar with overriding things in oscar, but in this case I'm still not sure what and where to override to achieve my goal. So when I'm trying to add a product to basket, it will check if it's available at ../api/product/n/availability which returns something like this: { "is_available_to_buy": false, "message": "Unavailable" } Since I personally don't need to check for availability, I just want it to return true in every case, for which I thought about these solutions: https://django-oscar.readthedocs.io/en/3.1/_modules/oscar/apps/partner/strategy.html#Structured Here, in the first function under Structured, I could change is_available_to_buy to true Or https://github.com/django-oscar/django-oscar-api/blob/master/oscarapi/serializers/product.py I could override AvailabilitySerializer to return true by default. I wonder if any of these could be overridden, and if yes, how exactly do I do it? -
AttributeError: module 'graphql_jwt' has no attribute 'DeleteJSONWebTokenCookie'
I am using django-graphql-jwt package everything works fine so far, but getting this error just stuck at there,appropriate your help import graphene import graphql_jwt class Mutation(graphene.ObjectType): token_auth = graphql_jwt.ObtainJSONWebToken.Field() verify_token = graphql_jwt.Verify.Field() refresh_token = graphql_jwt.Refresh.Field() # getting error from this line delete_token_cookie = graphql_jwt.DeleteJSONWebTokenCookie.Field() -
Comments not showing django review ecommerce
Am trying to introduce some basic comments to my ecommerce website on the products. I got the code in and i dont get why it dosent display on the page? Any advice why comments dosent show up when u submit the review, i get no errors. in views.py its: def product in models.py its: class Review in models.py its: in Product_detail.html its: starts at: Reviews views.py from django.shortcuts import render, redirect, reverse, get_object_or_404 from django.contrib import messages from django.contrib.auth.decorators import login_required from django.db.models import Q from django.db.models.functions import Lower from .models import Product, Category, Review from .forms import ProductForm # Create your views here. def all_products(request): """ A view to show all products, including sorting and search queries """ products = Product.objects.all() query = None categories = None sort = None direction = None if request.GET: if 'sort' in request.GET: sortkey = request.GET['sort'] sort = sortkey if sortkey == 'name': sortkey = 'lower_name' products = products.annotate(lower_name=Lower('name')) if sortkey == 'category': sortkey = 'category__name' if 'direction' in request.GET: direction = request.GET['direction'] if direction == 'desc': sortkey = f'-{sortkey}' products = products.order_by(sortkey) if 'category' in request.GET: categories = request.GET['category'].split(',') products = products.filter(category__name__in=categories) categories = Category.objects.filter(name__in=categories) if 'q' in request.GET: query = request.GET['q'] … -
How to get the path name of an URL path in django using the request.path
I have urls paths with name in my urls.py file. urls.py urlpatterns = [ path('home/', views.home, name="home_view"), ] my views.py def home(request): path_name = get_path_name(request.path) return HttpResponse(path_name) Now, I need to get the path name, "home_view" in the HttpResponse. How can I make my custom function, get_path_name() to return the path_name by taking request.path as argument? -
Django how split durationfield over dates it covers using ORM (PostgreSQL)
using Django (with PostgreSQL) I have a model that represents activities with a certain starting moment (start_datetime) and a duration. So it is possible that an activity covers more than one day, and I would like to know per activity how much time it covers on consecutive dates (days). So an example would be, all using UTC timezone, to have a 48 hour appointment start on 2022-12-24T12:00, which would have the activity end on 2022-12-26T12:00, giving duration per day: 2022-12-24 - 12 hours 2022-12-25 - 24 hours 2022-12-26 - 12 hours And I would like to get this information for up to a year's worth of activities, for a single person's agenda. Is this possible, and if so does anyone have an example of how to achieve this? Ideally I would also be able to specify the timezone that this data needs to be determined in. Thanks in advance! -
Autofill the model which have related fields to another model
I am creating a django application and have created three models: models.py : class User(AbstractUser): pass class Listing(models.Model): title = models.CharField(max_length=32) details = models.CharField(max_length=300, blank=True) price = models.DecimalField(max_digits=7, decimal_places=2) photo = models.ImageField() class ListingDetails(models.Model): listing_id = models.ForeignKey(Listing, on_delete=models.CASCADE, related_name="auctioner", unique=True) owner_id = models.ForeignKey(User, on_delete=models.CASCADE, related_name="auctioner") created_at = models.DateTimeField(default=timezone.now()) Listingdetails have one to many relationship. One user can have many Listing . What i want is that whenever I create a listing the data in ListingDetails get automatically filled with the listing_id which is pk of Listing and user_id of user who created listing and created_at gets automatically filled with that time. -
Difference between select_related() and prefetch_related() in django?
Can I use prefecth_related for foreign key field. I used select_related for a table containing foreign key fields. Can I use prefetch Instead of that? I am working on modelviewsets. models.py class Category(models.Model): category_name=models.CharField(max_length=100) active=models.BooleanField(default=True) def delete(self): self.active=False self.save(update_fields=('active',)) def __str__(self): return self.category_name class Brand(models.Model): brand_name=models.CharField(max_length=100) active=models.BooleanField(default=True) def delete(self): self.active=False self.save(update_fields=('active',)) def __str__(self): return self.brand_name class Product(models.Model): name=models.CharField(max_length=100) price=models.FloatField() details=models.TextField() category=models.ForeignKey(Category,on_delete=models.CASCADE,related_name='productshavecategory') brand=models.ForeignKey(Brand,on_delete=models.CASCADE,related_name='productshavebrand') stock=models.PositiveBigIntegerField() price_per_amount=models.CharField(max_length=100) rating=models.PositiveIntegerField(default=0) active=models.BooleanField(default=True) Special_offer=models.BooleanField(default=False) rating_count=models.PositiveIntegerField(default=0) average=models.FloatField(default=0) def delete(self): self.active=False self.save(update_fields=('active',)) def __str__(self): return self.name views.py class CategoryViewset(viewsets.ModelViewSet): permission_classes = [IsAuthenticated] queryset=Category.objects.filter(active=True) serializer_class=CategorySerialaizer def list(self, request, *args, **kwargs): queryset=Category.objects.filter(active=True) if queryset.exists(): serializer=CategorySerialaizer(queryset,many=True) return Response({'status':True,'data':serializer.data,'message':'Category found'}) else: return Response({'status':False,'data':None,'message':'Category not found'}) class BrandViewset(viewsets.ModelViewSet): permission_classes = [IsAuthenticated] queryset=Brand.objects.filter(active=True) serializer_class=BrandSerialaizer def list(self, request, *args, **kwargs): queryset=Brand.objects.filter(active=True) if queryset.exists(): serializer=BrandSerialaizer(queryset,many=True) return Response({'status':True,'data':serializer.data,'message':'Brands found'}) else: return Response({'status':False,'data':None,'message':'Brands not found'}) class ProductViewset(viewsets.ModelViewSet): permission_classes = [IsAuthenticated] queryset=Product.objects.select_related('category','brand').filter( Q(active=True) & Q(stock__gt=0) ) serializer_class=ProductSerialaizer filter_backends = [DjangoFilterBackend,filters.SearchFilter] search_fields = ['name'] filterset_fields = ['category','brand'] def list(self, request, *args, **kwargs): queryset=Product.objects.select_related('category','brand').filter( Q(active=True) & Q(stock__gt=0) ) if queryset.exists(): serializer=ProductSerialaizer(queryset,many=True) return Response({'status':True,'data':serializer.data,'message':'Products found'}) else: return Response({'status':False,'data':None,'message':'Products not found'}) When I used prefetch_related instead of select_related I got same result and query set returned at almost same time. Is this a proper way? -
Can't import modules
I've searched for this problem and tried different solutions but can't fix it. In my Django project I have different apps and a non-app directory called 'testing_utils' with modules which serve for a testing purposes. In particular I want to import all available models to file dummy_factory.py. However when I simply import modules from my apps like so: from abc import ABC from datetime import date from users.models import User I get the error message ModuleNotFoundError: No module named 'users' Which is strange since I definetley can import models to some_app.views.py and access them. Here's an example of my project's directory: /home/user/dev/project/ ▸ project/ ▾ testing_utils/ dummy_factory.py ▾ users/ ▸ __pycache__/ ▸ migrations/ ▸ templates/ ▸ tests/ __init__.py admin.py apps.py models.py views.py manage.py* -
Is there a good way to develop a ERP/CRM application using django? Maybe using an existing example such as Acumatia, Odoo or SAP?
Ok so I am in the process of starting my own ERP(enterprise resource planning)/CRM(company resource management) company and would like to use django to develop the application. I have the database setup however the data in the tables I extracted is from another ERP. I need help piecing everything together. Can anyone help me? -
Retrive Data from specific year interval in djnago
How are you? I need some help please. I am working in Django and I need to make a query that should return a value in specific year interval. for example if year interval is 2 than it should return data for 10 years, if apply date was 2020 than it should return data in 2020, 2022, 2024 like that and if the apply date was 2023 and interval was 3, than it also should return data similarly. The Code is below, i have tried: diff = get_factors_of(i.year_num) componant3 = ComponentInfo.objects.filter(component__category__water_scheme = scheme,maintenance_interval__in = diff_year, apply_date__lte = i.end_date, interval_unit='Year').aggregate(labour_cost = Sum(F('labour_cost')*F('component_numbers'),output_field=FloatField()),\ material_cost = Sum(F('material_cost')*F('component_numbers'),output_field=FloatField()), \ replacement_cost = Sum(F('replacement_cost')*F('component_numbers'),output_field=FloatField()),\ maintenance_cost = Sum(F('maintenance_cost')*F('component_numbers'),output_field=FloatField()),) and the diff return method is : def get_factors_of(num): """Return factor of integer number""" factor_list = [1] for i in range(1, num + 1): if num == 1: factor_list = [x for x in range(1,15)] elif num % i == 1: factor_list.append(i) return factor_list this method should return a specific interval range -
Deploying to production a Django app - Azure
I have a Django app in a Github repo. Through a Github action, it is deployed as a Python app in Azure. In the Azure portal: 1- In "Configuration > Application" settings, I've defined POST_BUILD_COMMAND as python manage.py makemigrations && python manage.py migrate as described in Configure a Linux Python app for Azure App Service. 2- I have configured a deployment slot and a production slot. It offers a 'Swap' option, to push the live app in the deployment slot to production. However, I'm under the impression that doing that doesn't run the POST_BUILD_COMMAND command for the production Django app, leaving the database unaltered - which means that the production frontend gets the new fields/updates, but the migrations don't occur. What's the best way to perform the migrations in production? Would the correct way be to set "Configurations > General settings > Startup Command" to 'python manage.py makemigrations && python manage.py migrate'? Would that work? -
Connection to server at "localhost" failed in Docker - Django
Im very new to Docker and im trying to create a one for my django application. but i encounter the error "Is the server running on that host and accepting TCP/IP connections?connection to server at "localhost" (::1), port 5432 failed: Cannot assign requested address" I've tried this and this and this . Basically everything I could find but still doesnt work . Docker-compose version: '1' services: web: build: . container_name: evident_django hostname: evident_django restart: always image: evident:latest volumes: - ./logs:/var/log/evident - ./src:/code - static_volume:/code/static expose: - 7000 ports: - "127.0.0.1:7000:7000" env_file: - ./src/.env depends_on: - db networks: - evident_network db: image: postgres:13-alpine restart: always container_name: evident_postgres hostname: evident_postgres volumes: - ./storage:/var/lib/postgresql/data/ env_file: - ./src/.env expose: - 5432 networks: - evident_network volumes: static_volume: networks: evident_network: driver: bridge Dockerfile FROM python:3.10.4-slim-bullseye COPY requirements.txt /requirements.txt RUN set -ex \ && BUILD_DEPS=" \ apt-utils \ build-essential \ ffmpeg libsm6 libxext6 \ postgresql-client \ python3-opencv \ " \ && apt-get update && apt-get install -y --no-install-recommends $BUILD_DEPS \ && pip install -U --force-reinstall pip \ && pip install --no-cache-dir -r /requirements.txt \ && rm -rf /var/lib/apt/lists/* RUN mkdir /code/ WORKDIR /code COPY /src . EXPOSE 7000 ENTRYPOINT [ "./entrypoint.sh" ] and the errors im getting … -
Create multiple user types in django
I want to create multiple user types in Django. Each type has several unique attributes, and some common like username and email. The code below creates 3 tables with one to one connection to the Account user model. However I want to add choice field to the user model and store user types in tuples, instead of creating is_type1 is_type2 etc. variables, but I'm not sure how to connect those types with it's class. Here is my account model in models.py: class Account(AbstractBaseUser): email = models.EmailField(verbose_name='email', max_length=255, unique=True) username = models.CharField(verbose_name='username', max_length=30, unique=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_type1 = models.BooleanField(default=False) is_type2 = models.BooleanField(default=False) is_type3 = models.BooleanField(default=False) objects = MyAccountManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] def __str__(self): return self.username def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, app_label): return True And here is my subclasses: class Type1(models.Model): account = models.OneToOneField(Account, on_delete=models.CASCADE, primary_key=True) #unique attrs def __str__(self): return self.account.username class Type2(models.Model): account = models.OneToOneField(Account, on_delete=models.CASCADE, primary_key=True) #unique attrs def __str__(self): return self.account.username class Type3(models.Model): account = models.OneToOneField(Account, on_delete=models.CASCADE, primary_key=True) #unique attrs def __str__(self): return self.account.username -
In Django how to add a placeholder to a form based on model charfield
I have a form: class SideEffectForm(ModelForm): class Meta: model = SideEffect fields = ['se_name'] def __init__(self, *args, p, **kwargs): super().__init__(*args, **kwargs) if p == 'antipsychotic': self.fields['se_name'].choices = [ ("insomnia_and_agitation", "Insomnida and Agitation"), ("akathisia", "Akathisia"), ("dystonia", "Dystonia"), ] That is based on this model: class SideEffect(TimeStampedModel): SE_CHOICES = [ ("insomnia_and_agitation", "Insomnida and Agitation"), ("akathisia", "Akathisia"), ("anticholinergic_effects", "Anticholinergic Side Effects") ] se_name = models.CharField("",max_length=200, choices=SE_CHOICES, blank=False) concern = models.IntegerField("",default=50) case = models.ForeignKey(Case, on_delete=models.CASCADE) As it stands the form displays the first option. I would however like to have a place holder e.g. 'Please select a side effect'. I could do this by having it as one of the options but would prefer not to as then would need to implement measures to stop the placeholder being saved as a valid user entry. I have tried a range of suggestions on the site but none have been sutiable -
Django : Plotly plot shows on localhost but not on heroku
I am trying to display some plots(created with plotly) on my page, it works totally fine on localhost but when deployed on heroku the plots are not shown. code to create plot in views.py def icons(request, name): l1 = testtable.objects.values() d1 = [] d2 = [] for i in l1: d1.append(i["d1"]) d2.append(i["d2"]) fig =px.bar(x=d1,y=d2) photo = plotly.io.to_html(fig,config= {'displayModeBar': False}) fig2 = px.line(x=d1, y=d2) photo1 = plotly.io.to_html(fig2,config= {'displayModeBar': False}) return render(request, 'icons.html', {'name':name,"photo":photo,"photo1":photo1}) code in icons.html {% extends 'index.html' %} {% block content %} <div class="content icon-content"> <div class="container icon-container"> <h3 class="icon-heading">Quick Launch</h3> <div class="icon-bar"> <a class="active" href="#"><i class="fas fa-hand-pointer fa-2x"></i><span>Time In/Out</span></a> <a href="#"><i class="fa-solid fa-copy fa-2x"></i><span>My Attendance Record</span></a> <a href="#"><i class="fa-solid fa-calendar-minus fa-2x"></i><span>My Leave List</span></a> <a href="#"><i class="fa-solid fa-file-invoice-dollar fa-2x"></i><span>My Payslips</span></a> <a href="#"><i class="fa-solid fa-calendar-check fa-2x"></i><span>Apply Leave</span></a> <a href="#" class="timesheet-icon"><i class="fa-solid fa-calendar-days fa-2x"></i><span>My Timesheet</span></a> <a href="#" class="team-icon"><i class="fa-solid fa-people-group fa-2x"></i><span>My Team</span></a> </div> </div> <hr> <div class="container icon-container"> <h3 class="icon-heading">Pending My Approval</h3> <div class="icon-bar"> <a class="active" href="#"><i class="fa-solid fa-file-circle-check fa-2x"></i><span>Leave</span></a> <a href="#"><i class="fa-solid fa-user-check fa-2x"></i><span>Attendance Regularization</span></a> <a href="#"><i class="fa-solid fa-business-time fa-2x"></i><span>Timesheet</span></a> </div> </div> <div> {% if photo %} {{ photo|safe }} {% else %} <p>No graph was provided.</p> {% endif %} </div> <div> {% if photo1 %} {{ photo1|safe }} {% … -
Django ManyToMany field relationship confusion
I am using Django 3.2 I am writing an app for commuities, and I want to be able to provide functionality for Administrators of a Community, as well as functionality to allow users to request access to restricted or private Groups. I seem to be getting myself confused with the ManyToMany relationships. This is what I have so far (redacted): class Community(models.Model): pass # Group of administrators responsible for moderation and membership approvals # (for restricted and private communities) # Note: administrators can autopost and delete topics and comments class CommunityAdministrator(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.RESTRICT) community = models.ForeignKey(Community, on_delete=models.CASCADE, related_name="administrators") class Meta: constraints = [ models.UniqueConstraint(fields=['user', 'community'], name='idxu_commty_admin') ] # Community membership approvals (for restricted and private communities) # class CommunityMembership(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.RESTRICT) communities = models.ManyToManyField(Community, though='CommunityMembershipApproval') class CommunityMembershipApproval(models.Model): PENDING = 0 APPROVED = 1 REJECTED = 2 APPROVAL_STATES = ( (PENDING, 'Pending'), (APPROVED, 'Approved'), (REJECTED, 'Rejected') ) person = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) community = models.ForeignKey(Community, on_delete=models.CASCADE) approval_state = models.PositiveIntegerField(choices=APPROVAL_STATES, default=PENDING) request_tstamp = models.DateTimeField(auto_now=True) Will the tables above allow me to implement the functionality I described above - namely: Administrators - allow me to add/remove administrators of a community, and also access the administrators of a community via an … -
use ->, #> operators in django JSONfield ORM
I would like to use ->, #> operators with Django ORM. at the moment I was able to perform only: ModelWithJsonField.objects.filter(id=1).values('outputs__key') that is translate from ORM in: SELECT ("app_model_with_json_field"."outputs" #> ARRAY['key']) FROM "app_model_with_json_field" WHERE "app_model_with_json_field"."id" = 1; args=(['key'], 1) but .values() it can't be used with single object, so if I try: ModelWithJsonField.objects.get(id=1).values('outputs__key') Any ideas to how perform this kind of operators in Django ORM? -
How to get actual return value instead of task id in celery?
I have a django app to run some linux commands accepted from a form. I'm implementing both actual process, and one using celery. I pass arguments to celery task and want to get return value from it, but I'm getting only the task id I guess. This is me running celery task in views.py: if 'celeryform' in request.POST: command = request.POST.get('command') rep = request.POST.get('rep') dur = request.POST.get('dur') cmd ='powershell -command '+command result=celery_run.delay(cmd,rep,dur) context = {'output':result} return render(request,'home.html',context) This is my tasks.py: from __future__ import absolute_import,unicode_literals from celery import Celery, shared_task import time,subprocess app = Celery('tasks', broker='redis://localhost:6379',include=['problem.tasks.add']) @shared_task def celery_run(cmd,rep,dur): output='' for i in range(int(rep)): time.sleep(int(dur)) p=subprocess.run(cmd,capture_output=True,text=True,shell=True) output += p.stdout return output I display my output in a textarea in a webpage, I'm getting output as d59af727-b24d-4518-9b66-dff063864c4a The above one is task id I guess How to get actual return value? Sample return value using normal method with command=pwd,rep=1,dur=2 Path ---- D:\betsol\Linux_command_app Path ---- D:\betsol\Linux_command_app -
Change object label on specific value in js
I'm working on charts in React.js and i want to display data sorted by month. In django i've created view for displaying json with total events per month and it looks like this: [ { "month": "2022-06-01T00:00:00+02:00", "total": 4 }, { "month": "2022-08-01T00:00:00+02:00", "total": 1 } ] ] I would like to sort every object in that array and change value 'month' from numbers to month name, so it would be: [ { "month": "june", "total": 4 }, { "month": "august", "total": 1 } ] ] For generating charts i'm using chartist. -
Django IntegrityError when change data in admin
Sorry I don't know much about deployment, My django rest framework project (I'm using it as a backend API), works fine in my computer, I can access to my django admin page and do modifications. The problem is, when I deployed my project to a server (I used nginx and gunicorn), I can't change data in django admin page, but I can see data and all my models. The message I get when I try to modify a model's data : IntegrityError at /admin/myproject/study/185/change/ Error: null value in column "id" violates not-null constraint PS: I don't have an id column in my Model, and I already run migrations PS: I use postgresql I imported the database that I have exported from my local project -
Explicity enable cache in Django by function/endpoint but not site wide
Our Django application is quite big, and it has reached the point where Caching in certain parts will improve a lot the performance. However, when we enable caching it will do site wise, and so some endpoints are failing for different reasons. Our ideal solution therefore would be to have cache by explicitly setting it by function or rest api endpoint, and all the rest disable by default. In order to enable it we could just use the decorator: @cache_page The problem is that I cannot get the default cache to be disabled, I tried these different options but non of them seem to work. CACHES = { 'manual': { 'BACKEND': 'django.core.cache.backends.memcached.PyMemcacheCache', 'LOCATION': '127.0.0.1:11211', } } -- CACHES = { 'default': {}, 'manual': { 'BACKEND': 'django.core.cache.backends.memcached.PyMemcacheCache', 'LOCATION': '127.0.0.1:11211', } } -- CACHES = { 'default': None, 'manual': { 'BACKEND': 'django.core.cache.backends.memcached.PyMemcacheCache', 'LOCATION': '127.0.0.1:11211', } } -
icant see my 404 and 500 custome pages in django
hello i try to make a custom 404 and 500 pages in my django project so when i use this codes i cant see any result ! views.py: def handle404(request,exception): return render(request,'400.html',status=404) def handle500(request): return render(request,'500.html',status=500) url.py : handler404 ='base.views.handle404' handler500 = 'base.views.handle500' i see only this page : enter image description here anybody have some suggestions to improve my code ?