Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django on Elastic Beanstalk
I zipped my Django project and dropped it in the AWS Elastic Beanstalk service. My plan is to leverage IAM to deliver fine grained access to the SQL database populated via my Django app and otherwise from client device data (via MS ActiveDirectory, ) and patient files downloaded from obsolete devices. Am curious whether experts recommend populating my templates with AWS CLI code (to implement the IAM infrastructure programmatically) before I move the zipped files to EB or whether I can make adjustments to the Django templates sitting in EB already (perhaps from cloud9 or thru updates). First problem to address tho: my EB app status is "severe." Still troubleshooting the "severe" status issue. -
{% url ... %} templatetag in Django included template not seeing variable
I'm experiencing strange behaviour in an included template which I can't figure out. parent_template.html {% for item in items %} Parent: {{ item.pk }} {% include 'child_template.html' %} {% endfor %} child_template.html Child: {{ item.pk }} URL: {% url 'some_named_url' item.pk %} I get a reverse error: Reverse for '/test/url/<int:pk>/' with arguments '('',)' not found. 1 pattern(s) tried: ['test/url/(?P<pk>[0-9]+)/\\Z'] If however I remove the {% url ... %} template tag, it renders correctly and shows: Parent: 1 Child: 1 So it's clear that item is in the context, but for some reason it isn't being passed to the templatetag. I have also tried variations like: {% for item in items %} {% with new_item=item %} {% include 'child_template.html' %} {% endwith %} {% endfor %} Any ideas? I am using Django 3.2.12 -
Translate WKT geometry from database into GeoJSON using Django
I have a database with schools that have as attributes geometry in this format: 01040000000100000001010000000CC47A46B78BF64038FB9CC22D731A41 I was wondering how can I translate this geometry into latitude and longitude using django. views.py: from django.http import JsonResponse from django.shortcuts import render from rest_framework.decorators import api_view from base.models import RSchools as School from definitions import ROOT_DIR from .serializers import SchoolSerializer @api_view(['GET']) def get_data(request): schools = School.objects.all() for school in schools: #PREPROCESS EACH SCHOOL GEOMETRY HERE INTO LATITUDE AND LONGITUDE pass return render(request, f'{ROOT_DIR}/templates/tst/index.html', {'schools': schools}) models.py: from django.db import models # Create your models here. class RSchools(models.Model): gid = models.AutoField(primary_key=True) schooltype = models.CharField(max_length=254, blank=True, null=True) provincie = models.CharField(max_length=254, blank=True, null=True) straatnaam = models.CharField(max_length=254, blank=True, null=True) huisnummer = models.CharField(max_length=254, blank=True, null=True) postcode = models.CharField(max_length=254, blank=True, null=True) plaatsnaam = models.CharField(max_length=254, blank=True, null=True) gemeentena = models.CharField(max_length=254, blank=True, null=True) geom = models.TextField(blank=True, null=True) # This field type is a guess. class Meta: # managed = False db_table = 'r_schools' -
Foreignkey relationship returning an AttributeError when queried in Django
Hy please am new to Django,I have a childmodel(relationship) referencing a parent model(Profile) through a foreign key. I want to get the relationship status of a particular profile, like querying it from backwards. Here's the code. from django.db import models from django.contrib.auth.models import User #Create your models here. class Profile(models.Model): user = models.OneToOneField (User, on_delete= models.CASCADE) prof_pics = models.ImageField (null = True, blank = True, upload_to = 'images/') friends = models.ManyToManyField (User, blank=True, related_name="friend" ) bio = models.TextField(blank=True) def__str__(self): return str(self.user) STATUS CHOICES = ( ("accept", "accept"), ("send","send"), ) def ___str__(self): return str(self.user) class Relationship(models.Model): sender = models.Foreignkey(Profile, on_delete = models.CASCADE, null=True, related_name = "senders") date_created = models.DateTimeField(auto_now_add= True) receiver = models.ForeignKey(Profile, on_delete= models.CASCADE, null= True, related_name= 'receivers') status = models.Charfield(max_length=10, choices= STATUS_CHOICES) def_str_(self): return f"{self.sender}-{self.receiver}-{self.status}" The query I ran in my view to get the relationship of a particular profile as I saw a tutorial that did same thing with similar models. #imported necessary dependencies def relationship_view(request): idd = request.user.id profiles =Profile.objects.get(id=idd) rel=profiles.relationship_set.all() Print(rel) return render(request, "profiles/relationship_query.html", {}) A screenshot from the tutorial The error I get when I run my own view File "C:\Users\semper\djangotry\twitterclone\profiles\views.py", line 96, in Relationship_view rel = profiles.relationship_set.all() AttributeError: 'Profile object has no attribute 'relationship_set" -
Django ckeditor_uploader is not working what is the issue in my code
settings.py file enter image description here urls. py enter image description here models. py enter image description here -
Error: (admin.E035) The value of 'readonly_fields[0]' is not a callable
Summarize the problem <class 'news.admin.NewsAdmin'>: (admin.E035) The value of 'readonly_fields[0]' is not a callable, an attribut e of 'NewsAdmin', or an attribute of 'news.News'. This all code error. I learn Django, and write code how in author. But write this error :( Describe what you`ve tried I immediately insert problem in search, but not found decision I read this question, but it not finished This question elementary, author question not correct write variable Show some code admin.py from django.contrib import admin from .models import News, Category class NewsAdmin(admin.ModelAdmin): list_display = ('id', 'title', 'category', 'create_at', 'updated_at', 'is_published') list_display_links = ('id', 'title',) # what be links in model search_fields = ('title', 'content',) list_editable = ('is_published',) # redact is published in menu list_filter = ('is_published', 'category',) # create table, what in be setting sorted fields = ('title', 'category', 'content', 'photo', 'get_photo', 'is_published', 'views', 'create_at', 'updated_at') readonly_fields = ('get_photo', 'views', 'create_at', 'updated_at') class CategoryAdmin(admin.ModelAdmin): list_display = ('id', 'title') # displays list_display_links = ('id', 'title') # links search_fields = ('title',) admin.site.register(News, NewsAdmin) admin.site.register(Category, CategoryAdmin) models.py from django.db import models from django.urls import reverse class News(models.Model): title = models.CharField(max_length=150) content = models.TextField(blank=True) create_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) photo = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True) is_published = models.BooleanField(default=True) category … -
Filter Django model based on other model
I have two models Wellinfo and LOGRD_RPT class Wellinfo (models.Model): WellID = models.CharField(max_length=15,unique=True) Perimeter = models.CharField(max_length=50) class LOGRD_RPT(models.Model): WellID = models.CharField(max_length=15, validators= [validate_textComptn]) I need to get a list of WellID (ListaWells) from the first model Wellinfo based on two conditions: 1- Perimeter. 2- if the WellID exists in the second model LOGRD_RPT So the First step is to get all wells that belong to a Field='FD1' in the Wellinfo model ListaWells= Wellinfo.objects.filter(Perimeter=Field) then I need to exclude the wells that don't exist in the 2nd model LOGRD_RPT. -
Even Gunicorn works well in locally, I face with Internal Server Error
This is my first deploy in Django for production. I tested whether it can serve my Django application by running the following command and there is no problem I can reach my site by my server ip adress. gunicorn hello.wsgi:application --bind 0.0.0.0:8000 application --bind 0.0.0.0:8000 [2022-05-01 11:00:46 +0000] [26484] [INFO] Starting gunicorn 20.1.0 [2022-05-01 11:00:46 +0000] [26484] [INFO] Listening at: http://0.0.0.0:8000 (26484) [2022-05-01 11:00:46 +0000] [26484] [INFO] Using worker: sync [2022-05-01 11:00:46 +0000] [26486] [INFO] Booting worker with pid: 26486 /home/scknylmz35/PersonelBlog/home/views.py:24: UnorderedObjectListWarning: Pagination may yield inconsistent results with an unordered object_list: <class 'home.models.Blog'> QuerySet. Then I followed following commands: sudo nano /etc/systemd/system/gunicorn.service [Unit] Description=gunicorn daemon After=network.target [Service] User=baris Group=www-data WorkingDirectory=/home/baris/eventhub ExecStart=/home/baris/eventhub/venv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/home/baris/eventhub/eventhub.sock eventhub.wsgi:application [Install] WantedBy=multi-user.target sudo systemctl start gunicorn sudo systemctl enable gunicorn And I tested gunicorn >> sudo systemctl status gunicorn Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor pres> Active: active (running) since Sun 2022-05-01 08:01:47 UTC; 2h 19min ago Main PID: 23885 (gunicorn) Tasks: 4 (limit: 1132) Memory: 136.3M CGroup: /system.slice/gunicorn.service ├─23885 /home/scknylmz35/PersonelBlog/venv/bin/python /home/scknyl> ├─23897 /home/scknylmz35/PersonelBlog/venv/bin/python /home/scknyl> ├─23898 /home/scknylmz35/PersonelBlog/venv/bin/python /home/scknyl> └─23899 /home/scknylmz35/PersonelBlog/venv/bin/python /home/scknyl> It seems working good. But when I try to reach my site as mysite.me I face with "Internal Server Error" Also when … -
Why picture don't move Django
I can't do anything with my pic. It is be displayed, but my CSS-file don't work properly. Grid-class too HTML: {% extends 'main/base.html' %} {% load static %} {% block title %} {{title}} {% endblock %} {% block content %} <link rel = 'stylesheet' href = "{% static 'main/css/main.css' %}"> <body> <div class="grid-wrapper"> <header class="grid-header"> <img class="circles" width="1400px" height="249px" src="{% static 'main/img/main2.jpg' %}"> </header> <div class="grid-content"> Контент </div> </div> <body> {% endblock %} css: .cicles { display: block; margin-left: auto; margin-right: auto; } I try work with pic through .grid-header and .grid-wrapper. It didn't work -
"subprocess.run() wait for command to complete, then return a CompletedProcess instance", but I am getting the desired output late
I am learning django and I am stuck with this problem. I am using subprocess.run() but the output file generated by it is late. Here is the code snippet. run(["gnome-terminal", "--", "sh", "-c", f"ffmpeg -i {video_name}_audio_stripped.mp4 -i {audio_name} -c:v copy -c:a aac {final_tutorial}"], cwd="media/") #for i in range(1000000000): # continue run(["gnome-terminal", "--", "sh", "-c", f"ffmpeg -i {final_tutorial} -vcodec libx265 -crf 28 reduce_{final_tutorial}"], cwd="media/") As you can see that the second run() uses the first run() output as input but although the first run() executes and returns a CompletedProcess instance the file generated by it is generated late. Please note that the file has to be generated completely for the second run() to work, so although the first run() generates the file it does not generate it completely, I mean it does generate it but its too late so the second run() doesn't get the complete file and does not produce any output. I am unable to understand this ambiguous behaviour because according to python documentation subprocess.run run the command described by args. Wait for command to complete, then return a CompletedProcess instance. If I do uncomment the for loop in order to add a time delay it works but I … -
How to upload images in Django
I want to upload thumbnail into media/thumbnails folder, however my images uploads to media/thumbnails/thumbnails folder. How can I fix this? All my code models.py class Post(models.Model): title = models.CharField(max_length=100) content = RichTextField(null=True,blank=True) date_posted = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(User,on_delete=models.CASCADE) topic = models.ForeignKey(Topic,on_delete=models.SET_NULL,null=True) thumbnail = models.ImageField(default='default.jpg',upload_to='thumbnails/') def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail',kwargs={'pk':self.pk}) def save(self, *args, **kwargs): super(Post, self).save(*args, **kwargs) new_image = self.crop_max_square(Image.open(self.thumbnail.path)).resize((300, 300), Image.LANCZOS) new_image_io = BytesIO() new_image.save(new_image_io, format='JPEG') temp_name = self.thumbnail.name self.thumbnail.delete(save=False) self.thumbnail.save( temp_name, content=ContentFile(new_image_io.getvalue()), save=False ) settings.py MEDIA_ROOT = os.path.join(BASE_DIR,'media') MEDIA_URL = '/media/' -
What is the best way to restrict login page for authenticated users
I have the following middleware: class SimpleMiddleware: def __init__(self, get_response): self.get_response = get_response self.login_path = '/login/' self.home_path = '/' def __call__(self, request): if request.user.is_authenticated and request.path == self.login_path: return redirect(self.home_path) response = self.get_response(request) return response It is a good idea to redirect any already authed users to home page if they try to reach login page? Thanks in advance! -
How to add data to manytomanyfield in drf
enter image description here enter image description here enter image description here So I have a 2 models with a manytomany field. A book might be created without a publisher. When a publisher is added, I want to add it to the Books model with respect to its id any help is much appreciated -
Django `UniqueConstraint` exception handled the same as 'unique=True'
When UniqueConstraint of a model is violated, an exception is raised. How can I make it to behave the same as violation of a field with unique=True? identifier = models.CharField("id", max_length=30, unique=True, blank=True, null=True, validators=[validate_id]) class Meta: constraints = [ models.UniqueConstraint( Lower("identifier"), name="id_case_insensitive_constraint" ) ] Here I want a form's form_invalid called with the same field errors and all that, whether the input is exactly the same as another one or its only difference is case distinction. -
How to access a field through a sub table Django
I Have a table Product and a table Variation, I want to access the field Price inside the table Variation trough calling my Product Object How im trying to call the field in my HTML page: {{item.variation.price_set.first}} Note: {{item}} is my product object my models: class Product(models.Model): //JUST NORMAL FIELD STUFF class Variation(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) price = models.FloatField() -
Get queryset objects grouped by an annotation value range
I need to filter my objects in a way to get them grouped by range (range is fixed, for this case let's say we have these 3 ranges [0.0, 33.0] [33.01, 66.0] [66.01, 100.0] here is my model class Item(models.Model): name = models.CharField( help_text="Itemname", max_length=256 ) price = models.DecimalField(max_digits=6, decimal_places=2) I am trying to get a result that looks like this { "0.0-33.0": { name: x, }, "33.01-66.0": { name: y, name: z, }, } I tried something like this: item_by_range = Item.objects.filter(price__lte=100.0).annotate( price_group=Case( When(price__range=[0.0, 33.0], then=Value('0-33')), When(price__range=[33.01, 66.0], then=Value('33-66')), When(price__range=[66.01, 100.0], then=Value('66-100')), default=Value('No group'), output_field=CharField(), ) ).values('name', 'price_group').order_by('price_group') but this only works if I pass only price_group in values but this way I lose the name of the item thanks. -
Can you use session authentication with token authentication? Django Rest Framework
I’m using Django token based auth for my mobile app (react native) and I’m able to log in successfully. I’m also using the Spotify api which I have to open the browser (safari) to log in then it’ll redirect me back to a url in my backend Django-Rest then redirect me back to my react frontend. My issue is that I have to set a redirect uri for Spotify but can’t attach my auth token to it. So after I log into Spotify in the browser and it redirects to the url, I get a 401 error bc it won’t recognize the current user. Is there a way to store the token/current user in cookies/session so the browser will remember who the user is? Do I use session authentication?? Can I/Do I use both token and session authentication? Appreciate any help! Can provide more info if it’ll help -
Given that both the functions are asynchronous, how to ensure that the second function executes after the first function has completely executed
I am learning django and I am stuck with this problem. I wrote a code that uses a function two times. Here is the code snippet. rjl = run(["gnome-terminal", "--", "sh", "-c", f"ffmpeg -i {video_name}_audio_stripped.mp4 -i {audio_name} -c:v copy -c:a aac {final_tutorial}"], cwd="media/") while True: print("frgd") if(rjl.check_returncode()==None): print("wdcv") #for i in range(1000000000): # continue run(["gnome-terminal", "--", "sh", "-c", f"ffmpeg -i {final_tutorial} -vcodec libx265 -crf 28 reduce_{final_tutorial}"], cwd="media/") break else: print("ygbhb") So, the function is run(). Please note that run is subprocess.run. The second run() uses the output generated by the first run function as input. Since run() is asynchronous the second run() executes before the first run() has produced the desired output. In this case, the first run() produces a .mp4 file in the media folder. I made some changes in the code as you can see to solve this problem but still the problem remains. Can someone please suggest me what should I do? I am a newbie and some help will be appreciated. -
Refreshing context variable with ajax
getting null instead of the refreshed value when the event is triggered in the template, getting the correct value in both terminal and console for example success 6 and 6 respectively. How do I get the real value to render out instead of null, feel free to improve this question if you see anything wrong. Cheer! This is my code: path('ajax_update/', views.ajax_update, name="ajax_update"), view def ajax_update(request): stuff = bagstuff(request) bag = stuff['bag'] if is_ajax and request.method == "GET": if bag: print("success", bag) data_attribute = request.GET.get(bag) return JsonResponse(data_attribute, safe=False, status=200) else: print("failed") context = {"bag": bag} return render(request, template, context) template: <script> var number= "{{bag}}"; var update_bag_url = "{% url 'main:ajax_update' %}"; </script> javascript: function update_bag() { // optional: don't cache ajax to force the content to be fresh $.ajaxSetup ({ cache: false }); // specify loading spinner var spinner = "<img alt='loading..' />"; $("#lil-icon-two").html(spinner).load(update_bag_url); console.log(number); } -
in django filter argument kay not define error
my model is first_name=models.CharField(max_length=100, null=False) last_name=models.CharField(max_length=100) dept = models.ForeignKey(Department,on_delete=models.CASCADE) salary = models.IntegerField(default=0) bonus = models.IntegerField(default=0) role = models.ForeignKey(Role, on_delete=models.CASCADE) phone = models.IntegerField(default=0,max_length=12) hire_date = models.DateField(default=datetime.now() and my view is as if request.method == "POST": # print("post received") # print(request.POST) name = request.POST['first_name'] d = request.POST['department'] role = request.POST['role'] emps = Employee.objects.all() if name: emps = emps.filter(Q(first_name__icontains== name) | Q(last_name__icontains == d)) if d: pass if role: pass return render(request, 'fil_emp.html') but at this time i received error like ** "first_name__icontains" is not defined ** -
Getting Image through HTML and using Python Code
I am trying to make a website that gets the user image and uses facelandmark code(python) to tell the user about user's face shape and etc. How can I get the imange through html and use the image file in python code and show the result to the user again? Is using django the only way? I have tried to study django in many ways and most of the stuffs I found were not directly helping on my planning website. Thank you for reading -
Django creating post for foreign key has error 'Direct assignment to the reverse side of a related set is prohibited'
I have a Protein model that is linked to the Domain model through the proteins foreign key in the Domain model. class Protein(models.Model): protein_id = models.CharField(max_length=256, null=False, blank=False) sequence = models.CharField(max_length=256, null=True, blank=True) length = models.IntegerField(null=False, blank=False) taxonomy = models.ForeignKey(Organism, blank=True, null=True, on_delete=models.DO_NOTHING) def __str__(self): return self.protein_id class Domain(models.Model): domain_id = models.CharField(max_length=256, null=False, blank=False) description = models.CharField(max_length=256, null=False, blank=False) start = models.IntegerField(null=False, blank=False) stop = models.IntegerField(null=False, blank=False) proteins = models.ForeignKey(Protein, blank=True, null=True, related_name="domains", on_delete=models.DO_NOTHING) def __str__(self): return self.domain_id I want to post a new protein record using the Protein serializer. The Protein serializer displays the data from the Domain under the domains field. class ProteinSerializer(serializers.ModelSerializer): domains = DomainSerializer(many=True) taxonomy = OrganismSerializer() class Meta: model = Protein fields = [ 'protein_id', 'sequence', 'taxonomy', 'length', 'domains', ] I made the create function in the Protein serializer to create the two foreign keys when posting a new record. However, when creating the foreign key for domains, I get the error TypeError: Direct assignment to the reverse side of a related set is prohibited. Use domains.set() instead. I have tried using domains.set() for my domains list but it still gives me the same error? def create(self, validated_data): taxonomy_data = self.initial_data.get('taxonomy') domains_data = self.initial_data.get('domains') domains_list … -
Django forms not saving posts to database
i am trying to create a course from my frontend using django form, everything seems fine but when i hit the create button it just refreshes the page without saving to database or throwing back any error, and that is not what i am expecting. create-course.html def create_course(request): if request.method == "POST": form = CreateCourse(request.POST, request.FILES) if form.is_valid(): new_form = form.save(commit=False) new_form.slug = slugify(new_form.course_title) new_form.course_creator = request.user new_form.save() messages.success(request, f'Your Course Was Successfully Created, Now in Review') return redirect('dashboard:dashboard') else: form = CreateCourse() context = { 'form': form } return render(request, 'dashboard/create_course.html', context) models.py class Course(models.Model): course_title = models.CharField(max_length=10000) slug = models.SlugField(unique=True) course_thumbnail = models.ImageField(upload_to=user_directory_path) short_description = models.CharField(max_length=10000) course_description = models.TextField() price = models.IntegerField(default=0) discount = models.IntegerField(default=0) requirements = models.CharField(max_length=10000) course_level = models.CharField(max_length=10000, choices=COURSE_LEVEL) # course_rating = models.CharField(max_length=10000, choices=COURSE_RATING) # course_rating = models.ForeignKey(CourseRating, on_delete=models.SET_NULL, null=True, blank=True) course_language = models.CharField(max_length=10000, choices=COURSE_LANGUAGE) # course_category = models.CharField(max_length=10000, choices=COURSE_CATEGORY) course_category = models.ForeignKey(Category, on_delete=models.DO_NOTHING) course_tag = models.ManyToManyField(Tag) course_cost_status = models.CharField(max_length=10000, choices=COURSE_COST_STATUS, default="Free") course_intro_video = models.FileField(upload_to=user_directory_path) course_intro_video_url = models.URLField(default="https://") course_intro_video_embedded = models.URLField(default="https://") course_creator = models.ForeignKey(User, on_delete=models.CASCADE) date_created = models.DateTimeField(auto_now_add=True, null=True) course_duration = models.IntegerField(default=0) course_publish_status = models.CharField(max_length=10000, choices=COURSE_PUBLISH_STATUS) views = models.IntegerField(default=0) likes = models.IntegerField(default=0) featured = models.BooleanField(default=False) digital = models.BooleanField(default=True) best_seller = models.BooleanField(default=False) forms.py from course.models import … -
Django - how to update elements within a list in a single pUT request
Could use some help with the following please. I am looking to update the objects in a list as one PUT request, how would I go about doing it? I've made some progress but I can't seem to figure it out. The list to PUT to perform updates could be some of the objects in the table, or all of them. But I am aiming to, in one request, submit a list of share elements, and have all the elements that match those in the table be updated with the new values, if any, of the elements within the list of this one PUT request. Models.py class Share(models.Model): ShareName = models.CharField(max_length=100, unique=True, default="N/A") ISINCode = models.CharField(max_length=100, primary_key=True, default="N/A") Price = models.DecimalField(decimal_places=6, max_digits=9, default=0.000000) Serializers.py class ShareSerializer(serializers.ModelSerializer): """ Serializer for Share """ class Meta: model = Share fields = ('ShareName', 'ISINCode', 'Price') Views.py class ShareViewSet(ModelViewSet): authentication_classes = [] permission_classes = [] queryset = Share.objects.all().order_by('ISINCode') # serializer_class = ShareSerializer paginator = None def get_serializer(self, *args, **kwargs): if "data" in kwargs: data = kwargs["data"] # enable list posting if isinstance(data, list): kwargs["many"] = True return super(ShareViewSet, self).get_serializer(*args, **kwargs) I've read through the docs here https://www.django-rest-framework.org/api-guide/serializers/#listserializer and also figured out one way to probably … -
Custom Mixin is not showing up
I'm not getting any errors but the carousel not showing up in my content/views.py class IndexView(CarouselObjectMixin, ListView): model = Post template_name = 'index.html' cats = Category.objects.all() ordering = ['-post_date'] ordering = ['-id'] def get_context_data(self, *args, **kwargs): cat_menu = Category.objects.all() context = super(IndexView, self).get_context_data(*args, **kwargs) context["cat_menu"] = cat_menu return context maybe their is something wrong with my custom mixin itself, I'm not sure if I build it correctly. slideshow/views.py class SlideShowView(ListView): model = Carousel context_object_name = 'carousel' template_name = 'showcase.html' Custom Mixin class CarouselObjectMixin(object): model = Carousel context_object_name = 'carousel' template_name = 'showcase.html' slideshow/templates/showcase.html {% extends 'base.html' %} {% load static %} {% block content %} <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1" /> <!-- Showcase --> <body> <section class="bg-transparent text-dark text-center"> <div id="carouselExampleControls" class="carousel slide" data-bs-ride="carousel"> <div class="carousel-inner"> {% for object in carousel %} <div class="carousel-item {% if forloop.counter0 == 0 %} active {% endif %}"> <img src="{{object.image.url}}" class="d-block w-100" alt="..."> </div> {% endfor %} </div> <button class="carousel-control-prev" type="button" data-bs-target="#carouselExampleControls" data-bs-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="visually-hidden">Previous</span> </button> <button class="carousel-control-next" type="button" data-bs-target="#carouselExampleControls" data-bs-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="visually-hidden">Next</span> </button> </div> </section> <!-- Post --> </body> {% endblock %} slideshow/models.py class Carousel(models.Model): title = models.CharField(max_length=255, blank=True) description = models.TextField(max_length=255, blank=True) image = models.ImageField(upload_to="showcase/%y/%m/%d/", …