Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: User Form not saving the data to the database
So, I'm trying to set the user's profile after they have signed up and I created this ModelForm for User Model and now I'm trying to fetch the data from the ModelForm (HTML) to my view but it's not really saving the data to my database. Although it doesn't give me any error. Here's my view: @login_required def saveprofile(request): if request.method == 'POST': form = ProfileForm(request.POST, request.FILES) form2 = UserForm(request.POST, request.FILES) if form.is_valid(): Form = form.save(commit=False) Form.user = request.user Form.save() if form2.is_valid(): Form2 = form2.save(commit=False) Form2.user = request.user Form2.save() return redirect('usersfeed') Here's my HTML form: <form action="/saveprofile/" method="post" enctype="multipart/form-data" style="transform: translate(60%,200%);"> {% csrf_token %} {{ Form.as_p }} {{ Form2.as_p }} <button type="submit">Submit</button> yaha pr username aur email nahi dikhana </form> My forms.py: from django import forms from django.contrib.auth.models import User from .models import profile class UserForm(forms.ModelForm): class Meta: model = User fields = ['username','email','first_name','last_name'] class ProfileForm(forms.ModelForm): class Meta: model = profile fields = ['desc','pfp','cover'] -
Django 3.1 can't manage to run views asynchronously
I'm running Django-3.1 (and also I've tried master 3.2 version) in asgi mode via uvicorn. But when I open the url in a couple of browser tabs I see requests to be processed sequentially. It seems like this claim from docs: Under a WSGI server, async views will run in their own, one-off event loop. is also applied to ASGI mode. Here's the code I use: # asgi.py import os from django.core.asgi import get_asgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings") application = get_asgi_application() # settings.py SECRET_KEY = "foo" ROOT_URLCONF = "urls" # urls.py import asyncio import uuid from django.http import HttpResponse from django.urls import path async def view(request): id = uuid.uuid4() print(f"{id} sleeping") await asyncio.sleep(5) print(f"{id} woke up") return HttpResponse("ok") urlpatterns = [ path("", view), ] And here's the sequential output I see: $ uvicorn asgi:application INFO: Started server process [28020] INFO: Waiting for application startup. INFO: ASGI 'lifespan' protocol appears unsupported. INFO: Application startup complete. INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) bb1d30bc-b05e-4412-94ad-f4507c766074 sleeping bb1d30bc-b05e-4412-94ad-f4507c766074 woke up INFO: 127.0.0.1:51878 - "GET / HTTP/1.1" 200 OK f451d614-89dd-401d-8302-13e842040a3a sleeping f451d614-89dd-401d-8302-13e842040a3a woke up INFO: 127.0.0.1:51878 - "GET / HTTP/1.1" 200 OK -
How to create a form that queries objects in a Model and display the query results in a new page?
I am creating a hobby website (Airbnb clone) where on the index page there is a form that accepts a city and a property type (Apartment, Office, Restaurant, etc). I am using Django as my backend. Hosted: https://directoffices.azurewebsites.net/ (May take some time to load ** No CDN config) The pages are index and listings where the index is the landing page that consists of the search form and listings that have the properties listed. I've built a form (forms.py) : class SearchPropertyForm(ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['city'].required = False self.fields['city'].empty_label = 'Where do you want to go?' self.fields['city'].widget.attrs.update( {'class': 'chosen-select-no-single'}) self.fields['property_type'].required = False self.fields['property_type'].empty_label = 'Any Type' self.fields['property_type'].widget.attrs.update( {'class': 'chosen-select-no-single'}) class Meta: model = Listing fields = ['city', 'property_type'] Views.py def index(request): searchForm = SearchPropertyForm() CONTEXT = { 'searchForm': searchForm } if request.method == "GET": searchForm = SearchPropertyForm(request.GET) if searchForm.is_valid(): location = searchForm.cleaned_data.get('city') property_type = searchForm.cleaned_data.get('property_type') listings = Listing.objects.filter( city=location, property_type=property_type) return render(request, 'core/listings.html', {'listings' : listings}) else: searchForm.errors.as_data() else: return render(request, 'core/index.html', CONTEXT) HTML: <form class="main-search-form" method="GET" target="/listings/"> ** CONTENTS AND FIELDS ** </form> I am not sure whether this is the correct way of doing it and once the listing page is up, the index page … -
DJANGO: Template URL to create new model with ForeingKey as parameter
Best regards!, I'm using a patter like this in Django admin templates to add new models: {% url 'admin:app_model_add' %} where app is an application and model is a model of that app, the problem is this, I have 2 models related by a ForeignKey, lets say I have: class Chapter(TimeStampedModel): title = models.CharField('Título', max_length=250) class Subchapter(TimeStampedModel): title = models.CharField('Título', max_length=250) chapter = models.ForeignKey(Chapter, on_delete=models.CASCADE, verbose_name='Capítulo') So, if I go to admin's Subchapter add it shows a combobox of all existing chapters to which I can link the Subchapter being added and that's just fine, but what I need is, via URL tag show above, I want to pass a parameter through that add URL so the chapter with a given Id be selected as default and the user does not have the need to select it. Is that possible? any help will be appreciated, thanks in advance! -
how to use a javascript variable in django if statement
My code is <body> <div class="slideshow"> {% for img in image_pr %} {% if img.section == section %} <div class="slideshow_img" style="background-image:url(/static/images/project_images/{{img.name}}.jpg)"> </div> {% endif %} {% endfor %} </div> <script type="text/javascript"> function getParameterByName(name, url) { if (!url) url = window.location.href; name = name.replace(/[\[\]]/g, '\\$&'); var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'), results = regex.exec(url); if (!results) return null; if (!results[2]) return ''; return decodeURIComponent(results[2].replace(/\+/g, ' ')); } var section = getParameterByName('section'); </script> </body> i would like to use the variable name "section" in the if statement used in body. How can i do it? -
Custom model manager gets clobbered by prefetch_related
I have a model and a corresponding model manager: class MyModelManager(models.Manager): def get(self, **kwargs): return super().select_related('group').get(**kwargs) class MyModel(models.Model): name = models.CharField(...) group = models.ForeignKey('Group', ...) tags = models.ManyToManyField('Tag', ...) # ... others ... objects = MyModelManager() The model manager does a select_related() in the get() routine so that I always have the given foreign key field joined (I'll likely be referring to it often). When I call the get() routine, things work just as I expect: obj = models.MyModel.objects.get(pk=1) print(obj.group) # Doesn't hit the database a second time However, if I make a call to something like prefetch_related(), my custom manager gets discarded along the way: obj = models.MyModel.objects.prefetch_related('tags').get(pk=1) print(obj.group) # Hits the database a second time to get the group The reason becomes pretty clear when I print the types: x = models.MyModel.objects print(type(x)) # Yields <class 'base.models.TestCaseManager'> y = models.MyModel.objects.prefetch_related('tags') print(type(y)) # Yields <class 'django.db.models.QuerySet'> My Question Can I get chained calls to return my custom manager instance, rather than the default one? -
How to get search results in different boxes in html
I have this search engine that gets results based on a search query. I am new to html so I don't know how to manage to put the results in different result boxes and so what happens is that all of the results overlap each other. How can I put them in separate boxes? Thank you for any suggestion. This is my html: {% load static %} <!DOCTYPE html> <html> <head> <title>Ghibli Studio | People</title> <link rel="stylesheet" href="{% static 'core/species.css' %}"> </head> <body> <div class=" header"> </div> <div class="wrap"> <form action='/species' method="POST"> {% csrf_token %} <div class="search"> <input type="text" name="search" class="searchTerm" placeholder=" Type character name, gender, age, or eye color"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <button type="submit" class="searchButton"> <i class="fa fa-search" style="font-size:24px"></i> </button> </div> </form> </div> {% if species %} {% for s in species %} <div> <ul class="result"> <style> @import url('https://fonts.googleapis.com/css2?family=Dosis:wght@300&display=swap'); </style> <h4>{{s.Name}}</h4> <h5 style="color:lightslategray;"> Classification: {{s.Classification}} <br>Eye colors: {{ s.Eye_Colors }} <br>Hair colors: {{s.Hair_Colors}} </h5> </ul> {% endfor %} {% endif %} </div> </body> </html> This is my css: body { background: url(https://ak.picdn.net/shutterstock/videos/1007358814/thumb/1.jpg) no-repeat; background-size: cover; background-position: bottom; background-attachment: fixed; background-color: rgba(140, 35, 207, 0.8); } .header { background: url(https://upload.wikimedia.org/wikipedia/sco/thumb/c/ca/Studio_Ghibli_logo.svg/640px-Studio_Ghibli_logo.svg.png) no-repeat center; font-size: 14px; filter: invert(100%); width: 640px; height: 307px; … -
ValueError: Field 'id' expected a number but got 'asd'
I've looked for other questions, but they're just different errors. I've been developing a simple forum app, and now I've come to the part where I can comment on topics. But then I realized that I have been missing the ForeignKey relationship to the topic from the comment. Then, I created a new ForeignKey but as usual, it asks me to give a default value. I was just about to add Blank and Null true, but then my hands just automatically give asd as a default. Now even when I succeed in making migrations with makemigrations, I got this error when making migrate how can I make this right? -
How to prevent resend inputed data when page is refreshing(F5)/ Django
Pls, advice. How can I escape resending session data when refreshing page(F5) . Name of city is inputed and we see appropriate message. If I will refresh page(F5) that message still will be on the page. It's looks like during refreshing of the page previous data is sending from browser to our app. views.py: import requests from django.shortcuts import render, redirect from .models import City from .forms import CityForm def index(request): url = 'http://api.openweathermap.org/data/2.5/weather?q={}&units=imperial&appid=' err_msg = '' message = '' message_class = '' if request.method == 'POST': form = CityForm(request.POST) if form.is_valid(): new_city = form.cleaned_data['name'] existing_city_count = City.objects.filter(name=new_city).count() if existing_city_count == 0: r = requests.get(url.format(new_city)).json() if r['cod'] == 200: form.save() else: err_msg = 'City does not exist in the world!' else: err_msg = 'City already exists in the database!' if err_msg: message = err_msg message_class = 'is-danger' else: message = 'City added successfully!' message_class = 'is-success' form = CityForm() cities = City.objects.all() weather_data = [] for city in cities: r = requests.get(url.format(city)).json() city_weather = { 'city': city.name, 'temperature': int((r['main']['temp']-32)*5/9), 'description': r['weather'][0]['description'], 'icon': r['weather'][0]['icon'], } weather_data.append(city_weather) context = { 'weather_data': weather_data, 'form': form, 'message': message, 'message_class': message_class } return render(request, 'weather/weather.html', context -
Why is the bottom half of my site not showing up?
I added another div to bottom half of my site but it is not showing up. I can get it to show up in a separate web page, but not when I paste the same code to the bottom of this web page. Check out code, thanks in advance for you efforts. {% extends 'blog/navBarFooter.html' %} {% block content %} <!-- *************SHOWING UP ON WEBPAGE******************* --> <h1 class="text-center mt-3" id="blogdetailtitle">{{ blog.title }}</h1> <h5 class="text-center mt-3" id="blogdetailtitle">By: {{ blog.by }} | {{ blog.category }}</h5> <hr color="black"> <div class="col-lg-12 col-md-8"> <img id="imgLeft" src="{{ blog.pageOneImage.url }}" height=190 width=350> <p id="textLeft">{{ blog.pageOne | safe }}</p> <br> <br> <hr> <img id="imgRight" src="{{ blog.pageTwoImage.url }}" height=190 width=350> <p id="textLeft">{{ blog.pageTwo | safe }}</p> <br> <br> <hr> <img id="imgLeft" src="{{ blog.pageThreeImage.url }}" height=190 width=350> <p id="textLeft">{{ blog.pageThree | safe }}</p> <br> <br> <hr> <img id="imgRight" src="{{ blog.pageFourImage.url }}" height=190 width=350> <p id="textLeft">{{ blog.pageFour | safe }}</p> <br><br><br><br> <hr> </div> <!-- *************NOT SHOWING UP ON WEBPAGE******************* --> {% for blog in blogs %} <div class="row"> <div class="col-lg-4 col-md-6"> <img src="{{ blog.summaryImage.url }}" height=190 width=350> <p>{{ blog.category }}</p> <a href="{% url 'pageOne' blog.id %}"> <h2>{{ blog.title }}</h2> </a> <p>{{ blog.date|date:'M d Y'|upper }}</p> <p>{{ blog.summary }}</p> </div> {% endfor … -
Do not wait for database result in async view in Django
I have an async view in Django 3.1: async def log_click(request): await sync_to_async(Click.objects.create(author=request.user)) return HttpResponse('<html>Clicked</html>') Is it possible to improve the performance of this view by not needing to wait for Click instance's creation? I tried omitting await, however in this case the Click object is not created at all. I want this view to finish execution as fast as possible, but still get Click object created. -
GCP AppEngine Deployment Stuck at "Building and pushing image for service [default]"
Problem I'm hoping someone has experience a similar issue. I have a python web-application deployed on Google Cloud Platform's flexible application service. I've updated this site dozens of times before without significant issue. A few days ago, I went to apply a hotfix but when I deployed the app through the GCP SDK, it stopped at "Building and pushing image for service [default]". While this step has typically taken 5 minutes at the most, this time I've left it running for several hours without any change in the console. Attempted Solutions I've run the gcloud components update. I've waited a few days to see if the problem resolved itself on a different day... I'm frankly at a loss. There aren't any error logs to be found and my google searching hasn't come up with any similar problems. -
Is there any way to accept only business/company emails that signup through Google Signup in django?
I want to restrict users with simple email by accessing the website, but also i would like to keep the sign up from google form, and i want to restrict it only to users who have a company email with gsuite. I am using social-auth-app-django==3.1.0 with django==3.0.2. -
Registration Form not saving data in Profile Model, using extended Django User model
Recently i am facing a problem in registration. I have made a ** accounts** app in my project for registrations. I don't want to save data in default **User** model in dB. So I have extended **User** model with **OneToOne** relationship with **Profile** model and trying to save the data into "Profile" model but when I submitting the form I don't get any error but data don't save in "Profile" DB. here is my models.py where I make OneToOne Relationship with default "User" model. from django.db import models from django.contrib.auth.models import User # Create your models here. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) phone=models.CharField(max_length=20) address=models.CharField(max_length=150) def __str__(self): return self.user.username I am trying to make ProfileForm form and InfoProfileForm form here to get the form data in forms.py. from django import forms from django.contrib.auth.models import User from .models import Profile from django.contrib.auth.forms import ReadOnlyPasswordHashField class ProfileForm(forms.ModelForm): password = forms.CharField(max_length=20, widget=forms.PasswordInput) #form = ProfileForm(data=request.POST, user=request.user) class Meta: model = User fields=('username','email','password') #extra info class InfoProfileForm(forms.ModelForm): class Meta: model = Profile fields = ('phone','address') Here is my Views.py where I am trying to merge two models (default User model and Profile model) from django.shortcuts import render from django.http import HttpResponse, JsonResponse # Create … -
uwsgi ImportError: No module named site
I've looked at the other similar questions, but mine is a different one. I tried to migrate a django app from one server to a new server and copied the entire file system of the app from the old server to the new server, including the environment folder. I have no problems to start nginx on the new server, but when I tried to start uwsgi, I got the errors as shown below. $ sudo uwsgi --ini /home/devuser/webapps/myproj-env/myproj/server/uwsgi/myproj.ini [uWSGI] getting INI configuration from /home/devuser/webapps/myproj-env/myproj/server/uwsgi/myproj.ini *** Starting uWSGI 2.0.9 (64bit) on [Mon Aug 24 14:13:03 2020] *** compiled with version: 4.4.7 20120313 (Red Hat 4.4.7-11) on 31 January 2015 12:37:00 os: Linux-3.10.0-1127.13.1.el7.x86_64 #1 SMP Fri Jun 12 14:34:17 EDT 2020 nodename: rhlnx01 machine: x86_64 clock source: unix detected number of CPU cores: 2 current working directory: /home/devuser/webapps/myproj-env/bin detected binary path: /home/devuser/webapps/myproj-env/bin/uwsgi !!! no internal routing support, rebuild with pcre support !!! setgid() to 2147186151 set additional group 986 (nginx) set additional group 20001 (spinner) setuid() to 2122832 chdir() to /home/devuser/webapps/myproj-env/myproj/server/uwsgi//../.. *** WARNING: you are running uWSGI without its master process manager *** your processes number limit is 31117 your memory page size is 4096 bytes detected max file descriptor number: 1024 … -
Querying with id and other fields vs querying with id and checking others after
For a large database, it's faster (and thus better) to grab the object with the id only and then check if the user matches, right? # Option A post = get_object_or_404(Post, id=post_id, owner=request.user) # Option B post = get_object_or_404(Post, id=post_id) if post.owner != request.user: raise Http404() -
Django KeyError when session variable exists
I'm getting a KeyError because the session variable is not found. However, I know the session variable exists and is displayed in the prior page. I tried to update settings.py with SESSION_ENGINE = ''django.contrib.sessions.backends.db' As explained in this question, but it didn't work. Django Session KeyError when key exists Python 3, Django 2.7 -
Select instance/row with max field/column value per with field/column (group by)
So, I have these models: class Computer(models.Model): hostname = models.CharField(primary_key=True, max_length=6) <other computer info fields> class ComputerRecord(models.Model): id = models.AutoField(primary_key=True) pc = models.ForeignKey(Computer, on_delete=models.CASCADE) ts = models.DateTimeField(blank=False) <other computerrecord info fields> I want to get the row / computerrecord instance that has the max ts for each pc (Computer model) In sql would be something like this: SELECT hub_computerrecord.* FROM hub_computerrecord JOIN ( SELECT pc_id, MAX(ts) AS max_ts FROM hub_computerrecord GROUP BY pc_id ) AS maxs ON hub_computerrecord.pc_id = maxs.pc_id WHERE hub_computerrecord.ts = maxs.max_ts; -
if statmen not working well in django please help me
I want to show and hide HTML elements depends on the content of the data I receive after pressing the button. data will be created after pressing the button (its output of another py file) but the if statement not working {% if data == 'empty' %} its shows the image not the massage i want. {% load static %} <html> <link rel="stylesheet" type="text/css" href="{% static 'css/main.css' %}"> <head> <title> Analyze your tweets </title> </head> <br> <br> <h1 class="text-light">Analyze Emotions in Your 2020 Tweets &#128526; </h1> <br> <br> <form action="/external/" method="post"> <div class="outter" aria-label="actionButtons"> <div class="inner"> {% csrf_token %} <label>Enter your @</label> <input id="username" type="text" name="param" placeholder="Username" required > <input id="btnSearch" type="submit" value="Analyze" onclick="show();"> </div> </form> </div> <div class="outter"> <div class="inner"> <div class="lds-ellipsis" id="load" style="display: none;"><div></div><div></div><div></div></div> </div> </div> <div class="outter"> {% if data %} {% if data == 'empty' %} <h5 style="font-family:Lato; color: azure; font-size: 18;">Sorry the username you looking for is either private or doesn't exist </h5> {% endif %} <div class="inner"> <h5 style="font-family:Lato; color: azure; font-size: 18;">Here is your result <span style="color:black;">@{{data}}</span></h5> <img id="pic" src="{% static 'images/graph.png' %}" width="640" height="480" /> </div> {% endif %} </div> <br> <br> <div class="outter2"> <h5>This website will <u>not</u> violate your Account Privacy.</h5> … -
Unable to send messages form Wagtail form using gmail
I'm trying to use my Gmail account to receive messages form my Wagtail/Django app. The messagesget added to Forms in admin panel and get printed in the console, however, they do not get send to and from my gmail account. My settings ass below: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'mg@gmail.com' EMAIL_HOST_PASSWORD = 'Password$' EMAIL_USE_TLS = True EMAIL_USE_SSL = True DEFAULT_FROM_EMAIL ='noreply@mysite.com' EMAIL_TO = 'mg@gmail.com' I tried to overwrite sent_mail function in ContactForm(AbstractEmailForm) and replace from_address and to_address with DEFAULT_FROM_EMAIL and EMAIL_TO. No success. -
How to disable next URL parameter while using login_required decorator in django?
I have the following project folder structure in Django: . |_blog/ |_django_blog/ |_users/ |_manage.py I have the following in django_blog/urls.py: from django.contrib import admin from django.contrib.auth import views as auth_views from django.urls import path, include from users import views as user_views urlpatterns = [ path('admin/', admin.site.urls), path('',include('blog.urls')), path('profile/',user_views.profile,name='profile'), path('register/',user_views.register,name='register'), path('login/',auth_views.LoginView.as_view(template_name='users/login.html'),name='login'), path('logout/',auth_views.LogoutView.as_view(template_name='users/logout.html'),name='logout'), ] And I have the following decorated view in users/views.py: from django.contrib.auth.decorators import login_required @login_required def profile(request): return render(request,'users/profile.html') And following constants in django_blog/settings.py: LOGIN_REDIRECT_URL = 'blog-home' LOGIN_URL = 'login' Now if user is not logged in and tries to access /profile/ URL he will be redirected to login page with next=/profile/ paramter passed in to the URL. After the user signs in, it redirects the user to /profile/. But I want the user to be redirected to the homepage instead which is the default behaviour of signing in from /login/ URL. How should I implement that functionality? -
Django Decimal field with value Decimal(0.00) is displayed as 0E-10 in the Django Admin Inline
Model Definition. class ExampleModel(BaseModel): price = models.DecimalField(max_digits=20, decimal_places=10) margin = models.DecimalField(max_digits=20, decimal_places=10) If the user saves margin or price as "0" it would be displayed as "OE-10" on the next page load. Screenshot is from DjangoAdmin. -
400 Bad Request while updating Django model with form-data
I am trying to update my Django model with axios and i send data as form-data. I use PATCH method while i want to make changing fields optional. This however is not working and i got 400 Bad Request error .There is also DRF serializer and APIview in the backend. Only field that i can update through form is my imagefield. What could cause error here? How form-data gets sent: handleFormSubmit = (event) => { event.preventDefault(); let form_data = new FormData(); form_data.append('name', event.target.elements.name.value); form_data.append('email', event.target.elements.email.value); form_data.append('location', event.target.elements.location.value); form_data.append('sport', this.state.sport); form_data.append('image', this.state.file); const profileID = this.props.token let url = `http://127.0.0.1:8000/api/profile/${profileID}/update` axios.patch(url, form_data, { headers: { 'content-type': 'multipart/form-data' } }) .then(res => console.log(res)) .catch(error => console.err(error)); } In my UpdateAPIView i also have parser_classes which should handle issue, but it doesn't class ProfileViewUpdate(generics.UpdateAPIView): queryset = Profile.objects.all() serializer_class = ProfileSerializer lookup_field = 'token' lookup_url_kwarg = 'pk' parser_classes = (MultiPartParser, FormParser) Thanks in advance! -
Django: Create zipfile from S3 using django-storage
I use django-storages and have user related content stored in folders on S3. Now I want users to have the ability to download all their files at once, preferably in a zip file. All the previous posts related to this are old or not working for me. The closest to working code I have so far: from io import BytesIO import zipfile from django.conf import settings from the_bookie.tax_returns.models import IncomeTaxReturn from django.core.files.storage import default_storage class DownloadIncomeTaxFiles(View): def get(self, request, id): itr = IncomeTaxReturn.objects.get(id=id) files = itr.attachments zfname = 'somezip.zip' b = BytesIO() with zipfile.ZipFile(b, 'w') as zf: for current_file in files: try: fh = default_storage.open(current_file.file.name, "r") zf.writestr(fh.name, bytes(fh.read())) except Exception as e: print(e) response = HttpResponse(zf, content_type="application/x-zip-compressed") response['Content-Disposition'] = 'attachment; filename={}'.format(zfname) return response This creates what looks like a zipfile but the only content it has is '<zipfile.ZipFile [closed]>' I got many different results, mainly with errors like zipfile expecting string or bytes content while a FieldFile is provided. At this point I'm completely stuck. -
FileNotFoundError: A json file not found after pushing it to heroku
I am working on a website. For this website I have to create a table which shows the time of the meeting and the participants of it. I am writing the code of site using Django. For the table I have a data on a .json file. When I run the server locally it works fine and when I push it to heroku it raises FileNotFoundError. I found this question which faces with the similar problem but the answer shows how to log something, but I need .json file for data. My django app directory: 66 admin.py 100 apps.py <DIR> migrations 60 models.py 3,332 schedule_of_teams.json <DIR> static <DIR> templates 63 tests.py 333 urls.py 807 views.py So I have a view function in views.py file: def schedule_of_teams(request): with open('./schedule_of_teams.json',encoding='utf-8') as f: context = json.load(f) context['title'] = 'Yarış cədvəli' return render(request,'schedule_of_teams.html',context) And open context manager raises the error: FileNotFoundError at /schedule_of_teams/ [Errno 2] No such file or directory './schedule_of_teams.json/' So why is this happening? Why it works fine when I run python manage.py runserver with localhost but when I push to heroku it raises this exception? Is heroku ignores .json files? By the way, I do not have *.json on my .gitignore …