Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to manage Hierarchical categories in Django?
I have this JSON object. I want to display this object in the HTML view Django, also this should be editable and modifiable by the end-user. ** User should also be able to add a category at any level of the hierarchy.** Is there a way to show this data in hierarchical form also as a form, so the user can edit and change these categories. { "label": "Indian Coins", "order": 1, "id": 1, "img": "https://cdn1.iconfinder.com/data/icons/major-world-flags-1/512/india_flag_circle-512.png", "list": [ { "id": "1", "label": "ancient", "order": 0, "list": [ { "id": "1", "label": "janpad", "order": 4 }, { "id": "2", "label": "City-States", "order": 1 }, ] }, { "id": "1", "label": "medieval", "order": 0, "list": [ { "id": "1", "label": "Dehli Rajas ,sindh sultan Dehli sultan", "order": 0 }, { "id": "2", "label": "Chola Chera Pandeyas Vijayanagar, and other southern kingdoms", "order": 0 }, ] } ] }, { "label": "World Coins", "id": 2, "order": 0, "img": "https://images.vexels.com/media/users/3/157970/isolated/preview/c156b4270aea292b9b335dd463ea17eb-earth-planet-icon-earth-icon-by-vexels.png", "list": [ { "id": "1", "label": "ancient", "order": 0, "list": [ { "id": "1", "label": "janpad", "order": 0 }, { "id": "2", "label": "City-States", "order": 0 }, ] }, { "id": "2", "label": "medieval", "order": 0, "list": [ { "id": "1", "label": "Dehli Rajas … -
lxml affects excel file generated by django + uwsgi?
The excel file generated cannot be open when my project started with uwsgi whne lxml installed in my environment as it can be opened successfully with django manage.py runserver and gunicorn My main codes like below: ── test_excel ├── urls.py ├── wsgi.py └── settings.py ── manage.py urls.py from django.contrib import admin from django.urls import path from django.views import View from openpyxl.writer.excel import save_virtual_workbook import pandas as pd from django.http import HttpResponse, StreamingHttpResponse import xlrd import openpyxl from openpyxl import Workbook from openpyxl.styles import Font, Alignment from openpyxl.writer.excel import save_virtual_workbook from openpyxl.cell.cell import ILLEGAL_CHARACTERS_RE class TestExcelView(View): def get(self, request): # indexs = {0: ['cost', '2020-01', 'testing'], # 1: ['cost', '2020-01', '360 Limited'], # 2: ['cost', '2020-02', 'Korea Co.,LTD'], # 3: ['cost', '2020-02', 'ADS4EACH HK TECH LIMITED']} # columns = [['1'], ['amy'], ['tom'], ['zara'], ['jay'], ['Lee'], ['Uzi'], ['Zome'], ['Qoe'], ['Aoi'], ['Yeezy'], # ['Hazy'], ['Wash'], ['pany'], ['zoey'], ['Moe'], ['total']] # datas = { # 0: [0.0, 0.0, 0.0, 0.0, 0.0, 7.85, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 7.85], # 1: [0.0, 0.0, 0.0, 0.0, 0.0, 7.85, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 7.85], # 2: [0.0, 0.0, 0.0, 0.0, 0.0, 7.85, 0.0, 0.0, 0.0, 0.0, … -
How to handle 403 forbidden error in docker container?
I have been running an application in docker container in windows 10. git for the application is https://github.com/CogStack/MedCATtrainer There are multiple places where I am uploading static files which is subsequently modified by the application. AFter the modification when I am trying to download the file. It is throwing the above error. http://localhost:8001/media/core_snomed_cdb_pjW1Zmf.dat when i have the above url it should allow me to download the file. The docker and nginx configuration files are the above link. I am fairly inexperienced not able to find out how to debug this. -
Javascript is not working with my Django?
I'm currently following a NetNinja Youtube Django Tutorial with the js as following: const titleInput = document.querySelector('input[name=title]'); const slugInput = document.querySelector('input[name=slug]'); const slugify = (val) => { return val.toString().toLowerCase().trim() .replace(/&/g, '-and-') // Replace & with 'and' .replace(/[\s\W-]+/g, '-') // Replace spaces, non-word characters and dashes with a single dash (-) }; titleInput.addEventListener('keyup', (e) => { slugInput.setAttribute('value', slugify(titleInput.value)); }); this is the exact same code as shown in the tutorial (Actually i just copy and pasted the code to see if it works... but this one doesn't work too) I couldn't find a reason why this doesn't work. Any suggestions?? Thanks -
How to write an api call through ajax in django by hiding the api tokens?
I am having django app in which there is a html page where I have shown all the users of slack workspace by accessing through the api token and wrote the javascript for posting message to the respective user on click now the problem here I have been using the token in the javascript function which is been not secure and I am not able to push the code to github so can anyone help me of just writing the api call in django for posting message on click of html elements the HTML code which I wrote: <div class="container"> <h3 class=" text-center">Slack Users List</h3> <div class="messaging"> <div class="inbox_msg"> <div class="inbox_people">\ <div class="headind_srch"> <div class="recent_heading"> <h4>Recent</h4> </div> <div class="srch_bar"> <div class="stylish-input-group"> <h6> Please select user to send message</h6> <span class="input-group-addon"></span> </div> </div> </div> <div class="inbox_chat"> <div class="chat_list active_chat"> <div class="chat_people"> {% for i,j in liste %} <div class="chat_ib"> <h5><a href="#" class="person_name" id={{i}}>{{j}}<span class="chat_date"></span></a></h5> <p>{{i}}</p> <p></p> <hr> </div> {% endfor %} </div> </div> </div> </div> <div class="mesgs"> <a href="/modsy/logout"><button type="button" style="float: right;" class="btn2">Log Out</button></a> <div class="msg_history mt-5"> <p id="insertName"></p> <div class="type_msg"> <div class="input_msg_write"> <input type="text" id="write_msg" placeholder="Type a message" /> <input type="hidden" id="myVar" name="variable" value="{{ secret }}"> <button id="msg_send_btn" type="button"><i class="fa … -
Is there a better (Pythonic) or Django way of doing using a table with slight differences across multiple pages?
I'm currently using pandas to create a table which contains prices/data that is a multiple of the 'base' price. for e.g desired function Table I (on page1.html) .---.-----------.-----------.------------. | | A | B | C | :---+-----------+-----------+------------: | 1 | $30 | $60 | $90 | :---+-----------+-----------+------------: | 2 | =A * 1.25 | =B * 1.25 | =C * 1.125 | :---+-----------+-----------+------------: | 3 | =A * 1.5 | =B * 1.5 | =C * 1.5 | '---'-----------'-----------'------------' Table II (on pagetwo.html) .---.-----------.-----------.------------. | | A | B | C | :---+-----------+-----------+------------: | 1 | $35 | $65 | $95 | :---+-----------+-----------+------------: | 2 | =A * 1.25 | =B * 1.25 | =C * 1.125 | :---+-----------+-----------+------------: | 3 | =A * 1.5 | =B * 1.5 | =C * 1.5 | '---'-----------'-----------'------------' there are around 20-30 different tables with different base or row 1 prices/amounts. Is there a pythonic or django way of using a base template and only having to enter the initial prices in each html page? I can only think of using a pandas table in a base template without row 1 (initial price) and pass each pages respected row 1 (prices) which then … -
Review a form before submitting in django
I am building a registration form. I want the users to review their filled-up forms to confirm their submissions. But in my code the form is submitted twice (overwritten not duplicated). Once when they hit the submit button after filling their form and overwritten after hitting the submit button on the review page. As a result if they close the browser in the review page their page is still submitted, which I don't want to allow. views.py from django.shortcuts import render, redirect from .models import * from .forms import * # Create your views here. def index(request): form = RegisterForm() print('hi') if request.method == 'POST': form = RegisterForm(request.POST, request.FILES) if form.is_valid(): z = form.cleaned_data if (Register.objects.filter(email=z['email']).exists()): print('already exist') return redirect('/') else: print('xx') return redirect('preview', pk=z.get('id')) context = {'form':form} return render(request, 'event/index.html', context) def preview(request, pk): prev = Register.objects.get(id=pk) if request.method == 'POST': prev.save() print('overwrite') return redirect('/') print('yy') context = { 'prev':prev,'id':pk} return render(request, 'event/preview.html', context) index.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Event Registration</title> <link rel="stylesheet" href="{% static 'css/style.css' %}"> <script src="{% static 'js/script.js' %}"></script> </head> <body> <div class="mobile-screen"> <div class="header"> </div> <div class="logo"></div> <form id="login-form" method="POST" action="" enctype="multipart/form-data"> {% csrf_token … -
ProductCreateView didn't return an HttpResponse object. It returned None instead
I am getting this error now ValueError at /store/createproduct/ This was working fine until yesterday but I dont understand what happened now. Please do have a look at the code. I am not able to understand whats causing it. Traceback: Traceback Switch to copy-and-paste view C:\Users\jerry\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py in inner response = get_response(request) … ▼ Local vars Variable Value exc ValueError("The view store.views.ProductCreateView didn't return an HttpResponse object. It returned None instead.") get_response <bound method BaseHandler._get_response of <django.core.handlers.wsgi.WSGIHandler object at 0x03E19478>> request <WSGIRequest: POST '/store/createproduct/'> C:\Users\jerry\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py in _get_response raise ValueError( views` class ProductCreateView(CreateView, LoginRequiredMixin): def get(self, *args, **kwargs): ImageFormSet = modelformset_factory(ProductImage, fields=('image',), extra=4, can_delete=True) form = CreateProductForm() formset = ImageFormSet(queryset=ProductImage.objects.none()) context = { 'form': form, 'formset': formset, } return render(self.request, 'store/product/product_form.html', context) def post(self, *args, **kwargs): current_user = self.request.user user = Account.objects.filter(email=current_user.email).first() ImageFormSet = modelformset_factory(ProductImage, form=ProductImageForm, extra=4, can_delete=True) formset = ImageFormSet(self.request.POST, self.request.FILES, queryset=ProductImage.objects.none()) form = CreateProductForm(self.request.POST or None, self.request.FILES or None) if form.is_valid() and formset.is_valid(): obj = form.save(commit=False) obj.user = self.user obj.save() form.save_m2m() #to save tags as per documentation create_action(self.request.user, 'posted a new product for sale', obj) for f in formset.cleaned_data: try: image = f['image'] photo = ProductImage(product=obj, image=image) photo.save() except Exception as e: break messages.success(self.request, 'Product has been listed for sale') … -
Field defines a relation with model 'Division', which is either not installed, or is abstract. Django
I have Error: polls.Choice.division_names: (fields.E300) Field defines a relation with model 'Division', which is either not installed, or is abstract models.py division_id = models.IntegerField(primary_key=True) division_name = models.CharField(max_length=200) def __str__(self): return self.division_name class Meta: app_label = 'db' db_table = "divisions" class Choice(models.Model): user = models.ForeignKey(User, on_delete=models.DO_NOTHING, null=True, blank=True) question = models.ForeignKey(Question, on_delete=models.CASCADE) funny_name = models.CharField(max_length=200) votes = models.IntegerField(default=0) division_names = models.ForeignKey(Division, on_delete=models.DO_NOTHING, null=True, blank=True) def __str__(self): return self.funny_name``` -
hoe to set Custom Path for Python Django logger in basicConfig
How to save the python logs in a custom path other than a Base directory. my code is like this logging.basicConfig(filename= '../applicationz.log', level=logging.ERROR, format='%(asctime)s %(levelname)s %(name)s %(message)s') logger=logging.getLogger(name) it always store the log in Base directory. I am using Ubuntu 16 - and in production its a AWS server with Apache. -
Django Rest Framework get the tree of parents and children of the object
I would lite to get the full tree of the objects for the given object. Let's say I have: Note 5 Note 1 Note 2 Note 3 Note 4 Note 6 Note 7 I tried to use model to get children and parents and combine it together. Then I found some solution using serializers but when I retreive i always geet all notes. I would like to get only notes that are in the tree # models.py class Note(models.Model): note_id = models.AutoField(primary_key=True) title = models.CharField(max_length=100) parent_note = models.ForeignKey('self', on_delete=models.SET_NULL, null=True, related_name='subnotes') # serializers.py class RecursiveSerializer(serializers.Serializer): def to_representation(self, value): serializer = self.parent.parent.__class__(value, context=self.context) return serializer.data class NoteTreeSerializer(serializers.ModelSerializer): subnotes = RecursiveSerializer(many=True, read_only=True) class Meta: model = Note fields = ('note_id', 'title', 'subnotes') # views.py class NoteTreeViewSet(viewsets.ModelViewSet): queryset = Note.objects.all() serializer_class = NoteTreeSerializer def retrieve(self, request, pk, *args, **kwargs): queryset = Note.objects.filter(pk=pk) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) For http://127.0.0.1:8000/api/note/3/note-tree/ I would like to get: { "note_id": 1, "title": "Note 1", "subnotes": [ { "notet_id": 2, "title": "Note 2", "subnotes": [ { "note_id": 3, "title": "Note 3", "subnotes": [ { "note_id": 4, "title": "Note 4", "subnotes": [] } ] } ] } ] }, So for notes 1, 2, 3, 4 the output … -
Validating blank django form field not working
I always use the following code to validate a form to prevent blank form submission. It always works in Django 1.8 but for some reason is not working in Django 2.2. Here is the form class CreateForm(forms.ModelForm): class Meta: model = Device fields = ['category', 'item_name', 'quantity'] def clean_category(self): category = self.cleaned_data.get('category') if category == '': raise forms.ValidationError('This field is required') return category def clean_item_name(self): item_name = self.cleaned_data.get('item_name') if item_name == '': raise forms.ValidationError('This field is required') return item_name Thanks -
How to use same MySQL database with both Django and Express.js together?
For Django, ORM makes it very easy to manage tables so I am using Django to manage the outline of the database. How to use express.js to use the same database so that IDEs can suggest field names and queries? Ideally the goal is to avoid or minimize typing manual sql queries in express.js. -
Django management command doesn't flush stdout
I'm trying to print to console before and after processing that takes a while in a Django management command, like this: self.stdout.write('Saving routes ... ', ending='') for route in get_all_routes(): route_obj = Route( route_type=route['routeTp'], route_id=route['routeId'], route_number=route['routeNum']) route_obj.save() self.stdout.write('done.') In the above code, Saving routes ... is expected to print before the loop begins, and done. right next to it when the loop completes so that it looks like Saving routes ... done. in the end. However, the former doesn't print until the loop completes, when both strings finally print together, which is not what I expected. I found this question, where the answer suggests flushing the output i.e. self.stdout.flush(), so I added that to my code: self.stdout.write('Saving routes ... ', ending='') self.stdout.flush() for route in get_all_routes(): route_obj = Route( route_type=route['routeTp'], route_id=route['routeId'], route_number=route['routeNum']) route_obj.save() self.stdout.write('done.') Still, the result remains unchanged. What could have I done wrong? -
How to log Django warning and errors to log file in Production?
What I want to achieve is that warning and errors that happen in production (DEBUG=False) are logged into to specific (wishfully rolling) log file. I have been googling for hours, but can't find a good tutorial on this. Maybe someone why has experience in this or just knows can show me an example. Thank you! -
How to anyway escape ? charater in Django url?
I know that '?' character is not recommended (permited?) in django urls, but one of my requirments is to process external calls like "/files/?access_token=" and i cannot change their syntax, so i need to process it. I've tried: 1 re_path(r'(?P<magic_name>[^/]+)(.+)access_token', views.GetFileInfo, name='get_info') 2 re_path(r'(?P<magic_name>[^/]+)(\?)access_token', views.GetFileInfo, name='get_info') 3 re_path(r'(?P<magic_name>[^/]+)(?)access_token', views.GetFileInfo, name='get_info') 4 re_path(r'(?P<magic_name>[^/]+)?access_token', views.GetFileInfo, name='get_info') 5 re_path(r'(?P<magic_name>[^/]+)\?access_token', views.GetFileInfo, name='get_info') But nothing above is a solution. Top url is working with other characters but not with question symbol. I'm starting to consider writing my own middleware (never did it) to change request's properties or using smth like url_rewrite, but all this looks like over-engineering of such simple task like processing a character. Do i miss something? -
Convert PostreSQL Enum type to Django Customer Field
I have the following ENUM in my PostgreSQL database: CREATE TYPE UserType AS ENUM ('Admin','Teacher', 'Student'); CREATE TYPE CourseType AS ENUM (); I want to use this as one of the column-type in my tables, but how do I create this custom field in Django which uses the values in the ENUM type of PostgreSQL and not just use tuples like: USER_TYPES = ( ('A', 'Admin'), ('T', 'Teacher'), ('S', 'Student'), ) usertype = models.CharField(max_length=1, choices=USER_TYPES) as this will be locally saved in Django project and not in database. I plan to add more values in this ENUM so want the Django to use this type as a Field and not choices. How do I do that. -
How do I make my pagination show in Django template?
Goodday everyone. I want to add pagination to my home page ('index.html'). I followed the documentation of Django for pagination but I added Bootstrap's pagination to it to give a beautiful outlook. However, it does show on my home page. Here is the index.html code <div class="row"> <div class="col-md-12"> {% if post.has_other_pages %} <ul class="pagination"> {% if post.has_previous%} <li class="page-item"> <a href="?page={{post.previous_page_number}}" class="page-link">&laquo; </a> </li> {% else %} <li class="page-item disabled"> <a class="page-link">&laquo;</a> </li> {% endif %} {% for i in post.paginator.page_range %} {% if post.number == i %} <li class="page-item active"> <a class="page-link">{{i}}</a> </li> {% else %} <li class="page-item"> <a href="?page={{i}}"class="page-link">{{i}}</a> </li> {% endif %} {% endfor %} {% if post.has_next%} <li class="page-item"> <a href="?page={{post.next_page_number}}" class="page-link">&raquo; </a> </li> {% else %} <li class="page-item disabled"> <a class="page-link">&raquo;</a> </li> {% endif %} </ul> {% endif %} </div> </div> This is the protion that contains the pagination. Here is my views.index def index(request): post = Post.objects.all() paginator = Paginator(post, 3) page = request.GET.get('page') page_post = paginator.get_page(page) context = { 'post': page_post } return render(request, 'blog/index.html', context) What am I doing wrong please? -
DJango annotate count filter по ManyToManyField
Есть модель тегов вопросов class QuestionTag(models.Model): objects = QuestionTagManager() name = models.CharField(max_length=32, primary_key=True) ... и модель вопроса class Question(models.Model): objects = QuestionManager() tags = models.ManyToManyField(QuestionTag) ... Мне необходимо в менеджере модели тега написать команду вычисления 10 лучших тегов, то есть, отсортировать их по количеству вопросов (по убыванию), связанных с соответствующим тегом полем ManyToManyField, и взять первые 10 элементов от полученного QuerySet. Вот, что у меня получилось class QuestionTagManager(models.Manager): def get_top(self): return self.annotate(rating=Count(Question, filter=Q(question__tags__contains))).order_by('rating')[:10] Данный запрос очевидно написан неверно и не работает. Подскажите, как правильно написать такой запрос. -
the post isn't selected automatically of particular user in django
hi am working on a project where am using multiple user data a user did a post onto the site and when driver see that post he adds their offer to that post but when driver submit the post ...at the admin level the particular is selected automatically but the post is not selected on which he adds price this is my post model.py class Loader_post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE ,related_name="Loader") pick_up_station = models.CharField(max_length=150) destination_station = models.CharField(max_length=150) sender_name = models.CharField(max_length=150) phone_number = PhoneNumberField(null=False, blank=False, unique=True) receiver_name = models.CharField(max_length=150) this is my second model of adding price to a particular post class price(models.Model): my_post = models.ForeignKey(Loader_post, related_name='prices') user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, default='') driver_price = models.CharField(max_length=150, null=True) driver_name = models.CharField(max_length=150, null=True) status = models.BooleanField(default=False) this is my adding price to the post views.py @login_required def add_price_to_post(request, pk): post = get_object_or_404(Loader_post, pk=pk) user = request.user if request.method == "POST": form = price_form(request.POST) if form.is_valid(): ps = form.save(commit=False) ps.user = request.user ps.status = True ps.post = post ps.save() return redirect('Driver:Driverview') else: form = price_form() return render(request, 'price_form.html', {'form': form}) this is my html add post button {% for loader in Loader %} this is loop and this is button <a href="{% url 'Driver:price' … -
Efficient way to update multiple model instances
I want to update multiple attributes of multiple model instances. It should update the instance based on the primary key. -
How to upload python modules on Heroku
I have Django app, which I deployed on Heroku. All the modules were deployed whith requirements.txt and everything is ok But I also have several classes which are made as modules in separate .py files. On local machine these modules are in ...\Python\Python38-32\Lib\site-packages\modules\ folder Now I need to upload these modules to Heroku. But I don't know how to do it. Is there any file manager program for windows, which allows to connect to heroku server and upload these /modules/ folder to the site-packages directory? I've tried to find such a program, but couldn't find anything -
How to automatically obtain which endpoint was a request sent to in django?
I want to include a feature in my django REST API where whenever sends a request to an endpoint / url that url along with the post data should be saved to the sqlite database. post data is already being saved but how do I obtain and save the url from which the request is coming from? I am using django rest framework thanks in advance! -
Trying to wrap my head around message flow with django channels
I'm trying to wrap my head around Django channels. I'm completely new to async programming and I'm trying to understand why my code behaves like this. I'm currently building an app using Django channels, currently using the in memory channel layer in settings.py: CHANNEL_LAYERS = { "default": { "BACKEND": "channels.layers.InMemoryChannelLayer" } } I'm trying to start a long running task via a websocket and want the consumer to send periodic updates to the client. Example code: import time from asgiref.sync import async_to_sync from channels.generic.websocket import JsonWebsocketConsumer class Consumer(JsonWebsocketConsumer): def connect(self): print("connected to consumer") async_to_sync(self.channel_layer.group_add)( f'consumer_group', self.channel_name ) self.accept() def disconnect(self, close_code): async_to_sync(self.channel_layer.group_discard)( 'consumer_group', self.channel_name ) self.close() def long_running_thing(self, event): for i in range(5): time.sleep(0.2) async_to_sync(self.channel_layer.group_send)( 'consumer_group', { "type": "log.progress", "data": i } ) print("long_running_thing", i) def log_progress(self, event): print("log_progress", event['data']) def receive_json(self, content, **kwargs): print(f"Received event: {content}") if content['action'] == "start_long_running_thing": async_to_sync(self.channel_layer.group_send)( 'consumer_group', { "type": "long.running.thing", "data": content['data'] } ) The consumer starts long_running_thing once it receives the right action. The calls to log_progress however happen after long_running_thing has completed. Output: Received event: {'action': 'start_long_running_thing', 'data': {}} long_running_thing 0 long_running_thing 1 long_running_thing 2 long_running_thing 3 long_running_thing 4 log_progress 0 log_progress 1 log_progress 2 log_progress 3 log_progress 4 Could someone explain … -
How to have a custom endpoint for a model's field in Django?
I want to have an endpoint for every image I want to add tags in. Suppose I have: #models.py class ImageTag(models.Model): name = models.CharField() description = models.CharField() class Image(models.Model): image_id = models.CharField(unique=True) image_tags = models.ManyToManyField(ImageTag, blank=True) ... #serializers.py class ImageSerializer(serializers.ModelSerializer): class Meta: model = Image fields = '__all__' #views.py class ImageViewSet(viewsets.ModelViewSet): queryset = Image.objects.all() serializer_class = ImageSerializer lookup_field = 'image_id' ... #urls.py router.register(r'images', ImageViewSet, basename='image') I want to POST and DELETE image_tags in an endpoint such as: localhost:8000/my_app/images/IMG_123/image_tags where: IMG_123 is an Image I think I will need a separate serializer and viewset for that. But more importantly I want to know how will I add such endpoint in the router in urls.py I am looking for something like this: router.register(r'<image>/image_tags', ImageTagViewSet, basename='image_tag') NOTE: I was able to change Image endpoint using its image_id (instead of ID) because of lookup_field in ImageViewSet, thus can be: localhost:8000/my_app/images/IMG_123/