Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django development server not serving css files correctly (error : was blocked due to MIME type (“text/html”) mismatch)
I'm developing a Django webapp and have the issue with the following code in base.html: <!-- Theme CSS --> <link rel="stylesheet" type="text/css" href="{% static 'assets/css/style.css' %}"> The CSS get's blocked by the browser because of incorrect mimetype. Funny thing is that if I duplicate the line (so loading it twice), the css gets loaded properly. Already tried solutions: 1. Setting in main url the following code: if settings.DEBUG: urlpatterns = urlpatterns + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) 2. Adding the below code snippet to settings.py import mimetypes mimetypes.add_type("text/css", ".css", True) The rest of loading of static files works just fine. Thanks in advance. -
'This field is required" - Django Rest Auth registration via fetch request
I'm trying to setup dj rest auth but I keep getting a 400 error stating that 'This field is required' in regards to the username, password1 and password 2 fields. Registration works fine if I do it directly/manually from http://127.0.0.1:5000/dj-rest-auth/register/ URLs urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('api.urls')), path('dj-rest-auth/register/', include('dj_rest_auth.registration.urls')), path('dj-rest-auth/login/', LoginView.as_view()), path('dj-rest-auth/logout/', LogoutView.as_view()) ] Fetch const registerUser = async (body) => { const response = await fetch('http://127.0.0.1:5000/dj-rest-auth/register/', postRequestOptions(body)) console.log(response) } postRequestOptions: export const postRequestOptions = (body) => { return { method: "POST", headers: { 'Content-Type': 'application/json', 'Accept': 'application/json', }, body: JSON.stringify({body}) } } I'm using React Hook Form so the data being passed is {"username":"test3","email":"test4@mail","password1":"tafasfss","password2":"tafasfss"} What am I missing here? -
how to submit html form data to django server and display output in real time using ajax
I need to be able to implement a form submit and display like this. My html form does not have a submit button, i'm using jquery to detect onchange event in each input fields then submit the form data. The goal is to have the output of the calculation updated in real time as the user types in the second form input field. Have done research however haven't found any article or similar implementation as this referenced in the link. Issues: My ajax code currently is able to submit form data, but it forces user to click somewhere else in the page in order for the form data to be submitted and output to display automatically.(Again not as expected behavior) The httpresponse from django view prints the raw output in a blank white html tab. The calculation is being handled by a python function back-end. How can i trick my code to have the same behavior as the one referenced in the link. my template and jquery ajax so far: {% extends "base.html" %} {% block title %}Two Way True Odd Finder{% endblock %} {% block content %} <script type="text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.js"></script> <script type="text/javascript"> $(document).ready(function () { $("#Odd1").on("change",function(){ if($("#Odd2").value … -
foreign key issue with my department model
I am getting the following error Cannot assign "u'167'": "Department.organization" must be a "Organization" instance. I have tried every way to send the Organization id but with no success. Request Method: POST Request URL: http://127.0.0.1:8081/profiles/api/createorganisation/ Django Version: 1.8.14 Exception Type: ValueError Exception Value: Cannot assign "u'167'": "Department.organization" must be a "Organization" instance. Exception Location: /usr/local/lib/python2.7/site-packages/django/db/models/fields/related.py in set, line 639 This is the model class Department(models.Model): """ Make department codes selectable and stuff """ organization = models.ForeignKey(Organization, related_name="departments") name = models.CharField(max_length=200) slug = models.SlugField(max_length=200, unique=True, editable=False) users = models.ManyToManyField("CustomUser", related_name="departments", blank=True) enter code here Serializer class class DepartmentCreateSerializer(serializers.ModelSerializer): organization = serializers.CharField() name = serializers.CharField() slug = serializers.CharField() class Meta: model = Department fields = ('pk','organization','name','slug') This is my code org = Organization.objects.get(slug="tata5").id department = { "organization":org, "name" : "finance1", "slug" : "finance1" , } logging.warning(department) instance = DepartmentCreateSerializer(data=department) instance.organization = org instance.is_valid(raise_exception=True) instance.save() # createDepartment.is_valid() # createDepartment.save() return Response(instance, status=status.HTTP_200_OK) -
Invalid literal int() with base 10: '[' when doing a filter with request.body
def patch(self, request): Claim.objects.filter(id__in=request.body, presented_to_client=False).update(presented_to_client=True, presented_to_client_date=datetime.datetime.now()) return HttpResponse(status=200) I'm trying to update some of my objects this way. But I get invalid literal for int() with base 10: '[' so I thought I might need to cast my request.body to list, and I tried it this way: def patch(self, request): Claim.objects.filter(id__in=list(request.body), presented_to_client=False).update(presented_to_client=True, presented_to_client_date=datetime.datetime.now()) return HttpResponse(status=200) and I still get the same error. Why is this happening? If I hardcode it this way: id__in=[8] I don't get any errors. Thanks. -
How to read radio button value and use it from FORM in view.py file
This is the code that's in the <fieldset class="form-group"> <div class="row"> <div class="col-sm-10"> <div class="form-check form-check-inline"> <input class="form-check-input" type="radio" name="transaction" id="deposit" value="deposit" checked="checked"> <label class="form-check-label" for="deposit"> Deposit </label> </div> <div class="form-check form-check-inline"> <input class="form-check-input" type="radio" name="transaction" id="deduction" value="deduction"> <label class="form-check-label" for="deduction"> Deduction </label> </div> </div> </div> </fieldset> I'm trying to take the 'transaction' and use it view.py and the calculations would be something like this in view.py: def form_valid(self, form): if (#deposit is checked): newFinanceTotal = currentUserTotal + value else: newFinanceTotal = currentUserTotal - value form.save() return super().form_valid(form) And this is what I have in models.py: class Finance(models.Model): FINANCE_CHOICES = ( ('DP', 'Deposit'), ('DD', 'Deduction'), ) transaction = models.CharField(max_length=2, choices=FINANCE_CHOICES,)transaction = models.CharField(max_length=2, choices=FINANCE_CHOICES,) forms.py: class FinanceForm(forms.ModelForm): class Meta: model = Finance fields = ('entryName', 'entryDate', 'transaction', 'value') -
Object's ManyToMany relationship is not updated inside signals
I have this singal @receiver(post_save, sender=Organization) def save_tags(sender, instance, **kwargs): from .views import post text_input_tags = post.getlist('tags1')[0] text_input_tags = text_input_tags.strip() text_inputs_tags = text_input_tags.split(' ') for tag in text_inputs_tags: if not tag.startswith('#') : tag = '#' + tag tag_obj = Tag.objects.get_or_create(name = tag)[0]#.organization_set.set([obj,]) tag_obj.save() instance.tags.add(tag_obj) print(instance.tags.all()) from the views I am importing the post data to use inside the signal. There is a manytomany relationship between two models Organization and Tag. I am trying to get some attributes from the post request and create a Tag object from them, then after that add that Tag object into the ManyToMany relationship of the instance of the Organization. when I print the tags of the organization instance print(instance.tags.all()) I get the added instances in the QuerySet, but it's not saved in the organization instance and I don't understand why... -
Query in sqlite using django [duplicate]
I want to access data from table1, from my database and to make a query based on other table, using django. For example: access data from table1 (date, hour:minutes, city, check) and table 2 (date: hour:minute, latitude, longitudinal) and if the hour:minutes are the same in both table, I need to update the field check with the value True. I tried to access the data from table1 with objects.filter, but I think that it's not a good method, because it doesn't give me the values from the row. I read the documentation from https://docs.djangoproject.com/en/4.0/topics/db/queries/#copying-model-instances but I can not manage to do this correctly and finish it -
Django authenticate() command returns None
I am creating a user in django and i'm trying to log them in also. For some reason the authenticate() command returns None. I am using a custom user model. I am passing email and password paramaters to the authenticate() command (I have replaced username for email) and they both have values as I have checked this. Could I have any suggestions? Here is the code: views.py email = request.POST.get("email") password = request.POST.get("password") account_id = ''.join(random.choices(string.ascii_uppercase + string.ascii_lowercase + string.digits, k=500)) CustomUser.objects.create(email=email,password=password,account_id=account_id) if user is not None: login(request, user) else: # Stuff models.py from django.contrib.auth.models import AbstractUser, BaseUserManager from django.db import models from django.utils.translation import gettext_lazy as _ class UserManager(BaseUserManager): def _create_user(self, email, password, **kwargs): if not email: raise ValueError("Email is required") email = self.normalize_email(email) user = self.model(email=email, **kwargs) user.set_password(password) user.save() return user def create_user(self, email, password=None, **extra_fields): """Create and save a regular User with the given email and password.""" extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **kwargs): kwargs.setdefault('is_staff', True) kwargs.setdefault('is_superuser', True) kwargs.setdefault('is_active', True) if kwargs.get('is_staff') is not True: raise ValueError("Superuser must have is_staff True") if kwargs.get('is_superuser') is not True: raise ValueError("Superuser must have is_superuser True") return self._create_user(email, password, **kwargs) class CustomUser(AbstractUser): username = None … -
How to run asynchronous function synchronously in python
I am learning Django and I am stuck with this problem. So basically, I have written two run functions and the second run function uses the first's output as input. Now it seems that the run function runs asynchronously so before the first run function executes completely and produces its output the second run function starts executing and since it needs the first run function output as input it does not produce any output. So, I want the run function to run synchronously. 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/") In the above code I have used a for loop and it works but I don't think it's the correct way. Can someone please suggest me the correct way? Here is my views.py file. def video(request): if request.method == 'POST': uploaded_video_file = request.FILES["video"] video_file_name = uploaded_video_file.name fs = FileSystemStorage() video_name = fs.save(video_file_name, uploaded_video_file) run(["gnome-terminal", "--", "sh", "-c", f"ffmpeg -i {video_name} -c:v copy -an {video_name}_audio_stripped.mp4"], cwd="media/") final_tutorial=video_name+"_spoken_tutorial.mp4" run(["gnome-terminal", "--", "sh", "-c", f"ffmpeg -i {video_name}_audio_stripped.mp4 -i {audio_name} -c:v copy -c:a aac … -
How to get data from a django model and show it into a bootstrap modal popup?
i'm new in django framework, in my app i have two model, BoardsList and BoardLink: class BoardsList(models.Model): master_code = models.CharField(max_length=6, primary_key=True) uc_code = models.CharField(max_length=20) description = models.CharField(max_length=200) customer_name = models.CharField(max_length=30) def __str__(self): return "MASTER_CODE = " + self.master_code class BoardLink(models.Model): boardsList = models.ForeignKey(BoardsList, on_delete=models.CASCADE) configuration_sheet_link = models.CharField(max_length=300) wiring_diagram_link = models.CharField(max_length=300) def __str__(self): return self.boardsList_id And the relative views are : class BoardsListView(generic.ListView): template_name = 'index.html' context_object_name = 'boards_list' paginate_by = 75 def get_queryset(self): query_filter = self.request.GET.get("find_master", None) if query_filter is not None: return BoardsList.objects.filter(Q(master_code__contains=query_filter) | Q(uc_code__contains=query_filter) | Q(customer_name__contains=query_filter)).order_by('customer_name') return BoardsList.objects.order_by('master_code') class BoardLinkView(generic.DetailView): template_name = 'index.html' context_object_name = 'board_link_list' paginate_by = 1 def get_queryset(self): query_filter = self.request.GET.get("find_master_link", None) if query_filter is not None: return BoardLink.objects.filter(Q(boardsList__exact=query_filter)) in my html page i correctly showed boardlist data into a table : <tbody> {% for board in boards_list %} <tr> <td>{{ board.master_code }}</td> <td>{{ board.uc_code }}</td> <td>{{ board.description }}</td> <td>{{ board.customer_name }}</td> <td> <form method="GET" action=""> <button type="button" class="btn" name="find_master_link" data-bs-toggle="modal" data-bs-target="#boardLinksModal"> <i class="fa-solid fa-file-lines"></i> </button> </form> </td> </tr> {% endfor %} </tbody> now my problem is how i can get BoardLink model data record on button click event and show it on bootstrap modal popup that i have already created and include it on … -
Run a separate task in django rest framework
I've to perform two tasks in an API request but I want to run the second task asynchronously in the background so the API doesn't have to wait for the second task and return the response after the completion of the first task, so how can I achieve it? @api_view(['POST']) def create_project(request): data = first_task() second_task(data) # want to run this function at background return Response("Created") # want to return this response after completion of first_task() -
'social' is not a registered namespace
Im trying to implement google authentication but I got the following error: django.urls.exceptions.NoReverseMatch: 'social' is not a registered namespace i have like this in my login.html: <a href="{% url 'social:begin' 'google-oauth2' %}"> Sign in with Google</a> I also added this in my setting.py SOCIAL_AUTH_URL_NAMESPACE = 'social' Does anyone know how to solve this? -
problems trying to migrate from django to postgrsql
when trying to migrate from django to postgresql I get this error: C:\Users\Al2Misael\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\commands\makemigrations.py:121: RuntimeWarning: Got an error checking a consistent migration history performed for database connection 'default': warnings.warn( could you help me, please,I'm new working with databases and django,I'm trying to make a web site for our animal rescue club.thanks in advance -
Django create post with reverse relation foreign key
I have a Protein model that is linked to the Domain model through the proteins foreign key in the Domain model like below. 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 And I have a Protein serializer that displays the Queryset like so: domains = DomainSerializer(many=True) taxonomy = OrganismSerializer() class Meta: model = Protein fields = [ 'protein_id', 'sequence', 'taxonomy', 'length', 'domains', ] The problem comes when I have to create a new record of the Protein using the Protein serializer. I write a post API function to create a new record but it gives errors when attempting to create the foreign key fields. @api_view(['POST']) def protein(request): if request.method == 'POST': serializer = ProteinSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) I added the following function to my Protein serializer to override the create function for the two foreign keys but it doesn't seem to work when attempting to … -
UnboundLocalError at / local variable 'email' referenced before assignment django error
I am getting local variable referenced before assignment django error. Here is views.py from django.shortcuts import render from verify_email import verify_email def valid_email_verifier(email): email_vrifier_task = verify_email(email) results = {} if email_vrifier_task == False: results['email_altert'] = 'Wrong Email' else: results['email_altert'] = 'This email is correct!' return results # Create your views here. def home_view(request): if request.method == "POST" and 'email' in request.POST: email = request.POST.get(email) results = valid_email_verifier(email) context = {'results':results} else: context = {} return render(request, 'home.html', context) my form on templates file <form action="" method="post"> {% csrf_token %} <input class="form-control m-3 w-50 mx-auto" type="text" name="email" id="email" placeholder="Enter email...."> <input class="btn btn-secondary btn-lg my-3" type="submit" value="submit"> </form> </div> {% if results %} Email Info {{results.email_altert}} {% endif %} Please, anyone, help me where I did wrong? Thanks is advance. -
How to declare in Django Models a class with an attribute pointing to the same class?
How can I declare the previous or next attributes pointing to the same class type ? I couln't find the answer in official documentation In the models.py below I have just written "scenes" for previous and next from pickle import TRUE from django.db import models from django.contrib.auth.models import User class scenes(models.Model): name = models.CharField('Event name', max_length=120) record_date = models.DateTimeField('Event date') manager = models.ForeignKey(User, blank=True, null=True, on_delete=models.SET_NULL) description = models.TextField(blank=True) previous = models.ForeignKey(scenes, blank=True, null=True, on_delete=models.SET_NULL) next = models.ForeignKey(scenes, blank=True, null=True, on_delete=models.SET_NULL) def __str__(self): return self.name -
unsupported operand type(s) 'Decimal128' and 'decimal.Decimal' | (django)
I started a project in Django and just switched the local SQLite Database to mongodb Now that I'm trying to test the functionality of the site, I'm getting misunderstood errors. for example when I want to view all my data regarding a particular course and I send all the data back to HTML I get an error: unsupported operand type(s) for /: 'Decimal128' and 'decimal.Decimal' i am using star-rating django so i also have this package in my html files see down how i load the rating obj. Terminal Errors: Traceback (most recent call last): File "/Users/a2019/opt/miniconda3/envs/EstudyEnv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/Users/a2019/opt/miniconda3/envs/EstudyEnv/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/a2019/opt/miniconda3/envs/EstudyEnv/lib/python3.9/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "/Users/a2019/opt/miniconda3/envs/EstudyEnv/lib/python3.9/site-packages/django/views/generic/base.py", line 98, in dispatch return handler(request, *args, **kwargs) File "/Users/a2019/Documents/GitHub/TEAM_15_ESTUDY/Estudy_Project/category/views.py", line 54, in get return render(request,"HomeWorks.html",{'course':course,'homeworks':homeworks}) File "/Users/a2019/opt/miniconda3/envs/EstudyEnv/lib/python3.9/site-packages/django/shortcuts.py", line 19, in render content = loader.render_to_string(template_name, context, request, using=using) File "/Users/a2019/opt/miniconda3/envs/EstudyEnv/lib/python3.9/site-packages/django/template/loader.py", line 62, in render_to_string return template.render(context, request) File "/Users/a2019/opt/miniconda3/envs/EstudyEnv/lib/python3.9/site-packages/django/template/backends/django.py", line 61, in render return self.template.render(context) File "/Users/a2019/opt/miniconda3/envs/EstudyEnv/lib/python3.9/site-packages/django/template/base.py", line 170, in render return self._render(context) File "/Users/a2019/opt/miniconda3/envs/EstudyEnv/lib/python3.9/site-packages/django/template/base.py", line 162, in _render return self.nodelist.render(context) File "/Users/a2019/opt/miniconda3/envs/EstudyEnv/lib/python3.9/site-packages/django/template/base.py", line 938, in render bit = node.render_annotated(context) File "/Users/a2019/opt/miniconda3/envs/EstudyEnv/lib/python3.9/site-packages/django/template/base.py", line … -
why Django use int auto primary key instead of other fields?
I'm developing a rest API service that use DRF in back-end,my question is can I user username of user as PK instead of Django auto field default ID?why Django uses this method what are the benefits? -
django.template.exceptions.TemplateSyntaxError: Could not parse the remainder
I am trying to display the image in html template in python Django project. passed list of object as downloadData <div class="col-sm-6"> {% for d in downloadData %} <div class="row content"> <div class="col-sm-3"> <!--<img src="{{ 'static/assets/images/about-us.jpg' }}" >--> <img src="{{ url_for('static', filename='assets/images/' + d.img1) }}" > </div> <div class="col-sm-9"> <h3>{{ d.title }} </h3> <p>{{ d.p1 }}</p> </div> </div> <br> {% endfor %} </div> Error : django.template.exceptions.TemplateSyntaxError: Could not parse the remainder: '('static', filename='assets/images/' + d.img1)' from 'url_for('static', filename='assets/images/' + d.img1)' Images present in XYZProject-> static-> assets-> images-> about-us.jpg Could anyone point out the what I am doing wrong? Any link or pointer would be helpful -
ERROR: Service 'web' failed to build: The command '/bin/sh -c pip install -r requirements.txt' returned a non-zero code: 1 when dockerize a django app
Building wheel for backports.zoneinfo (pyproject.toml) did not run successfully. lib/zoneinfo_module.c: In function ‘zoneinfo_fromutc’: lib/zoneinfo_module.c:600:19: error: ‘_PyLong_One’ undeclared (first use in this function); did you mean ‘_PyLong_New’? 600 | one = _PyLong_One; | ^~~~~~~~~~~ | _PyLong_New lib/zoneinfo_module.c:600:19: note: each undeclared identifier is reported only once for each function it appears in error: command '/usr/bin/gcc' failed with exit code 1 [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. ERROR: Failed building wheel for backports.zoneinfo Failed to build backports.zoneinfo ERROR: Could not build wheels for backports.zoneinfo, which is required to install pyproject.toml-based projects ERROR: Service 'web' failed to build: The command '/bin/sh -c pip install -r requirements.txt' returned a non-zero code: 1 please need help to solve this and why this error happened, I have no idea. Thanks -
how to run django project with gunicorn
I have uploaded my Django app on the RHEL7 server it's running with help of gunicorn but not with full width so how do I customize it to use with full width. gunicorn_config.py command='/home/tarun/env/bin/gunicorn' pythonpath='/home/tarun/' bind='10.88.32.40:8000' workers =11 to run this project i use this command gunicorn -c conf/gunicorn_config.py ecom.wsgi -
How do I change the text color of a default UserCreationForm in Django?
I'm working on a simple website using django and bootstrap. I've used the UserCreationForm class to make a standards registration page. But I'd like to make the texts a little darker so it's more legible and has a good contrast from the background image and mask. What'd be the best solution? View module def register(request): #if the request method is a 'get' #Yes initial data if request.method != 'POST': form = UserCreationForm() #no initial data #f the request method is a 'post' else: form = UserCreationForm(data=request.POST) if form.is_valid(): new_user=form.save() authenticated_user = authenticate(username=new_user.username, password=request.POST['password1']) login(request, aunthenticated_user) return HttpResponseRedirect(reverse('my_websites:home')) context = {'form': form} return render(request, 'users/register.html', context) bootstrap {% extends "pages/base.html" %} {% load bootstrap5 %} {% block header %} <div="container my-5"> <div class="bg-image position-relative rounded" style="background:url('https://wallpaperaccess.com/full/1708426.jpg') no-repeat center center fixed; -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; background-size: cover; height: 100vh;"> <div class="mask position-absolute rounded p-4 top-0 end-0 bottom-0 start-0" style="background-color: rgba(251, 251, 251, 0.8);"> <h2 class="text-center display-6"> Register </h2> <form method="post" action="{% url 'users:register' %}" class="form text-dark" style="max-width: 400px; margin:0 auto;"> {% csrf_token %} {% bootstrap_form form %} {% buttons %} <button name="submit" class="btn btn-dark">Register </button> {% endbuttons %} <input type="hidden" name="next" value="{% url 'my_websites:home' %}" /> </form> </div> </div> </div> … -
How can i omit a url so i reach the url i want
hi i have a Form an the action method is 'Home_Search' i want to reach the Home_Search view but when ever i Post something the url will be like this http://127.0.0.1:8000/home/Home_Search and Page not found error will be raised , is there any method so i can exclude /home from the url?Only for this Form... my url.Py : path("home/", views.home, name="home"), path("Home_Search/", views.Home_Search, name="Home_Search"), and my Form is : <form action="Home_Search" method="post" role="form"> -
Function Based View to Class Based View
How would I convert my Function Based View into Class Based View. urls.py urlpatterns = [ path('', views.SlideShowView, name="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/", blank=True) def __str__(self): return self.title views.py def SlideShowView(request): carousel = Carousel.objects.all() context = { 'carousel' : carousel, } return render(request, "showcase.html", context)