Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
request.META.get('HTTP_REFERER') isn't working when prefix_default_language=True
url = request.META.get('HTTP_REFERER') worked when prefix_default_language=False. But when I make prefix_default_language=True, it isn't getting anything. Help please. -
How to display the product of multiple models in a model using foreign key or something else
I want to display my product offers and monthly plans in the single model Theres products and monthly plan model class Monthlyplan(models.Model): ... name = models.CharField(max_length=220) class Product(models.Model): ... name = models.CharField(max_length=220) class Customers(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) monthly_plan = models.ForeignKey(Monthlyplan, on_delete=models.CASCADE) Packages = GenericForeignKey('product', 'frozen_food') error core.Customers.Packages: (contenttypes.E004) 'Customers.product' is not a ForeignKey to 'contenttypes.ContentType'. HINT: GenericForeignKeys must use a ForeignKey to 'contenttypes.ContentType' as the 'content_type' field. -
ImportError: No module named sentry_sdk.integrations.wsgi
I'm trying to upgrade the implementation of the old Sentry config to the new one for my wsgi configuration in my django project but I'm getting the following error. ImportError: No module named sentry_sdk.integrations.wsgi Earlier I had: from raven.contrib.django.raven_compat.middleware.wsgi import Sentry Now I have: from sentry_sdk.integrations.wsgi import SentryWsgiMiddleware My sentry init is in settings.py file as: sentry_sdk.init( dsn=SENTRY_CONFIG.get("dsn", ""), environment=SENTRY_CONFIG["environment"], integrations=[ DjangoIntegration(), CeleryIntegration(), sentry_logging, ], attach_stacktrace=True, send_default_pii=True, ) Using: Django==4.0.3 sentry-sdk==1.5.8 python3.8 Any help is appreciated, thanks in advance! -
got error while setting default image in ImageField Django
my model have an imagefield which stores the image for post . I want to add default image to that in case if not is not uploaded.But I am getting error The 'title_image' attribute has no file associated with it. If I upload image then its working fine. Models.py class Post(models.Model): title_image = models.ImageField( upload_to='Images/PostTitleImages/', max_length=None, default = 'Images/Image_not_found.jpg', blank = True, null = True) home.html <img src="{{post.title_image.url}}" height="350px"/> Settings.py STATIC_URL = 'static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static/'), ] MEDIA_URL = 'media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') urls.py urlpatterns = [ path('admin/', admin.site.urls), path('',include('MainSite.urls'), name = "Main"), path('account/',include('account.urls'), name = 'Accounts') ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) what I am doing wrong here I checked the file is in this directory /media/Images/PostTitleImages/ -
how can ı submit more than one row in django view with table form
ı wanna submit more than one record but in that code only first student can be record how can ı add more than one record in django view ı am prety new in django can anyone help about that table image thats the model.py class GonulluOgrenciDevamsizlik(models.Model): ogrenci_dersi = models.ForeignKey('Ogrenci', null=True, on_delete=models.SET_NULL) gonulu = models.ForeignKey('Gonullu', null=True, on_delete=models.SET_NULL) devamsizlik = models.BooleanField(verbose_name="Devamsızlık Bilgisi",blank=True, default=False) sinif = models.ForeignKey('SinifListe', null=True, on_delete=models.SET_NULL) olusturma_tarihi = models.DateTimeField(auto_now_add=True, verbose_name='Oluşturma Tarihi') guncelleme_tarihi = models.DateTimeField(auto_now=True) class Meta: ordering = ['-devamsizlik'] verbose_name = 'Devamsızlık' verbose_name_plural = 'Devamsızlıklar' def __str__(self): return self.gonulu.ad + ' ' + self.gonulu.soyad here is my view: in view ı had been add required foreign keys for my table and then try to save coming post data from table form. def ogrencidevamsizlik(request, id): details = "hesabim/ogrenci-devamsizlik.html" siniflar = SinifListe.objects.filter(gonullu__gonullu__email=request.user.email) ogrenci = SinifDetay.objects.filter(sinif__gonullu__gonullu__email=request.user.email) gonulu = GonulluDersleri.objects.get(gonullu__email__iexact=request.user.email, id=id) gonulluler = Gonullu.objects.get(email__iexact=request.user.email) ders = GonulluDersleri.objects.filter(gonullu__email=request.user.email, id=id) devamsizliklar = SinifDetay.objects.filter(sinif__gonullu__gonullu__email=request.user.email, sinif__gonullu__id=id) if request.method == 'POST': form = DevamsizlikDetayForm(request.POST, request.FILES) if form.is_valid(): form.save() messages.success(request, 'Devamsızlıklar başarılı bir şekilde eklendi.') return redirect('gonullu-siniflar') else: messages.error(request, 'Devamsızlık bilgilerinizdeki zorunlu alanları eksiksiz doldurmalısınız.') else: form = DevamsizlikDetayForm() context = {'devamsizliklar': devamsizliklar, 'gonulu': gonulu, 'ders': ders, 'form': form, 'ogrenci': ogrenci, 'siniflar': siniflar, 'gonulluler': gonulluler} return render(request, details, context) and … -
Function like keyword in return statement before loop in DRF APIView permission
Hey guys I am having a hard time understanding the following return statement code in django drf APIView source code: def get_permissions(self): """ Instantiates and returns the list of permissions that this view requires. """ return [permission() for permission in self.permission_classes] I understand that permission is the key iterating through permission_classes but what on earth is the permission() doing here -
How to implement Django social login using google for different type of users(eg: candidate ,employer, customer)
I want to implement Social login in my Django project. When I searched about it, I found social login for only one user. But I want to implement it for different type of users as I mentioned in the title. Can anyone suggest a solution to implement this in my project. -
Django-Python : Check if network file exists from web client
I would like to know if a network file exists from web client. On the server in localhost, it works (return True) but return False with IP adress. Code : folder = "\\IP\dir_test" id = "123456" filename = "{}.pdf".format(str(id)) path = os.path.abspath(folder + filename) check = os.path.isfile(path) return check Thanks for your help. Ben. -
Repetition of the same results consecutif
I need to check if I have repetition 4 times the same value for "PCR POS/Neg" consecutive, 3 times in my "output_df". How i can do it ? def results1(file1,file2): results_list = defaultdict(list) names_loc = file2 listing_file = pd.read_excel(file1, index_col=None) headers = ['Vector Name', 'Date and Time', 'Test ID', 'PCR POS/Neg'] output_df = pd.DataFrame(columns=headers) with open(names_loc, "r") as fp: for line in fp.readlines(): line = line.rstrip("\\\n") full_name = line.split(',') sample_name = full_name[0].split('_mean') output_df['Date and Time'] = pd.to_datetime(output_df['Date and Time']) -
Django: Duplicate value to the new field on mingration
I have a modal called Account as below class Account(models.Model): name = models.CharField(max_length=225) category = models.ForeignKey(AccountCategory, on_delete=models.PROTECT) date_added = models.DateTimeField(auto_now_add=True) added_by = models.ForeignKey(Staff, on_delete=models.SET_NULL, null=True) I already have data there, but i need to add another field called display_name which i need to inherit the value of name. i tried adding a field with a default value of name like this display_name = models.CharField(max_length=255, default=name) This was my final modal: class Account(models.Model): name = models.CharField(max_length=225) display_name = models.CharField(max_length=255, default=name) category = models.ForeignKey(AccountCategory, on_delete=models.PROTECT) date_added = models.DateTimeField(auto_now_add=True) added_by = models.ForeignKey(Staff, on_delete=models.SET_NULL, null=True) But it failed to populate the field. someone help me out. -
How to handle 50k or above array of objects in Django Rest Framework?
I'm facing a problem. Our requirement is we cannot use pagination so we need all records at a time in Response. my function like this: from rest_framework.response import Response class TestingViewsAPI(APIView): def get(self, request): data_list = [{}....................] #50k list of dict return Response({ "Data": { "data": data_list, } }) When doing this then my system hang how i can handle this? I need expert guidelines I don't use pagination -
Manager isn't accessible via Police instances
Error is occurred in if user.objects.filter(login_id=login_obj).exists(): how to solve this error This is my police_app/views.py def police_register(request): if request.method == 'POST': login_obj = Login() login_obj.username = request.POST.get('uname') login_obj.password = request.POST.get('pwd') login_obj.save() if Login.objects.filter(username=request.POST.get('uname')).exists(): user = Police() user.station_name = request.POST.get('name') user.email = request.POST.get('email') user.mobile = request.POST.get('mob') user.district = request.POST.get('district') user.state = request.POST.get('state') user.login_id = login_obj user.save() if user.objects.filter(login_id=login_obj).exists(): return render(request, "login.html") return render(request, "police_app/police_register.html", context={'error': 'Registration failed'}) return render(request, "police_app/police_register.html") -
How to resolve problem with CORS policy django
I try to create module with OpenStreetMaps on my website, but when I try use it i got some errors: Access to image at 'https://c.tile.openstreetmap.org/3/6/5.png' (redirected from 'http://c.tile.openstreetmap.org/3/6/5.png') from origin 'http://127.0.0.1:8000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. I try some method from web, but still not results. Can you see any error in code? In website script map is loading but map image have error. I try add corsheader middleware but problem still exist. I don't what to do more to repair this problem. All is fine but images have problem. Settings file from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent ALLOWED_HOSTS=['127.0.0.1'] # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '--' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True # Application definition INSTALLED_APPS = [ 'corsheaders', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'gosgucompl', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'corsheaders.middleware.CorsPostCsrfMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ORIGIN_ALLOW_ALL = True ROOT_URLCONF = 'gosgu.urls' TEMPLATES = [ { … -
Need to make two model fileds as primary key
Here profile and category should be primary key how can i do this. class QuickApproximation(models.Model): profile = models.CharField(primary_key=True, null=False, max_length=1024, default=None) category = models.CharField(null=False, max_length=1024, default=None) approximation = models.IntegerField(null=False, default=None) I need to dump this data into DB Profile,Category,Approximations Always on road,Groceries,500 Always on road,Dining,500 Always on road,Gas,500 Always on road,Others,1500 Social Butterfly,Groceries,500 Social Butterfly,Dining,500 Social Butterfly,Gas,500 Social Butterfly,Others,1500 Foodie,Groceries,500 Foodie,Dining,500 Foodie,Gas,500 Foodie,Others,1500 Pantry Stocker,Groceries,500 Pantry Stocker,Dining,500 Pantry Stocker,Gas,500 Pantry Stocker,Others,1500 Avid Shopper,Groceries,500 Avid Shopper,Dining,500 Avid Shopper,Gas,500 Avid Shopper,Others,1500 Healthy nut,Groceries,500 Healthy nut,Dining,500 Healthy nut,Gas,500 Healthy nut,Others,1500 Digital Junky,Groceries,500 Digital Junky,Dining,500 Digital Junky,Gas,500 Digital Junky,Others,1500 and everything should be available in db -
Error when try to integrate payment system
I try to integrate payment system to django. I did use django-flexible-subscriptions, installed, created appropriate url, view and html. But when I created Subscription Plan and when tried to save get an error "conversion from NoneType to Decimal is not supported". Somebody knows how can I fix this error? Best regards -
How to get the day difference in a little complicated way using queryset in Django
I am using Django, and whenever the manager of a task is changed, the change is saved in the history field. The history field is saved as follows. Here, I would like to get the duration of each manager. EX: {'field_summary': {'manager': 'Michael -> Michael/Amelia', 'contact': '010-1234-1234-> 010-1234-1234/010-9876-9876'}} [models.py] Task(models.Model): task_name = models.CharField(max_length=100, blank=False) manager_name = models.CharField(max_length=100, blank=False) history = models.ForeignKey(History, on_deleted=models.SET_NULL) .... create_date = models.DateTimeField(auto_now_add=True) [views.py] task = Task.objects.filter(id='20', history__summary__icontains='manager') [statistic.html] {% for task in task %} {% for h in task.history %} {% if h.summary_json.field_summary.manager %} manager: {{ h.summary_json.field_summary.manager }} date: {{ h.create_date }}, {% endif %} {% endfor %} {% endfor %} [result] manager: Michael/Amelia -> Michael/Sophia change_date: 2022-02-25, manager: Michael -> Michael/Amelia change_date: 2021-10-12, manager: Michael/Amelia -> Michael change_date: 2021-09-23, manager: who -> Michael/Amelia change_date: 2021-05-12, manager: None -> who change_date: 2021-04-12 I want to output something like Michael: 2021.05.12 ~ today total: 316 days Amelia:2021.05.12 ~ 2021.09.23 (134), 2021.10.12 ~ 2022.02.25. (136) total: 270 days Sophia: 2022.02.25. ~ today total: 27 days queryset -> Michael, 316, Amelia, 270, Sophia, 27 -
django : rename in admin panel does not work
When i change the primary key in the admin panel and choose the save button a new recrod is created. But i want to rename the primary key. models.py: class Firma(models.Model): firma = models.CharField( primary_key=True, max_length=50, db_column='Firma', help_text='Firma', verbose_name = 'Firma', ) def __str__(self): return self.firma admin.py: class FirmaAdmin(admin.ModelAdmin): list_display = ( 'firma', ) ordering = ('firma',) I use Django 3.2. What am I doing wrong? -
why is my list cannot be convert into zip list? python
i have 2 list that i got from input in my html i want to ouput that 2 list together but when i use zip(lista, listb) no output shown {% for proc, ope in procslist %} <tr> <td style="width:10%;">{{proc.id}}</td> <td style="width:10%;">{{proc.name}}</td> <td style="width:10%;">{{proc.setcost}} / {{proc.proccost}}</td> <td style="width:10%;">{{proc.id}}</td> <td style="width:10%;">{{proc.id}}</td> <td style="width:10%;">{{proc.id}}</td> <td style="width:10%;">{{proc.settime}}</td> <td style="width:10%;"> <input type="hidden" name="opetimelist" value="{{proc.id}}" id=""> <input type="text" name="opetime-{{proc.id}}" id="" value="{{ope}}" style="width: 80%;"> </td> </tr> {% endfor %} and this is my views.py proc = '' choosenproc = request.POST.get('choosenproc') if choosenproc: proc = Proc.objects.get(Q(name__icontains=choosenproc) | Q(id__icontains=choosenproc)) flag = False if proc: if selectedproc != []: for product in selectedproc: if product.id == proc.id: flag = True break if flag == False: selectedproc.append(proc) opetimelist = request.POST.getlist('opetimelist') opetimevalue = [request.POST['opetime-{}'.format(o)] for o in opetimelist] procslist = zip(selectedproc, opetimevalue) the result it no ouput how to fix this? -
django rest framework saving data to multiple tables from a single view
I'm currently new to DRF I am looking to save data to two database tables via the viewset and I don't know how to go about it. I am using react for my frontend here is my models from django.db import models # Create your models here. class Customer(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=255) phone = models.CharField(max_length=255) town = models.CharField(max_length=255) region = models.CharField(max_length=255) added_on = models.DateTimeField(auto_now_add=True) objects = models.Manager() class Order(models.Model): id = models.AutoField(primary_key=True) order_no = models.CharField(max_length=255) customer_name = models.CharField(max_length=255) phone = models.CharField(max_length=255) town = models.CharField(max_length=255) region = models.CharField(max_length=255) farmer_id = models.ForeignKey(Farmer, on_delete=models.CASCADE) price_per_kgs = models.CharField(max_length=255) kgs = models.CharField(max_length=255) packaging = models.CharField(max_length=255) transport = models.CharField(max_length=255) discount = models.CharField(max_length=255) amount = models.CharField(max_length=255) status = models.BooleanField(default=False) added_on = models.DateTimeField(auto_now_add=True) objects = models.Manager() and here is my serializer from rest_framework import serializers # Create your serializers here from barakasalessystemApp.models import Farmer, Customer, Bill, Payments, Orders class FarmerSerializer(serializers.ModelSerializer): class Meta: model = Farmer fields = "__all__" class CustomerSerializer(serializers.ModelSerializer): class Meta: model = Customer fields = "__all__" class OrdersSerializer(serializers.ModelSerializer): class Meta: model = Orders fields = "__all__" def to_representation(self, instance): response = super().to_representation(instance) response["farmer"] = FarmerSerializer(instance.farmer_id).data return response this is my views from functools import partial from django.shortcuts import render from rest_framework import viewsets, … -
how to password protect my site in django
Is is possible to password protect my whole site. I'm new to Django and i want to create a chatroom for a group of friends, but i want to have a password to get into the room. is there any tutorial out there in where i can put a password that anyone can use over my whole site? so far I have a website which can be used to input text but has no verification for passwords. all i've found are complicated tutorials for creating users and managing them. I'm looking for something simple. Thanks. -
How to view my data on the page without reload it and how to post my data on server?
I have a python script on my PC, that takes data from sensors and return it in the list like: [24 25, 32, 56] This data from different 4 sensors. Also i have a server with django site. I want to take data from sensors and display it on my html page without reloading the page. How can i do it? I listened about ajax, maybe you have helpful links to similar problem or lesson. my python-script for taking data from hardware: import serial import time wox = serial.Serial('COM3', 115200,stopbits=1) #Открыли порт while True: #if wox.inWaiting() two_sensors = wox.readline().decode("utf-8") two_sensors = two_sensors.replace("\n","") st_two_sensors = two_sensors.split(",") st_two_sensors[3] = float(st_two_sensors[3])/220000 print(st_two_sensors) temperature_0 = int(st_two_sensors[0]) temperature_1 = int(st_two_sensors[1]) voltage = st_two_sensors[2] Simple html: {% load static %} <html> <head> <meta http-equiv="Content-Type" content="text/html; Charset=UTF-8"> <!--<meta http-equiv="refresh" content="7"> --> <script type="text/javascript" src="{% static '/js/jquery-3.6.0.js' %}"></script> </head> <body> I want to have sensor data here with live updating. </body> </html> beside ajax i listened about web-sockets what would be easier? and where can i find examples Also i intrested how to transmit that data to the server, maybe some url requests? -
No retrived data in related table/model in django
i have this api that will retrieve the data of a farmer, now I retrieved the main profile but not the details in parcels. model.py from django.db import models class Farmer(models.Model): record_no = models.CharField(primary_key=True,max_length=19) control_no = models.CharField(max_length=50) fname = models.CharField(max_length=100) mname = models.CharField(max_length=100) lname = models.CharField(max_length=100) ename = models.CharField(max_length=100) sex = models.CharField(max_length=6) birthday = models.DateField(blank=True, null=True) arb = models.CharField(max_length=3) pwd = models.CharField(max_length=3) ben_4ps = models.CharField(max_length=3) ip = models.CharField(max_length=3) tribe_name = models.CharField(max_length=100) fca_mem = models.CharField(max_length=3) fca_name = models.CharField(max_length=200) house_no = models.CharField(max_length=100) street = models.CharField(max_length=100) region_code = models.CharField(max_length=2) region_shortname = models.CharField(max_length=50) region_longname = models.CharField(max_length=150) province_code = models.CharField(max_length=2) province_name = models.CharField(max_length=150) municipality_code = models.CharField(max_length=2) municipality_name = models.CharField(max_length=150) brgy_code = models.CharField(max_length=2) brgy_name = models.CharField(max_length=150) farm_size = models.DecimalField(max_digits=10,decimal_places=4) class Meta: managed = False db_table = 'farmers' class Parcels(models.Model): record_no = models.ForeignKey(Farmer,null=True, db_column='record_no',on_delete=models.CASCADE) parcel_no = models.IntegerField() parcel_farm_area = models.DecimalField(max_digits=10,decimal_places=4) type_of_ownership = models.CharField(max_length=100) presented_doc = models.CharField(max_length=100) reg_name = models.CharField(max_length=100) prov_name = models.CharField(max_length=100) mun_name = models.CharField(max_length=100) bgy_name = models.CharField(max_length=100) class Meta: managed = False db_table = 'parcels' serializers.py from rest_framework import serializers from .models import Farmers, Parcels class ParcelDetailSerializer(serializers.ModelSerializer): class Meta: model = Parcels fields = ['record_no','parcel_no','parcel_farm_area','type_of_ownership','presented_doc','reg_name','prov_name','mun_name','bgy_name'] class FarmerDetailSerializer(serializers.ModelSerializer): parcels = ParcelDetailSerializer(many=True, read_only=True) class Meta: model = Farmers fields = ['control_no','record_no','fname','mname','lname','ename','sex','birthday','arb','pwd','ben_4ps','ip','tribe_name','fca_mem','fca_name','house_no','street','region_code','region_shortname','region_longname','province_code','province_name','municipality_code','municipality_name','brgy_code','brgy_name','farm_size','parcels'] views.py from django.shortcuts import render from rest_framework.decorators … -
How to use Django AutoSlug in Custom Form
I am working on a project and using the django-autoslug package to auto generate slugs for me. The package does its job perfectly well and I like it. So far, I can edit slugs from the admin panel when I added editable=True which works well from the admin panel. Now I want a working system where users can easily edit there slug from an UpdateForm in the UpdateView. I tried the official docs but I think it is limited to the admin panel and no support for the regular custom forms. Is there any better solution that can solve this for me? A solution that can auto generate forms, and also allow my users update their slug uniquely. I'll be very grateful if I get a solution on this. Warm Regards. slug = AutoSlugField(populate_from='name', unique=True, editable=True) -
Unable to make websocket connection in django
I am trying to make a websocket connection I am using the django's channels API. For some reason the handshaking is not taking place. Maybe it has something to do with the url? This is my main routing.py file from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter,URLRouter import chat.routing application = ProtocolTypeRouter({ 'websocket':AuthMiddlewareStack( URLRouter( chat.routing.websocket_urlpatterns ) ), }) This is my chat app routing.py from django.urls import re_path,path # from django.conf.urls import url from . import consumers websocket_urlpatterns = [ re_path(r'ws/chat/room/(?P<room_name>\w+)/(?P<username>\w+)/$',consumers.ChatRoomConsumer.as_asgi()), ] This is my chat app consumers.py file # import pytest from accounts.models import Account from .models import ChatRoom, Message from channels.generic.websocket import AsyncWebsocketConsumer import json from channels.db import database_sync_to_async import string import random # from asgiref.sync import sync_to_async class ChatRoomConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name= 'chat_%s'%self.room_name await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self,close_code): await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) async def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] username = text_data_json['username'] room_name = text_data_json['room_name'] # print("[RECIEVED] "+room_name) print("[receiving....]"+message) await self.channel_layer.group_send( self.room_group_name, { 'type':'chatroom_message', 'message':message, 'username':username, 'room_name':room_name, } ) async def chatroom_message(self,event): message = event['message'] username = event['username'] room_name = event['room_name'] print("[SENDING....]"+message) room_obj = ChatRoom.objects.get(room_name=room_name) sender = Account.objects.get(username=username) await self.save_message(message=message,sender=sender,room_name=room_obj) await self.send(text_data=json.dumps({ 'message':message, 'username':username, … -
This is a django project . I am trying to fetch carousel image from database but it's ,only one image showing and slider not changing
00 I am trying to make a carousel slider. The picture comes from the database and is then rendered on the frontend slider. But the picture is rendering but it is creating a new slider and when I change to the next slide then it shows the same picture. What to do?? I am trying to make a carousel slider. The picture comes from the database and is then rendered on the frontend slider. But the picture is rendering but it is creating a new slider and when I change to the next slide then it shows the same picture. What to do?? my Url.py from django.urls import path from . import views urlpatterns = [ path('',views.home, name='home'), ] views.py from django.shortcuts import render from .models import Products, About, Slider, Team # Create your views here. def home(request): slider = Slider.objects.all() return render(request, 'index.html', {'slider':slider}) index.html <!-- slider --> <div id="carouselExampleCaptions" class="carousel slide" data-bs-ride="carousel"> <div class="carousel-indicators"> <button type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide-to="0" class="active" aria-current="true" aria-label="Slide 1"></button> <button type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide-to="1" aria-label="Slide 2"></button> </div> <div class="carousel-inner"> **{% for s in slider %} <div class="carousel-item active"> <img src="{{ s.image.url }}" class="d-block w-100" alt="..."> <div class="carousel-caption d-none d-md-block"> <h5 class="fw-bolder fs-2">{{ s.Title }}</h5> <p class="fw-bolder …