Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django/Docker-compose: Retry Database Connection when: django.db.utils.OperationalError: (2002, "Can't connect to MySQL server on 'db' (115)")
This question have been asked here: django.db.utils.OperationalError: (2002, "Can't connect to MySQL server on 'db' (115)") and the answer has been to wait for the database to be ready. However, the official documentation here: https://docs.docker.com/compose/startup-order/ suggests that instead an in app retry method is implemented in order to retry the database connection when this fails. To handle this, design your application to attempt to re-establish a connection to the database after a failure. If the application retries the connection, it can eventually connect to the database. The best solution is to perform this check in your application code, both at startup and whenever a connection is lost for any reason. Unfortunately, the documentation just ends there and does not provide any examples or guides on how to implement this retry method. Does anyone knows how to do that in a clean way? -
Django orm query to count all the results returned and add to the queryset with other annotations, but not use group by
This should be the sql of django orm query select 0 'bucket_id', 'Incomplete' as 'name', count(*) 'user_count' from UserSr where job = 1 and pred_perf is null here is what i tried but it does group_by and returns multiple results UserSr.objects.filter(job=job_id, pred_perf__isnull=True).annotate(bucket_id=Value(0, IntegerField()),name=Value('Incomplete', output_field=CharField()),entry_count=Count('*')) -
ERROR django-softdelete: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output
I am trying to download django-softdelete~=0.9.1 on a different (windows) device than I usually use through pip. However when run I get the error ERROR: Command errored out with exit status 1: command: 'c:\users\pelizzy\appdata\local\programs\python\python38-32\python.exe' -c 'im port sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\PelizzY\\AppData\\Local\\Temp\ \pip-install-32uur6be\\django-softdelete\\setup.py'"'"'; __file__='"'"'C:\\Users\\PelizzY\\A ppData\\Local\\Temp\\pip-install-32uur6be\\django-softdelete\\setup.py'"'"';f=getattr(tokeni ze, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.cl ose();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base 'C:\Users\PelizzY\A ppData\Local\Temp\pip-pip-egg-info-_tq6m_l3' cwd: C:\Users\PelizzY\AppData\Local\Temp\pip-install-32uur6be\django-softdelete\ Complete output (44 lines): WARNING: The wheel package is not available. ERROR: Command errored out with exit status 1: command: 'c:\users\pelizzy\appdata\local\programs\python\python38-32\python.exe' -u - c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\PelizzY\\AppData\\Local\\ Temp\\pip-wheel-300gjngn\\setuptools-hg\\setup.py'"'"'; __file__='"'"'C:\\Users\\PelizzY\\Ap pData\\Local\\Temp\\pip-wheel-300gjngn\\setuptools-hg\\setup.py'"'"';f=getattr(tokenize, '"' "'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();e xec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d 'C:\Users\PelizzY\AppData\Local \Temp\pip-wheel-3w4e_e8i' cwd: C:\Users\PelizzY\AppData\Local\Temp\pip-wheel-300gjngn\setuptools-hg\ Complete output (6 lines): usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...] or: setup.py --help [cmd1 cmd2 ...] or: setup.py --help-commands or: setup.py cmd --help error: invalid command 'bdist_wheel' ---------------------------------------- ERROR: Failed building wheel for setuptools-hg ERROR: Failed to build one or more wheels Traceback (most recent call last): File "c:\users\pelizzy\appdata\local\programs\python\python38-32\lib\site-packages\set uptools\installer.py", line 126, in fetch_build_egg subprocess.check_call(cmd) File "c:\users\pelizzy\appdata\local\programs\python\python38-32\lib\subprocess.py", l ine 364, in check_call raise CalledProcessError(retcode, cmd) subprocess.CalledProcessError: Command '['c:\\users\\pelizzy\\appdata\\local\\programs\\ python\\python38-32\\python.exe', '-m', 'pip', '--disable-pip-version-check', 'wheel', '--no -deps', '-w', 'C:\\Users\\PelizzY\\AppData\\Local\\Temp\\tmp2i04c4ia', '--quiet', 'setuptool s_hg']' returned non-zero exit status 1. The above exception was the direct cause … -
No module named django-admin
I have using virtual environment to create a django project. I have freshly installed django and python to create a project. but facing an error to create a project. I guess the screenshot may help you the understand my question.enter image description here . (venv) C:\Users\abhinavkumar\Documents\mysql.python>django-admin startproject tutorials (venv) C:\Users\abhinavkumar\Documents\mysql.python>python -m django-admin C:\Users\abhinavkumar\Documents\mysql.python\venv\Scripts\python.exe: No module named django-admin. Project didn't get created whereas after "python -m django-admin". it is showing an error as module django-admin not found. -
Django, upload two files on one page
model.py: class InJPG(models.Model): file_path = models.FileField(upload_to="media",unique=True) views.py from model import InJPG def get_name(request): file1=InJPG(request.POST or None) file2=InJPG(request.POST or None) if file1.is_valid(): file1.save() if file2.is_valid(): file2.save() return render(request,'files.html',{'file1':file1,'file2':file2}) files.html ... {% block page %} <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{file1}} <button type="submit">upload file1</button> </form> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{file2}} <button type="submit">upload file2</button> </form> {% endblock %} I have web page, where I can upload two files file1 and file2 problem: I can load one file at once only, page is refreshing when I am uploading first file. I want to Load both files using one button. or two load buttons without refreshing second form. I am using two forms because i want to separate webpage and use there card classes -
Passing different URL parameters to AJAX function in Django
How to pass the different URL names to the javascript function. Here are my HTML and Javascript code. {% for profile, g_name in group_list %} <li class="contact"> <div class="wrap"> <img src="{{profile}}" alt="No image" /> <div class="meta"> <input type="hidden" id="myGroup" name="myGroup" value="{{g_name}}"> <button onclick="GetMessages()"> <p class="name">{{g_name}}</p> </button> </div> </div> </li> {% endfor %} <script> function GetMessages() { var myGroup = document.getElementById('myGroup').value; $('.ajaxProgress').show(); $.ajax({ type: "GET", url: "/getmsgs/"+myGroup, success: function(response){ $("#display").empty(); ... }, error: function(response){ alert("No Data Found"); } }); } </script> and this is my URL path('getmsgs/<str:word>/', views.groupmsgs_ajax, name='groupmsgs_ajax'), when I try the above method I am getting the first 'myGroup' id value. it is passing the first group name by default. I am not able to call other group names. Thank you for any help -
Django: Can't redirect to home page after login
I'm developing simple user authentication with a gorgeous frontend. It has only one app 'account'. under the app I created a 'registerPage' view and the register process working fine. But for login I'm using default view from django.contrib.auth. Problem is, after giving the email & password to login it should be redirect to home page, but remains in the same login page account/views: from django.shortcuts import render, redirect from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from django.contrib.auth import authenticate, login, logout from django.contrib import messages from django.contrib.auth.decorators import login_required # views here... from .models import * from .forms import CreateUserForm def registerPage(request): if request.method == 'POST': form = CreateUserForm(request.POST) if form.is_valid(): form.save() user = form.cleaned_data.get('username') messages.success(request, 'Account was created for ' + user) return redirect('login') else: form = CreateUserForm() context = {'form':form} return render(request, 'account/register.html', context) def logoutPage(request): logout(request) return redirect('login') @login_required def homePage(request): context = {} return render(request, 'account/home.html', context) account/urls: from django.urls import path from . import views urlpatterns = [ path('', views.homePage, name="home"), path('register/', views.registerPage, name="register"), # path('login/', views.loginPage, name="login"), ] login.html: main body <main class="login-body" data-vide-bg="{% static 'img/login-bg.mp4' %}"> <!-- Login Admin --> <form class="form-signin" action="" method="POST"> {% csrf_token %} <div class="login-form"> <!-- logo-login --> <div class="logo-login"> <a … -
Django check if username starts with a special character and change it to authenticate with changed username
Here's my custom auth backend. I want to check if username starts with a certain character and change this character to the new string or character. class PhoneAuthBackend(object): def authenticate(self, request, username=None, password=None): try: user = User.objects.get(username=username) if username.startswith('8'): username[0].replace('+7') if user.check_password(password): return user except User.DoesNotExist: return None -
Has anyone verified paystack payment using python or django
I check their documentation on how to implement verifying payment in my django rest project but i noticed they only had the options of using php, node and curl. please is there any other way i can go about it Thanks. -
django.core.exceptions.FieldError: Cannot resolve keyword 'slug' into field. Choices are:
#models.py class Category(models.Model): title = models.CharField(verbose_name='TITLE', max_length=200) slug = models.SlugField('SLUG', unique=True, allow_unicode=True, help_text='one word for title alias.') ... class Episode(models.Model): category = models.ForeignKey("Category", verbose_name=("CATEGORY"), on_delete=models.CASCADE) number = models.IntegerField() ... class Meta: ... def __str__(self): ... def get_absolute_url(self): return reverse("manga:episode_detail", kwargs={"slug": self.category.slug, "number": self.number}) #urls.py ... path("category/<korslug:slug>/", views.CategoryDetailView.as_view(), name="category_detail") path("category/<korslug:slug>/<int:number>/", views.EpisodeDetailView.as_view(), name="episode_detail"), #views.py # ... class EpisodeDetailView(DetailView): model = Episode It raised django.core.exceptions.FieldError: Cannot resolve keyword 'slug' into field. Choices are: ... How to access to Foreign key's slug? I've tried to change attribute query_pk_and_slug to True, and change get_queryset function like follow this, but it throwed same exception. query_pk_and_slug = True def get_queryset(self): return Episode.objects.filter(category__slug=self.kwargs['slug']) -
root domain running wordpress and django application on app subdomain - proxy pages from app subdomain to main domain
I have a Saas website that is developed using Django and the marketing site is also hand coded and running under django. I would like to move the marketing site on the main domain to wordpress and then host the web application under an app subdomain. However a number of pages that are important to our SEO are generated by the web application and appear on the main domain now. eg. example.com/service_page_1 example.com/service_page_2 Once I move the application to a subdomain these will be available at: app.example.com/service_page_1 app.example.com/service_page_2 Is there a way example.com can be running a wordpress marketing site and these pages from the subdomain can be made available on the main domain? I thought about hosting the content in iframes on the wordpress site but I am not sure how this would affect SEO. The web application will be running behind an nginx web server. Is there a way to proxy calls to certain routes on wordpress to my web application running behind nginx? (eg. www.example.com/service/*/ to display the page from my web application at app.example.com/service/*/) -
How can I arrange translation properly between the languages?
Arrangment of words is different in english and the language I want to switch to. <span> Biplove{% trans " has" %} <span class="font-6"> {% trans "replied" %} </span> {% trans "to your comment." %} </span> The arrangement of translation from above code will be different according to code. English Biplove has replied to your comment Another language Biplove has to your comment replied So, the arranging of translation will just be altering its position like above. What am I missing? -
Django: How do I make the media_url and root append my tenant folders using django-tenants?
I am trying to serve images from different tenants but on inspecting the image it brings a 404 error. How can I make my media_url or media_root append my tenant folder so as to appropriately server the images? This is the URL that is currently using to serve the broken thumbnails: http://d9.local.com:8000/media/thumbs/document-b4ded536-0302-11eb-be53-1062e5032d68-thumb.png?v=32361c04 expected url:http://d9.demo.com:8000/media/d9/thumbs/document-b4ded536-0302-11eb-be53-1062e5032d68-thumb.png Here is my settings.py file: STATICFILES_STORAGE = "django_tenants.staticfiles.storage.TenantStaticFilesStorage" MULTITENANT_RELATIVE_STATIC_ROOT = "" DEFAULT_FILE_STORAGE = 'django_tenants.files.storage.TenantFileSystemStorage' STATICFILES_LOCATION = 'static' MULTITENANT_RELATIVE_MEDIA_ROOT = '' MEDIAFILES_LOCATION = 'uploaded' MEDIA_ROOT = os.path.join(BASE_DIR,'media') MEDIA_URL = '/media/' STATIC_URL = '/static/' STATIC_ROOT = 'staticfiles' _DEFAULT_STATICFILES_DIRS = [ os.path.join(PROJECT_ROOT, STATICFILES_LOCATION), ] STATICFILES_DIRS = os.getenv('STATICFILES_DIRS', _DEFAULT_STATICFILES_DIRS) STATICFILES_FINDERS = ( 'django_tenants.staticfiles.finders.TenantFileSystemFinder', 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ) MULTITENANT_STATICFILES_DIRS = [ os.path.join(PROJECT_ROOT, "media/%s/thumbs" ), ] -
Is there a way to change the display value in series using highcharts
(Notice: noticed stackoverflow didn't like me embeding pictures because the account is so new so I will post a link to them instead) I am quite new to stackoverflow, django and highcharts so I apologies for any inconvenience. So I am currently working with displaying time and dates in highcharts when I noticed a small problem. When looking at the chart everything looks fine like this. https://i.stack.imgur.com/6hALh.png But when I hover my mouse about a point on the chart it shows a different value. It looks like this https://i.stack.imgur.com/WUr2p.png I would like so that when focusing on a point it will display as HH:MM:SS like it does on the side instead of the total amount of microseconds. What do I need to change to make it happen? Here is the code for the chart <script> $(function () { $('#container').highcharts({ chart: { type: 'line' }, title: { text: 'Time worked by {{user_to_show}}' }, xAxis: { categories: {{dates|safe}} }, yAxis: [{ title: { text: '' }, gridLineWidth: 1, type: 'datetime', //y-axis will be in milliseconds dateTimeLabelFormats: { //force all formats to be hour:minute:second second: '%H:%M:%S', minute: '%H:%M:%S', hour: '%H:%M:%S', day: '%H:%M:%S', week: '%H:%M:%S', month: '%H:%M:%S', year: '%H:%M:%S' }, opposite: true }], plotOptions: … -
What languages & technologies are best for a community website development? [closed]
I'm seeking for some guidance for a solid start in a website project :) I'm a fresh CS graduate and currently want to try and build a community website that will include a few 'bulletin board' based pages, such as: Apartment rents Second handed furniture sales Classes, courses & private teachers Activities and so on... *The website will require a registration to use it. And all users can post their announcements. My questions are: What technologies should I use? maybe Django? What database would be considered best for this use? lets say for a few thousand users. Is there a designated design pattern for it? Do you have an idea what would be the best combination for this use? Thank You! -
Django Forms labels render next to field above FilteredSelectMultiple
I have added a widget 'FilteredSelectMultiple' into my sign up form and now the following label is next to the widget. How can I get the next field label to render after the widget? form.py class MyCustomSignupForm(SignupForm): first_name = forms.CharField(max_length=30, label='First Name') last_name = forms.CharField(max_length=30, label='Last Name') dbs_number = forms.CharField(max_length=13, label='DBS Number') hospitals = forms.ModelMultipleChoiceField(queryset=HospitalListModel.objects.all(), widget=FilteredSelectMultiple('HospitalListModel',False), required=False, ) class Media: css = { 'all': ('/static/admin/css/widgets.css',), } js = ('/admin/jsi18n',) template {% extends '_base.html' %} {% load crispy_forms_tags %} {% block title %}Sign Up{% endblock title %} {% block content %} <h2>Sign Up</h2> <form method="post"> {% csrf_token %} {{ form|crispy }} {{ form.media }} <script type="text/javascript" src="{% url 'jsi18n' %}"></script> <button class="btn btn-success" type="submit">Sign Up</button> </form> {% endblock content %} -
How to routes in Django with Vue?
I want to create MPA with Vue for the frontend and Django for the backend. I only find a way to render the different routes via the Vue part. I made this with the vue create command. For example: App.vue <router-link to="/">Home</router-link> | <router-link to="/about">About</router-link> | <router-link to="/profile">Profile</router-link> This is just because I can't find the way to render my Vue pages from urls.py in my django application. For example, that's not my routes because I can't find how to write them: path('', TemplateView.as_view(template_name='index.html')), Can I render Vue pages in urls.py and how? -
Received unregistered task of type 'appname.tasks.add' - Celery
I'm trying to use Celery in my Django application. My tasks.py [this file is in the same folder as views.py] from celery import Celery app = Celery('tasks', backend='redis://localhost', broker='pyamqp://') @app.task def add(x, y): return x + y My views.py def view(): try: task = add.delay(4,5) except Exception as e: print (e) return True The error I am getting [2020-09-30 15:11:09,058: ERROR/MainProcess] Received unregistered task of type 'appname.tasks.add'. The message has been ignored and discarded. Did you remember to import the module containing this task? Or maybe you're using relative imports? Please see http://docs.celeryq.org/en/latest/internals/protocol.html for more information. My settings.py [I have added celery in the installed apps] CELERY_IMPORTS = ( 'sweetapi.tasks' ) I use the following command to start celery celery -A tasks worker The same code is working when used on the python shell. Do I have to add more settings to make it work with the Django application? -
How do i get the value of a file field in Django session wizard view class
I am doing a project in which i am required to save the path of a file into a database. I am capturing the data using form-tools in Django as shown in the code below: class FormWizardView(SessionWizardView): template_name = "done.html" file_storage =DefaultStorage() #form_list = [Vacancy,Personal,Academic,Other] @property def __name__(self): return self.__class__.___name__ def get_context_data(self,form,**kwargs): user=self.request.user #print(vacancy) msg = Post_vacancy.objects.filter(end__gte=datetime.now().date()) u = User.objects.get(username=user) context=super(FormWizardView,self).get_context_data(form=form,**kwargs) context.update({'msg':msg,'u':u}) return context def get_form_step_files(self,form): return form.files def done(self, form_list,form_dict, **kwargs): user=self.request.user m= Applicant.objects.get(user=user) ad=self.kwargs['advert'] self.urlhash = id_generator() while Application.objects.filter(uid=self.urlhash).exists(): self.urlhash = id_generator() x=[form.cleaned_data for form in form_list] print(form_dict) #vacancy=x[0]['vacancy'] vacancy=Post_vacancy.objects.filter(advert=ad).values_list('subjects',flat=True)[0] tsc_no=x[0]['tsc_no'] duration=x[0]['duration'] uid=str(vacancy) + self.urlhash surname=x[1]['surname'] m_name=x[1]['m_name'] l_name=x[1]['l_name'] id_no=x[1]['id_no'] image_id=self.request.FILES['image_id']#x[1]['image_id'] institutionA=x[2]['institutionA'] award=x[2]['award'] kcse=x[2]['kcse'] image_cert=self.request.FILES['image_cert']#x[2]['image_cert'] image_certKC=self.request.FILES['image_certKC']#x[2]['image_certKC'] break_in=x[2]['break_in'] co_curriculum=x[3]['co_curriculum'] image_co=self.request.FILES['image_co']#x[3]['image_co'] leadership=x[3]['leadership'] image_lead=self.request.FILES['id_no']#x[3]['image_lead'] sex=m.gender All the other field data is being captured as expected except the image file field which return none. I have read elsewhere that i need to use request to capture these field but i dont know how. Any assistance will be highly appreciated Included here is the html snippet for the wizard view: <form action="" method="post" class="form-horizontal" enctype="multipart/form-data"> {% csrf_token %} <div class="col-sm-3 form-control-label"> <table> {{ wizard.management_form }} {% if wizard.form.forms %} {{ wizard.form.management_form }} {% for form in wizard.form.forms %} {% for i in form %} … -
How can i search in django like google search?
I want to implement search input in Django like google search,for example when i type word in input it gives the list of words below the input.i want to implement auto search in Django. -
How to pass object properties from view to template in Django?
I must be missing something really basic here. I have created an object in my view to pass to my template. All the properties of my object are passed successfully but the last property, an integer, is not shown when rendering my template. Why? Here is my code: Views.py: def courseListView(request): object_list = {} courses = Course.objects.all() for course in courses: object_list[course] = { 'title': course.title, 'slug': course.slug, 'thumbnail': course.thumbnail, 'get_absolute_url': '/' + course.slug, 'progress': int(lessonsCompleted.objects.filter(user=request.user.id, course=course.id).count() / course.lessons.count() * 100) } print(object_list) context = { 'object_list': object_list, } return render(request, "courses/course_list.html", context) This way I am creating an object that looks like this when I print it: {<Course: Mezclar música chill y ambient>: {'title': 'Mezclar música chill y ambient', 'slug': 'mezcla-chill-ambient', 'thumbnail': <ImageFieldFile: mixing.jpeg>, 'get_absolute_url': '/mezcla-chill-ambient', 'progress': 66}, <Course: Componer bases electrónicas>: {'title': 'Componer bases electrónicas', 'slug': 'componer-bases-electronicas', 'thumbnail': <ImageFieldFile: beats.jpeg>, 'get_absolute_url': '/componer-bases-electronicas', 'progress': 75}, <Course: Melodías ultrasónicas>: {'title': 'Melodías ultrasónicas', 'slug': 'melodias-ultrasonicas', 'thumbnail': <ImageFieldFile: melodies.jpeg>, 'get_absolute_url': '/melodias-ultrasonicas', 'progress': 50}} Ultimately I want to pass to the template the progress for each course, for the currently logged user, so I can show this information for each course in my web page. To show that, in my template I am … -
Django JSONField with default and custom encoder
Django version: 3.1.0, MySQL backend I have a JSONField on my model: class Employee(models.Model): address = models.JSONField( encoder=AddressEncoder, dedocer=AddressDecoder, default=address_default ) Then the encoder looks like this: class AddressEncoder(DjangoJSONEncoder): def default(self, o): if isinstance(o, Address): return dataclasses.asdict(o) raise TypeError("An Address instance is required, got an {0}".format(type(o))) Then the address_default looks like this: def address_default(): encoder = AddressEncoder() address = Addres(...) return encoder.encode(address) Currently I have set the address_default to return a dict. Although it should actually return an Address instance. When I change this so that the address_default returns an instance of Address, an error is raised TypeError: Object of type Address is not JSON serializable. However, in other parts of the code where the address is in fact an instance of Address, no errors are raised. So the custom AddressEncoder does not seem to be used on the value provided by the address_default. When the address attribute on Employee is set to e.g. a string, no error is thrown. This might have to do with what is explained in Why is Django not using my custom encoder class. The code in AddressEncoder is not executed. Question: What is the correct way to set up the address_default, and Encoder/Decoder so … -
How do I specify urlconf correctly in Django reverse() function?
I need to specify my file containing the URLs explicitly like this: link = reverse(link, urlconf='backend/urls') The backend folder is located in a src folder of the project. But the path 'backend/urls is not found, I get an error: No module named 'backend/urls' How do I specify the path correctly? I'm not sure where Django thinks the root of the project is. -
ELI5: Django Migrations - Do they change the SQL database?
My company has tasked me with creating a small proof-of-concept web app where we would like to read and display a few columns from one of our tables in our microsoft sql server. I have setup my django project and installed the django-mssql-backend etc. However I found the explanation of migrations rather vague Migrations are Django’s way of propagating changes you make to your models (adding a field, deleting a model, etc.) into your database schema. They’re designed to be mostly automatic, but you’ll need to know when to make migrations, when to run them, and the common problems you might run into. Django migrations documentation I'm not allowed to alter the database in any way as it would break some legacy systems so I want to make sure that migrating does not alter the database. Thus my question is rather simple, would executing the "python manage.py migrate" alter the database or is it only locally in my django project? -
Django, get fullpath of loaded file
/django 3/ I want to use my loaded file , with external script to do that I need full path for this file in my media folder, each time I am loading same named file, I get unique name. example: input : image12.jpg in folder media -> image12_0x982.jpg my model.py: class InJPG(models.Model): file_path = models.FileField(upload_to="media",unique=True) #I have also prepared forms.py but its simillar as model form my views.py: from model import InJPG def get_name(request): file1=InJPG(request.POST or None) file2=InJPG(request.POST or None) if file1.is_valid(): file1.save() if file2.is_valid(): file2.save() #print file path: file = InJPG.objects.all() for f in file: print(f.file_name) return render(request,'my.html',{'file1':file1,'file2':file2}) In this last line, I am receiving list of all files with right paths with unique names. How to get only paths for file1 and file2 ? And open those files using external script?