Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Wagtail 'expected string or bytes-like object' error
I've been having some trouble figuring out what exactly is causing this error in my code. My main pages render but when I try to open a child page I get the expected string error. Any help debugging this greatly appreciated. Traceback Below: Internal Server Error: /resonate/page-2/ Traceback (most recent call last): File "/Users/saeahmad/.pyenv/versions/auxe_cms/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Users/saeahmad/.pyenv/versions/auxe_cms/lib/python3.6/site-packages/django/core/handlers/base.py", line 156, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/saeahmad/.pyenv/versions/auxe_cms/lib/python3.6/site-packages/django/core/handlers/base.py", line 154, in _get_response response = response.render() File "/Users/saeahmad/.pyenv/versions/auxe_cms/lib/python3.6/site-packages/django/template/response.py", line 106, in render self.content = self.rendered_content File "/Users/saeahmad/.pyenv/versions/auxe_cms/lib/python3.6/site-packages/django/template/response.py", line 83, in rendered_content content = template.render(context, self._request) File "/Users/saeahmad/.pyenv/versions/auxe_cms/lib/python3.6/site-packages/django/template/backends/django.py", line 61, in render return self.template.render(context) File "/Users/saeahmad/.pyenv/versions/auxe_cms/lib/python3.6/site-packages/django/template/base.py", line 171, in render return self._render(context) File "/Users/saeahmad/.pyenv/versions/auxe_cms/lib/python3.6/site-packages/django/template/base.py", line 163, in _render return self.nodelist.render(context) File "/Users/saeahmad/.pyenv/versions/auxe_cms/lib/python3.6/site-packages/django/template/base.py", line 937, in render bit = node.render_annotated(context) File "/Users/saeahmad/.pyenv/versions/auxe_cms/lib/python3.6/site-packages/django/template/base.py", line 904, in render_annotated return self.render(context) File "/Users/saeahmad/.pyenv/versions/auxe_cms/lib/python3.6/site-packages/django/template/loader_tags.py", line 150, in render return compiled_parent._render(context) File "/Users/saeahmad/.pyenv/versions/auxe_cms/lib/python3.6/site-packages/django/template/base.py", line 163, in _render return self.nodelist.render(context) File "/Users/saeahmad/.pyenv/versions/auxe_cms/lib/python3.6/site-packages/django/template/base.py", line 937, in render bit = node.render_annotated(context) File "/Users/saeahmad/.pyenv/versions/auxe_cms/lib/python3.6/site-packages/django/template/base.py", line 904, in render_annotated return self.render(context) File "/Users/saeahmad/.pyenv/versions/auxe_cms/lib/python3.6/site-packages/django/template/loader_tags.py", line 62, in render result = block.nodelist.render(context) File "/Users/saeahmad/.pyenv/versions/auxe_cms/lib/python3.6/site-packages/django/template/base.py", line 937, in render bit = node.render_annotated(context) File "/Users/saeahmad/.pyenv/versions/auxe_cms/lib/python3.6/site-packages/django/template/base.py", line 904, in render_annotated return self.render(context) File … -
Why language is not changing with set_language url in Django?
I added django-user-language-middleware package but it only change language when I manually change it at admin or DB. When I use set_language link, it doesn't update language. Before adding that middleware, it was working without any problem but I need to save language for user. The middleware order: MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'user_language_middleware.UserLanguageMiddleware', ... } -
How do I save the video recorded on web browser to smartphone (Android) internal storage?
I managed to stream the video from camera in a smartphone to the web app in the code below. However, I do not know how to save the video to the internal storage of the smartphone from the web app. How can I achieve this? The following is my working code so far. Thank you for any kind assistance. base.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content="{% block metadescription %}{% endblock %}"> <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet"> <title>{% block title %}{% endblock %}</title> </head> <body> <div class="container-fullwidth"> <div class="container-fluid bg-light navbar-fixed-top"> </div> {% block content %} {% endblock %} </div> <script async src="https://www.googletagmanager.com/gtag/js?id=UA-33848682-1"></script> <script> window.dataLayer = window.dataLayer || []; function gtag() { window.dataLayer.push(arguments); } gtag('js', new Date()); gtag('config', 'UA-33848682-1'); </script> <script> 'use strict'; var videoElement = document.querySelector('video'); var audioSelect = document.querySelector('select#audioSource'); var videoSelect = document.querySelector('select#videoSource'); navigator.mediaDevices.enumerateDevices() .then(gotDevices).then(getStream).catch(handleError); audioSelect.onchange = getStream; videoSelect.onchange = getStream; function gotDevices(deviceInfos) { for (var i = 0; i !== deviceInfos.length; ++i) { var deviceInfo = deviceInfos[i]; var option = document.createElement('option'); option.value = deviceInfo.deviceId; if (deviceInfo.kind === 'audioinput') { option.text = deviceInfo.label || 'microphone ' + (audioSelect.length + 1); audioSelect.appendChild(option); } else if (deviceInfo.kind === 'videoinput') { … -
not able to upload image in app static folder
i have a app named website and in this i have a static folder and inside it i have website folder and then i have uploaded_image folder and i want to upload my images in this folder through admin panel. this is my model class About(models.Model): displayname=models.CharField(max_length=50) email=models.EmailField(max_length=70) website=models.CharField(max_length=200) photo=models.FileField(upload_to='website/static/uploaded_image') des=models.TextField() def __str__(self): return self.displayname -
Html for loop add another condition
I want to fetch the data in html template by for loop. Here's what my code is. {% for entry in topic.entries.all %} <li> <a style="line-height:170%", href="{% url 'xx' entry.id %}">{{ entry.text }}</a> </li> {% endfor %} And I need to add one additional condition to identify if the Entry Model field 'delete' = '1'. I try {% for entry in topic.entries.all().value_list(delete = '1') %}, but id did not work. How could I achieve that? Here's the Model.py. class Topic(models.Model): text = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey(User, on_delete=models.CASCADE) delete = models.IntegerField(default=1) def _str_(self): return self.text class Entry(models.Model): topic = models.ForeignKey(Topic, on_delete=models.CASCADE, related_name="entries") text = models.TextField() date_added = models.DateTimeField(auto_now_add=True) delete = models.IntegerField(default=1) class Meta: verbose_name_plural = 'entries' def _str_(self): return self.text[:50] + "..." #on_delete=models.CASCADE, -
Django Web/Dev On same Unix Server
I'm looking at a couple of MVC/MVT frameworks for a new server I'm getting at work (Unix, not sure of the flavor yet). I'm heavily leaning towards Django as well as Laravel. What I'm having trouble figuring out right now, is how Django would be setup, or would work, if I need a separation between web and dev environments. I'm only getting one server for this. The other problem I'm trying to figure out is the difficulty in only having 1 database (going with PostgreSQL). I mean when you're using migrations, how difficult is it to control the db names being different (db names like "test_prod_v1" and "test_dev_v1"). How to only have two sub-folders in the htdocs: web and dev, and how hard is it to deal with a setup like that? With migrations (etc) how to deal with needing a Web and Dev version of each database? I need to make a decision next week so I'm just looking for some advice or keyword/concepts to read up on over the weekend (weekend reading pointers). Thanks for any help or advice. In setting up a new web server, this is my biggest problem by far in making a framework decision. -
Need to quickly update Django model with difference between two other models
I'm populating my database from an API that provides year-to-date stats, and I'll be pulling from this API multiple times a day. Using the year-to-date stats, I need to generate monthly and weekly stats. I'm currently trying to do this by subtracting the stats at the start of the month from the stats at the end of the month and saving it in a separate model, but the process is taking far too long and I need it to go faster. My models look something like this : class Stats(models.Model): date = models.DateField(default=timezone.now) # Date pulled from API customer_id = models.IntegerField(default=0) # Simplified for this example a = models.IntegerField(default=0) b = models.IntegerField(default=0) c = models.IntegerField(default=0) d = models.IntegerField(default=0) class Leaderboard(models.Model): duration = models.CharField(max_length=7, default="YEARLY") # "MONTHLY", "WEEKLY" customer_id = models.IntegerField(default=0) start_stats = models.ForeignKey(Stats, related_name="start_stats") # Stats from the start of the Year/Month/Week end_stats = models.ForeignKey(Stats, related_name="end_stats") # Stats from the end of the Year/Month/Week needs_update = models.BooleanField(default=False) # set to True only if the end_stats changed (likely when a new pull happened) a = models.IntegerField(default=0) b = models.IntegerField(default=0) c = models.IntegerField(default=0) d = models.IntegerField(default=0) e = models.IntegerField(default=0) # A value computed based on a-d, used to sort Leaderboards I thought … -
Error: Django-Social-Auth LinkedIn Client Error
After authentication I got this error message HTTPError at /oauth/complete/linkedin-oauth2/ 410 Client Error: Gone for url: https://api.linkedin.com/v1/people/~:(email-address,first-name,headline,id,industry,last-name)?format=json Django settings conf SOCIAL_AUTH_LINKEDIN_OAUTH2_SCOPE = [ 'r_emailaddress', 'r_liteprofile' ] SOCIAL_AUTH_LINKEDIN_OAUTH2_FIELD_SELECTORS = [ 'email-address', 'headline', 'industry',] ====================================== Django package versions: social-auth-app-django==3.1.0 social-auth-core==2.0.0 Django==2.1 -
Django - adding contact form to footer
I am trying to create a contact form that can be used on all pages of my app. My function contact_form(request) in context_processors.py successfully shows the contact form in all templates that my base template extends to, but the problem is that I can't submit the information and run POST requests with it. After extensive research, it seems like the only clean way to do this would be to have context_processors.py perform the GET request and have a custom template tag handle the POST request. Taking this approach, I can't find a way to process this in the template tag. I have tried several different ways and have gotten several different errors. I have also looked at many of the posts out there to get to this point, including Contactform in footer of page, and there doesn't seem to be any answers that show how this is formatted in the template. settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ ... 'services.context_processors.contact_form', ], }, }, ] context_processors.py from .forms import ContactForm def contact_form(request): if request.method == 'GET': contact_form = ContactForm() return {'contact_form': contact_form} return tags.py @register.inclusion_tag('services/headerfooter.html', takes_context=True) def post_request(context): request = context['request'] if request.method … -
Rest_Pandas and Rest_Framework usage [rest_pandas.html does not exist]
I am working on a webapp with data tracking/visualization in Django. I have a Rest_Framework API configured so far and I'm trying to couple it with Rest_Pandas to create data visualization that visualizes hours submitted by users on one part of the website for managers on another. I have set up my views correct to the Rest_Pandas usage guide: # Organization Hours View class HoursOverviewView(PandasView): queryset = HoursEntry.objects.all() serializer_class = HoursEntrySerializer Along with my url: urlpatterns = [ path('overview/', views.HoursOverviewView.as_view()), ] And my serializer: class HoursEntrySerializer(serializers.ModelSerializer): class Meta: model = HoursEntry fields = ('id', 'user', 'hours_date', 'hours_category', 'hours_amt', 'notes') But, I seem to be getting an error stating: TemplateDoesNotExist at /staff/overview/: rest_pandas.html I'm still new to Django development, API's and third-party packages, so I'm not sure if I'm misunderstanding the purpose of API's, Rest_Pandas, how they interact, or all three. My goal is to create data visualization for the HoursEntry model and this seemed like the most simple approach, but I can't seem to figure it out. -
Oddly unable to reach the media folder in django
I'm tinkering with an image gallery, but I can't seem to make contact with my media folder when upload time comes, and I was hoping someone might point me in the right direction. In settings.py I have: MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' In my main urls.py I have: urlpatterns = [ ... ] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) and finally in models.py I have: class Gallery(models.Model): class Meta: verbose_name = 'gallery' verbose_name_plural = 'galleries' owner = models.ForeignKey(Profile, on_delete=models.CASCADE) extra_img = models.ImageField(default='default.jpg', upload_to='images') def __str__(self): return self.owner.user.username def save(self, force_insert=False, force_update=False, using=None): super().save() #print(settings.MEDIA_URL + 'images/thumbs_color') #print(settings.MEDIA_ROOT) img = Image.open(self.extra_img.path) xpad = int(img.width/2)-45 ypad = int(img.height/2)-45 coords = (xpad, ypad, xpad+90, ypad+90) color_url = settings.MEDIA_URL + 'images/thumbs_color/' bw_url = settings.MEDIA_URL + 'images/thumbs_bw/' crop_img_color = img.crop(coords) crop_img_color.save(color_url) crop_img_bw = ImageOps.grayscale(crop_img_color) crop_img_bw.save(bw_url) With the idea of creating two thumbnails from the original image, one in color (hover state) and one in b/w (normal state), I find myself struggling with something that I think ought to be a straight shot. Rather confusing indeed; knowing me and my beginner ways, it's most likely something simple I've overlooked. As I had expected the two print statements give me: /media/images/thumbs_color/ C:/Users/vulpes/Desktop/velox/media However, … -
Django admin ImageField: Upload a valid image. The file you uploaded was either not an image or a corrupted image
ERROR: "Upload a valid image. The file you uploaded was either not an image or a corrupted image." I have been looking around and I haven't been able to find a solution to my problem. I use the same images locally in a venv and they work. I use the same images in a docker container that has the same Pillow library and dependancies and it works. I have a Django ImageField that I have a simple admin form. I can get the images to upload to S3 for storage. I have pulled the docker container we use on the servers and I have ran this locally, but is cannot get the error. I have not run into this error before with image uploading, so I am unsure why this is happening. # models.py @deconstructible class RandomFileName(object): def __init__(self, path): self.path = path def __call__(self, instance, filename): ext = filename.split('.')[-1] filename = '{}.{}'.format(uuid.uuid4().hex, ext) return os.path.join(self.path, filename) class MyModel(models.Model): name = models.CharField(max_length=50) avatar = ImageField( upload_to=RandomFileName('avatars') ) ... # admin.py @admin.register(MyModel) class MyModelAdmin(admin.ModelAdmin): list_display = ( 'name', ... ) fieldsets = ( (None, {'fields': ( 'name', 'avatar', )}), ) ... Dependancies: Django==2.0.3 Pillow==5.3.0 -
Run the most basic of tests in python/django
I have created a selenium client to create unit tests against the actual staging website (and its database) without doing everything locally. In other words, I don't think I necessarily need all of django's testing framework and such. Here is the "test function" I want to run: def run_time() s = SeleniumClient() s.login() assert "my-data" in self.user1.current_url It works, and I can run it from the command line. How would I run this test, and how would I properly call it so that it runs as a unit test? -
Django select random value of one column with distinct value on another
I have a table tab(id, pid) where id is the primary keys. Example of values id pid 1 23 2 23 3 5 4 7 5 7 I want to select a random id for each distinct pid. Here is the working mysql query: SELECT a.pid, (SELECT b.id FROM tab AS b WHERE a.pid=b.pid ORDER BY rand() LIMIT 1) AS id FROM tab AS r GROUP BY r.pid order by r.pid; How do I write this query in django syntax? -
How to make a redirect view jump to a section in django
so I have a section in my templates: <div id='comments'>Comments go here</div> now I want my django redirect function to redirect to this page and jump to this div id. return redirect('post_detail', post.slug) Where do I put in '/#comments' to make it jump there on redirecting -
How to install Django on Python 3?
My OS is Ubuntu 18.04 if that helps. I tried installing using pip. It keeps saying it's successful but this is the result: Requirement already satisfied: django in /usr/local/lib/python2.7/dist-packages (1.11.17) Requirement already satisfied: pytz in /usr/local/lib/python2.7/dist-packages (from django) (2014.10) Now, I tried upgrading it and it still shows the same error. I tried using pip3. It's successful but when I try to import it on python 3.0, it shows this error: ModuleNotFoundError: No module named 'django' I also tried installing using virtualenv. It still doesn't work. If it helps, this is the error which shows when I try installing using pip3: Requirement already satisfied: django in ./pgadmin4/lib/python3.6/site-packages (2.1.4) Requirement already satisfied: pytz in ./pgadmin4/lib/python3.6/site-packages (from django) (2018.3) -
How to serve subdirectory as root in nginx using django?
When a user visits www.website.com I would like to server content as if the user went to www.website.com/frontend/. However, I want to mask the /frontend/ part of the url so the user doesn't see it. Can this be done? What would my rewrite rule look like? -
How to create a user/password for a selenium test case in django
I am trying to write some selenium test cases using Django (or python's) unit testing frameworks. What I have below is for a login, but I have previously created the user: from selenium import webdriver from django.conf import settings class SeleniumClient(object): def __init__(self, driver="Chrome", url=BASE_URL): if driver == 'Chrome': self.driver = webdriver.Chrome(CHROMEDRIVER) self.url = url def _get_url_from_path(self, path): return self.url.rstrip('/') + '/' + path.lstrip('/') def login(self): url = self._get_url_from_path("/login") self.driver.get(url) email_field = self.driver.find_element_by_id('email').send_keys(TEST_USERNAME) password_field = self.driver.find_element_by_id('password').send_keys(TEST_PASSWORD) self.driver.find_element_by_id('loginButton').submit() Is there a way to "generate" the user on the test and destroy it when it's done? If so, how would I do that? -
Xlsxwriter cant find file for close() in Django Project
I am attempting to write a class to create an excel sheet using my Django Models. I have created the following class: class workBook(object): def __init__(self, title, data): path = '\\workbooks\\' + title + '.xlsx' print(os.path.normpath(path)) self.workbook = xlsxwriter.Workbook(os.path.normpath(path)) newWorkSheet(self.workbook, data) self.workbook.close() The method creates the workbook with the proper path but when I close it I get the following error: [Errno 2] No such file or directory: '\\workbooks\\Test.xlsx' I know this is because of the double "\" but I dont know how to send the correct path to the close method. I also know the rest of my class works because it does not throw this error when I simply put the file name and not a full directory. Thank you! -
Editing a topic and its sub entries at the same time
I want to edit an entry and it's child at the same time. So I have a Price model which has Entry (another model) as it's foreign key. ` class Price(models.Model): price = models.ForeignKey(Entry, on_delete = models.CASCADE) ptext = models.FloatField(blank = True, null = True) date_added = models.DateTimeField(auto_now_add = True) class Meta: verbose_name_plural = 'prices' def __str__(self): return self.ptext[:50] + "..." ` How would I pull the price from the entry model? I can only modify data inside the entry model, but not the price model. The instance part is giving a problem in particular. I don't know what to put for the PriceForm instance. def edit_entry(request, entry_id): entry = Entry.objects.get(id = entry_id) price = entry.price_set.get.all() topic = entry.topic check_topic_owner(topic.owner, request.user) if request.method != 'POST': form = EntryForm(instance = entry) form2 = PriceForm(instance = price) else: form = EntryForm(instance=entry, data = request.POST) form2 = PriceForm(instance=price, data = request.POST) if form.is_valid() and form2.is_valid(): form.save() form2.save() return HttpResponseRedirect(reverse('learning_logs:topics')) context = {'entry': entry, 'topic': topic, 'form': form, 'form2':form2} return render(request, 'learning_logs/edit_entry.html', context) -
Django - getting data from url in register view
Im trying to grab data from the url /register/?ref=123456 but having some trouble with it. User registration is tied to one of my views: class UserRegisterView(FormView): form_class = UserRegisterForm template_name = 'accounts/user_register_form.html' success_url = '/accounts/login' def form_valid(self, form): username = form.cleaned_data.get('username') email = form.cleaned_data.get('email') password = form.cleaned_data.get('password') new_user = User.objects.create(username=username, email=email) new_user.set_password(password) new_user.save() ref = self.request.GET.get('ref', 'None') print(ref) return super(UserRegisterView, self).form_valid(form) I'm trying to use "self.request.GET.get('ref', 'None')" to grab the data, but each time a user registers ref returns "None" rather than 123456 Here is the user_register_form.html: <div class='row'> <div class='col-sm-4 offset-sm-4 mt-3'> <h1 class='text-center mt-3'>Sign Up</h1> <form {% if form_id %} id='{{ form_id }}' {% endif %} class='form mt-3' method='POST' action=''> {% csrf_token %} {{ form|crispy }} <input class='btn btn-primary-new' id="submit" type="submit" value="Sign Up" /> </form> </div> </div> -
django adding a background image to admin site
I need to display a background image in the django admin site. I have looked to all questions but none of the solutions seems to work for me. I just want the background to appear in the back of the admin site. I have a base_site.html {% extends "admin/base_site.html" %} {% load static %} {% block extrastyle %} {{ block.super }} <link rel="stylesheet" type="text/css" href="{% static "css/admin-extra.css" %}" /> {%endblock%} The extra-admin.css head.bg { /* The image used */ background-image: url('{{ STATIC_URL }} background.png') ; /* Full height */ height: 100%; /* Center and scale the image nicely */ background-position: center; background-repeat: no-repeat; background-size: cover; } This extra-admin.css is loaded as I see it in the firfox inspector. However the image does not appear. something seems to appear in the background but is immediately covered by the normal admin site with white background. -
Is ASKBOT project still alive?
It seems that askbot.com hasn't been updated since 2016, docs at askbot.org/doc are properly 404, the latest release on the GitHUB has been released on 2015-04-22, and in the askbot_requirements.txt I found django>=1.8,<1.9... At the time of this writing the latest official version of django is v2.1.4, so AskBot is quite a bit behind. Despite all the negative, git log kind of reveals that it's still an active project: $ git log -100 --date=iso | grep Date: | sort -ruk2,2 Date: 2018-10-28 16:26:23 -0300 Date: 2018-10-15 21:34:30 -0300 Date: 2018-10-14 17:09:29 -0300 Date: 2018-10-13 16:14:25 -0300 Date: 2018-09-23 20:06:21 -0300 Date: 2018-09-22 19:53:15 -0300 Date: 2018-09-17 17:22:02 -0300 Date: 2018-09-06 11:41:11 -0300 Date: 2018-09-04 20:24:43 -0300 Date: 2018-09-02 11:52:41 -0300 Date: 2018-08-28 11:15:44 -0300 Date: 2018-08-26 13:32:05 -0300 Date: 2018-08-25 20:01:44 -0300 Date: 2018-08-18 19:22:05 -0300 Date: 2018-08-15 09:25:52 -0300 Date: 2018-08-12 20:18:20 -0300 Date: 2018-08-05 21:22:23 -0400 Date: 2018-07-22 17:44:37 -0400 Date: 2018-07-14 21:46:46 -0400 Date: 2018-05-28 12:06:19 -0400 Date: 2018-05-26 20:27:24 -0400 Date: 2018-05-25 10:09:06 -0400 Date: 2018-05-24 19:18:06 -0400 Date: 2018-05-20 21:17:18 -0400 Date: 2018-05-19 20:08:32 -0400 Date: 2018-05-14 11:23:25 -0400 Date: 2018-04-29 12:31:34 -0300 So it begs the question, whether it's still alive? We are considering … -
500 Internal Server Error!! - Issue in wsgi in django application migrating from python2.7 to python3.6
I am getting 500 Internal Server Error when I migrated my django app from python2.7 to python3.6. I have created a new virtualenv, and created all the apps individually. The virtualenv is defined in uwsgi.ini file home = /home/netadc/.venvs1/netadc I have installed all the packages using pip3.6. I am not sure what I am missing. Every config in uwsgi is same as python2.7 when it was working.I am using uwsgi 2.0.13. I have restarted nginx as well. Is there a separate uwsgi for python3 which I cannot locate? The socket permissions are also same as before. Please help. -
Django: render only last part of image url in template
I've a model that has an image field as attribute. I need to render the attributes of this model in my template, but specifically the image.url atribute. Right now, I can render it as: /media/images/floral.jpg However, I'd like to only render the last part: floral.jpg So I'm using this in my template: {{ cart_item.image.url }} What can I do to only render the last part of the image url? class SizeQuantity(models.Model): cart = models.ForeignKey(Cart, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) size = models.CharField(max_length=20, choices=TAMANIOS) quantity = models.CharField(max_length=20, choices=CANTIDADES) image = models.ImageField(upload_to='images', blank=True, null=True) uploaded_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.size view.py def cart_detail(request, total = 0, counter = 0, cart_items = None): try: cart = Cart.objects.get(cart_id = _cart_id(request)) cart_items = SizeQuantity.objects.filter(cart = cart) except ObjectDoesNotExist: pass return render(request, 'cart.html', dict(cart_items = cart_items, total = total, counter = counter))