Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Websocket connection getting closed automatically when sending data from an external api
I am new to django channels and trying to send an api response to an active websocket connection, but as soon as I do it, it is getting disconnected. can someone please check this code and tell me what I did wrong? Thanks inside api view: channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)( 'chat-{}'.format(str(chat.id)), { 'type': 'external.message', 'text': json.dumps(serializer.data), } ) in consumer def external_message(self, event): print(event) self.send({ 'type': 'websocket.send', 'text': event['text'] }) The event is getting printed, but the connection is getting closed. -
UNIQUE constraint failed: restaurant_payment.transaction_id in django 3
I want to make payment for my project. when clicked button Make Payment in my checkout, field customer and order will be filled automatically and redirect to template PaymentView for enter customer full name, and proof of payment. But i get this error, anybody can help me ? enter image description here views.py def makePayment(request): customer = request.user.customer order = Order.objects.get(customer=customer) payment, created = Payment.objects.get_or_create( order=order, customer=customer) payment.save() print(order) return redirect('restaurant:payment') class PaymentView(CreateView): model = Payment form_class = PaymentForm template_name = 'restaurant/payment.html' def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) if self.request.user.is_authenticated: customer = self.request.user.customer order, created = Order.objects.get_or_create( customer=customer, complete=False) items = order.ordermenu_set.all() cartItems = order.get_cart_items else: items = [] order = {'get_cart_total': 0, 'get_cart_items': 0} cartItems = order['get_cart_items'] context['items'] = items context['order'] = order context['cartItems'] = cartItems context['page_title'] = 'Payment' return context def get(self, *args, **kwargs): if self.request.user.is_authenticated: customer = self.request.user.customer order, created = Order.objects.get_or_create( customer=customer, complete=False) items = order.ordermenu_set.all() cartItems = order.get_cart_items else: items = [] order = {'get_cart_total': 0, 'get_cart_items': 0} cartItems = order['get_cart_items'] if cartItems == 0: return redirect('restaurant:order') else: return super().get(*args, **kwargs) in function makePayment, used for fill in the fields customer and order, and will be redirect to PaymentView. urls.py from django.urls import … -
Return JSONresponse in custom authentication class django
I am trying to write a custom authentication class inside a app called helpers which should be called before every api request Settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'helpers.authentication.ExampleAuthentication', ] } helpers/authentication.py class ExampleAuthentication(authentication.BaseAuthentication): def authenticate(self, request): IDP_ADDRESS = "https://localhost:8000/api/environments.json" # header = request.headers.get('Authorization') header = "Token token=portal_toke" if header is not None: response = requests.get(IDP_ADDRESS, headers={"Authorization": header}) print(response.status_code) if response.status_code != requests.codes.ok: if response.status_code != requests.codes.ok: return JsonResponse({ "status": "fail", "message": "unauthorized" }) I need to return the json response once validation fails. But am getting below error File "D:\Users\service\env\lib\site-packages\rest_framework\request.py", line 387, in _authenticate self.user, self.auth = user_auth_tuple ValueError: not enough values to unpack (expected 2, got 1) -
Django queryset to order by list of item matches in one of the fields
Im working on a queryset which requires a complex ordering of queryset. here is my model.py class ItemTable(models.Model): item_name = models.CharField(max_length=50) class tableA(models.Model): user = models.OneToOneField(User, primary_key=True) items = models.ManyToManyField(ItemTable, on_delete=models.CASCADE) class tableB(models.Model): type = models.CharField(max_length=50) items = models.ManyToManyField(ItemTable, on_delete=models.CASCADE) Im not sure how do I do a query on tableB to with specific items passed from the request.body and then match/compare the items from tableA and replace the entire items values on tableB obj with only matching queryset and order them based on the counts on the replaces items list for each obj. Eg: tableB_qs = tableB.objects.filter(items__in=["list_of_ids_from_request_body"]) items_list_from_tableA = tableA.objects.get(id=request.user).items then --> Compare items_list_from_tableA with tableB_qs each object property "items". then -->> replace the matched only ingredients to the items list for each obj in tableB qs. then -->> Order the final qs based on the count of items for an obj in tableB qs -
How to redirect a local app to a url on django?
I have a local app running localy on localhost:9000, and my django website (running on docker) on localhost:8000 which is exposed to the internet i.e. mydomain.com. How could redirect this local webapp for exemple to mydomain.com/webapp. I cannot modify the local webapp at all, consider it a black box that can only ouput on localhost:9000. Using Django, how can I do it ? -
checking which decimal is bigger django
Im having problem with one line of code... Im trying to check which decimal is greater, i checked few answers from stackoverflow and they didnt work (probably cuz they were from 7 years ago :P) anyways here is my view: auction = all_auctions.objects.get(id= my_id) comment_num = auction.comments.all().count() all_comments = auction.comments.all() context = { "auction": auction, "bid_auction": auction.bid.all(), "comment_num": comment_num, "all_comments": all_comments } if request.method == "POST" and "bid" in request.POST: if request.user.is_authenticated: highest_bid = request.POST["bid"] if not Decimal(highest_bid) <= Decimal(int(auction.bid.all().reverse()[0])): all_bid = bids.objects.create(bid = highest_bid) auction.bid.add(all_bid) if request.method == "POST" and "watch"in request.POST: if request.user.is_authenticated: if auction not in request.user.watchlist.all(): request.user.watchlist.add(auction) else: request.user.watchlist.remove(auction) if request.method == "POST" and "comment" in request.POST: comment = request.POST["comment"] if request.user.is_authenticated: comment_now = comments.objects.create(comment = comment) auction.comments.add(comment_now) return render(request, "auctions/dynamic_auction.html", context) and there is the problematic line: if not Decimal(highest_bid) <= Decimal(int(auction.bid.all().reverse()[0])): in models: from django.contrib.auth.models import AbstractUser from django.db import models class comments(models.Model): comment = models.TextField(blank=False) class bids(models.Model): bid = models.DecimalField(decimal_places = 2, max_digits = 100000) class all_auctions(models.Model): category = models.CharField(max_length= 14, default = "none") title = models.CharField(max_length= 14) description = models.TextField(blank=False) photo_url = models.CharField(max_length= 500000) bid = models.ManyToManyField(bids, blank = True, related_name = "bid_auction") comments = models.ManyToManyField(comments, blank = True, related_name = "comments") … -
Django Signal request_finished get user instanse
I try to understand Signals in Django. I am creating project for DRF. from django.dispatch import receiver from django.contrib.auth.signals import user_logged_in from django.core.signals import request_finished For this Signal I can catch user @receiver(user_logged_in) def last_user_login(sender, request, user, **kwargs): print('User **{}** logged in'.format(user)) And I want to catch user for this signal, but it's impossible as I understood. @receiver(request_finished) def last_user_request(sender, **kwargs): print('User made request') My target: catch last user request and write this data to db. Could someone help me? Thanks. -
it is problem when i open runserver and i dont understand error [closed]
RelatedObjectDoesNotExist at / User has no customer. Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.1.7 Exception Type: RelatedObjectDoesNotExist Exception Value: User has no customer. Exception Location: C:\Users\Dell\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\fields\related_descriptors.py, line 421, in get Python Executable: C:\Users\Dell\AppData\Local\Programs\Python\Python39\python.exe Python Version: 3.9.1 Python Path: ['C:\Users\Dell\Desktop\ecommerce', 'C:\Users\Dell\AppData\Local\Programs\Python\Python39\python39.zip', 'C:\Users\Dell\AppData\Local\Programs\Python\Python39\DLLs', 'C:\Users\Dell\AppData\Local\Programs\Python\Python39\lib', 'C:\Users\Dell\AppData\Local\Programs\Python\Python39', 'C:\Users\Dell\AppData\Local\Programs\Python\Python39\lib\site-packages'] Server time: Mon, 15 Mar 2021 11:58:17 +0000 -
Cannot use ArrayField from Djongo Models
I'm trying to make an app with Django using MongoDB as my database engine, so I'm using Djongo as ORM. In my models, I have defined a Client class, which is intended to contain an array of Profiles (authorized people to login in name of client). In the Djongo Documentation, it says one can use the ArrayField class in models in order to store an array to the database. The point is that I followed the example in the documentation (even I tried to copy without changing anything) and it isn't working. When running the view, I always get this error: "Value: Profile object (None) must be an instance of <class 'list'>" I have the following models.py: from django import forms from djongo import models class Profile(models.Model): _id=models.ObjectIdField() fname = models.CharField(max_length=25) lname = models.CharField(max_length=50) email = models.EmailField() password = models.CharField(max_length=16) class Meta: abstract=True class ProfileForm(forms.ModelForm): class Meta: model = Profile fields =( 'fname', 'lname', 'email', 'password', ) class Client(models.Model): #informacion del cliente _id = models.ObjectIdField() name = models.CharField(max_length=256) authorized = models.ArrayField( model_container=Profile, model_form_class=ProfileForm ) objects = models.DjongoManager() class ClientForm(forms.ModelForm): class Meta: model = Client fields = ( 'name', 'authorized' ) I have a form that uses ClientForm, and the view … -
Get Element inside Array With Django-MongoDB (Djongo)
I am using Django with MongoDB as my database. I create a model (MyObject) and one field is an ArrayField type that contains in wich entry Json Fields. For that I created an abstract model. So my models.py : class MyObject(models.Model): ... myArrayField = models.ArrayField(model_container=NIC, null=True, blank=True, default=[]) ... class MyAbstractObject(models.Model): field1 = models.CharField(null=True, blank=True, max_length=100, default="") field2 = models.IPAddressField(blank=True, null=True, default="") class Meta: abstract = True In mongoDB I have: MyObject: { ... myArrayField: [{field1: "abc", field2: "1.1.1.1"}] ... } Now I want to get the element that have the value "1.1.1.1", how can I do that? I try: q1 = MyObject.objects.filter(myArrayField__contains='1.1.1.1') q2 = MyObject.objects.filter(myArrayField_0_field2='1.1.1.1') q3 = MyObject.objects.filter(myArrayField__contains={'field2':'1.1.1.1}) Can you help me? -
how to send multiple images to user in django?
I am new to Django I wanted to make an app that will send assignment files from teacher to students but I have no idea how to implement it with Django please anybody has an idea about this please help me. -
I'm trying to get in from the main page to another page and there's a problem with slug/url What's the problem with what I wrote?
I write a project of a list of films with their details(IMDB), when I click on the image of a film he doesn't go to the page of that film, i do not understand where the problem is in url on html file or in the models ? husdfguejhfuwkjhruefgwdujshfjrwueruyiwyerwhiuiuen 8yryeriwkeuriwur yehikyrhiwkyrew fyeier Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/movies/%7B$%20url%20'movies:movie_detail'%20movie.slug%20%25%7D Using the URLconf defined in django_movie_center.urls, Django tried these URL patterns, in this order: admin/ movies/ [name='movie_list'] movies/ category/<str:category> [name='movie_category'] movies/ language/<str:lang> [name='movie_language'] movies/ search/ [name='movie_search'] movies/ <slug:slug> [name='movie_detail'] movies/ year/<int:year> [name='movie_year'] ^static/(?P<path>.*)$ ^media/(?P<path>.*)$ The current path, movies/{$ url 'movies:movie_detail' movie.slug %}, didn't match any of these. models.py: from django.db import models from django.utils.text import slugify # Create your models here. CATEGORY_CHOICES = ( ('action','ACTION'), ('drama','DRAMA'), ('comedy','COMEDY'), ('romance','ROMANCE'), ) LANGUAGE_CHOICES = ( ('english','ENGLISH'), ('german','GERMAN'), ('hebrew','HEBREW') ) STATUS_CHOICES = ( ('RA' , 'RECRNTLY ADDED'), ('MW' , 'MOST WATCHED'), ('TR' , 'TOP RATED'), ) class Movie(models.Model): title = models.CharField(max_length=100) description = models.TextField(max_length=1000) image = models.ImageField(upload_to='movies') category = models.CharField(choices=CATEGORY_CHOICES , max_length=10) language = models.CharField(choices=LANGUAGE_CHOICES, max_length=10) status = models.CharField(choices=STATUS_CHOICES, max_length=2) cast = models.CharField( max_length=100) year_of_production = models.DateField() views_count = models.IntegerField(default=0) movie_trailer = models.URLField() slug = models.SlugField(blank=True, null=True) def save(self, *args, **kwargs): if … -
How to convert webscraping into django api?
I'm trying to scrape some data on two websites. I successfully scraped it. I also want to develop an API using this scraped data using Django. But when I try to display the scraped data in JSON format in Django. It only shows an empty list. Below I attached my code snippets. from django.shortcuts import render from bs4 import BeautifulSoup import requests import re import json import time data = [] def getURL(url): url = url.replace(' ', '-').lower() for char in url: if char in "?.!:;|/[]&()": url = url.replace(char, '-') if char == "'" or char == ",": url = url.replace(char, '') decodeUrl = re.sub(r'-+', '-', url) # check whether the url is up or not parsedUrl = "http://www.tutorialbar.com/" + decodeUrl + "/" if requests.head(parsedUrl).status_code == 200: return parsedUrl urls = ['https://www.discudemy.com/all', 'https://www.discudemy.com/all/2'] for url in urls: source = requests.get(url).text soup = BeautifulSoup(source, 'html5lib') # print(soup) for content in soup.find_all('section', class_="card"): # print(content) try: language = content.label.text header = content.div.a.text day = content.find('span', class_="category").text i = content.find('div', class_="image") img = i.find('amp-img')['src'] image = img.replace('240x135', '750x422') description = content.find('div', class_="description").text.lstrip() myURL = getURL(header) udemyURL = requests.get(myURL).text udemySoup = BeautifulSoup(udemyURL, 'html5lib') udemylink = udemySoup.find_all('a', class_="btn_offer_block re_track_btn")[0]["href"] entry = { 'language': language, 'header': … -
Django modeltranslation TranslationOptions add external attribute to a model field
I have to add a unique=True attribute to the translated model fields, excluding the original field. E.x.: I have a model class News(models.Model): title = models.CharField(max_length=255) text = models.TextField() and I add such translation option: from modeltranslation.translator import translator, TranslationOptions from .models import News class NewsTranslationOptions(TranslationOptions): fields = ('title', 'text') translator.register(News, NewsTranslationOptions) My project setting file contains language settings: LANGUAGE_CODE = 'ru' gettext = lambda s: s LANGUAGES = [ ('ru', gettext('Russian')), ('en', gettext('US English')), ] MODELTRANSLATION_LANGUAGES = ('ru', 'en',) USE_I18N = True USE_L10N = True After applying migrations, I will get such fields in my news table in db: title, title_en, title_ru, text, text_en, text_ru, and I want to add a unique option to a fields title_en and title_ru, excluding title field. How can I do this without manual adding required attribute to a migration file? -
Celery task and mysql
I will try to simplify this question as much as possible. I have a django project that uses celery tasks for some async job. For simplicity, let's say I have an order. In task, I update the order from waiting to in progress. @task(bind=True) # pylint: disable=E1102 def mytask(self, id: str): """This is my custom task """ order = Order.objects.get(pk=id) order.status = IN_PROGRESS order.save() print(order.status) # This returns 'in progress' But after the task is done, it revers the state to waiting and I'm not sure why. Could be transaction isolation of MySQL, but what would be a way to do this most cleanly there? -
Reverse for 'single' with arguments '('',)' not found. 1 pattern(s) tried: ['(?P<slug>[-a-zA-Z0-9_]+)/$']
I run this code and it works perfectly. I opened it a few days later again and it's throwing an error in all pages except the add/ page. Error code: django.urls.exceptions.NoReverseMatch: Reverse for 'single' with arguments '('',)' not found. 1 pattern(s) tried: ['(?P<slug>[-a-zA-Z0-9_]+)/$'] I tried reading other similar issues here but they didn't solve the problem models.py class Core(models.Model): title = models.CharField(max_length=200) excerpt = models.TextField() author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='core') slug = models.SlugField(max_length=100, unique=True) updated = models.DateTimeField(auto_now=True) published = models.DateTimeField(default=timezone.now) def get_absolute_urls(self): return reverse('core:single', args=[self.slug]) def __str__(self): return self.title class Meta: ordering = ['-published'] urls.py app_name = 'core' urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('add/', views.AddView.as_view(), name='add'), path('posts/', views.PostsView.as_view(), name='posts'), path('<slug:slug>/', views.SingleView.as_view(), name='single'), ] views.py class IndexView(ListView): model = Core template_name = 'core/index.html' context_object_name = 'index' class SingleView(DetailView): model = Core template_name = 'core/single.html' context_object_name = 'post' class PostsView(ListView): model = Core template_name = 'core/posts.html' context_object_name = 'post_list' class AddView(CreateView): '''Basically a form. Someone types in and add new post''' model = Core template_name = 'core/add.html' fields = '__all__' #take all the fields from the db and put that into a form success_url = reverse_lazy('core:posts') single.html {% extends 'core/base.html' %} {% block content %} <div class="container"> <div class="row"> <div class="col-12 … -
Regular load of data via CSV into django data model
I am writing a web application that will regularly pull data in the CSV format from different sources from the internet. This data will then be aggregated using django and made visible via a frontend so the data can be manipulated. Is it better to create a function that will convert the CSV file into a jason format and then loaded into the django model or is it better to directly load the CSV content into a django model. I was thinking that by first converting it to jason the data could be reused by another app at a later point in time. -
AttributeError: 'Account' object has no attribute 'exclude'
I build the notification system, and I want to exclude the author of the post when adding like to their own post so of receiving the notification, I facing this problem my view def add_remove_like(request, pk): data = {} video = Video.objects.get(pk=pk) if request.method == "POST": user = request.user if video.likes.filter(id=user.id).exists(): liked = False video.likes.remove(user) else: video.likes.add(user) instance = video.author content_type = ContentType.objects.get_for_model(instance) try: notify = Notify.objects.create(from_user=request.user.exclude(from_user=instance), target=instance, content_type=content_type, redirect_url=f"{settings.BASE_URL}/video/account/video/{video.pk}", object_id=instance.pk, verb=f"{request.user} added like to your video" ) notify.timestamp = timezone.now() notify.save() -
How to order by model property value?
How to order by model property? class Item(models.Model): name = models.CharField() ... @property def permissions_count(self) -> int: .... return permissions_count qs = Item.objects.all() if order_by == 'permissions_count': qs = qs.order_by('permissions_count') return qs I see this error: Cannot resolve keyword 'permissions_count' into field. Choices are: -
pytest-django & django restramework - prevent Rollback
i'm using django with restframework to create my apps.. For testing i'm using django-pytest.. for db i'm using my real development environment db - i do not create a new one for testing.. (i need to use the data out of my real dev db) Now i have created my test classes and method.. @pytest.mark.django_db class TestCreateNewRecords: """ Test class for creating new record.. """ @pytest.mark.parametrize('test_data', EXAMPLE_DATA) def test_record_creation(self, test_data): """Test create of records""" input_json = test_data[0] should_pass = test_data[1] api = ApiCaller() user = Users.objects.get(username='testuser') user.is_admin = False user.save() user.user_permissions.clear() # Now assign the correct permission.. user.user_permissions.add(Permissions.objects.get(name='manager') assert user.user_permissions.count() == 1 acc_ci = Accounting.objects.get(name='mytest') status_code, resp_json = api.make_request(endpoint=f'accounting/acc/{acc_ci.id}/add-accounting', method='POST', data={'data': input_json}) assert status_code == 201 My Problem is now, that the assignment of the correct permission will be done correctly. BUT - when calling the api endpoint (where the assigned permissions will be checked) the api return a 403. After debugging a while, i realized, that all the changes which were made during a test run, is not reflected in the real DB.. I found an article where they explained that, every db action in a test will be done in an separate transaction and rolled back after every … -
HTMX for messages from the backend
I want to use HTMX to show messages from django. There are two easy ways I can think of: using django-messages just replying with a JSON to a request both is fairly easy on the django side, but I am not so sure on how to proceed on the htmx side. In django the response could be simple (case 1): class TestView(TenmplateView): template_name = "index.html" def get(self, request, *args, **kwargs): messages.success(request, "there was no error") return HttpResponse("") or, (case 2) with JsonResponse: class TestView(TenmplateView): template_name = "index.html" def get(self, request, *args, **kwargs): return JsonResponse({'success': False, 'err_code': 'there was an error'}) in the first case I could easily post messages in the template like this: <div id='messages'> {% if messages %} {% for message in messages %} <div class="alert alert-{{ message.tags }} alert-dismissible fade show"> {{ message }} <button type="button" class="close" data-dismiss="alert">&times;</button> </div> {% endfor %} {% endif %} </div> But now I am struggeling with the HTMX part of the method and would appreciate some help :) -
How can we compare request object in django?
I am building a website in django where user can upload their apk and the app will be modified by server and it return back the modified apk but there i have to limit user to upload 1 apk from 1 category at a time. if(request.FILES["app"]): name = request.FILES["app"] elif(request.FILES["lib"]): name = request.FILES["lib"] elif.... And more But i am facing some multivalue dict key error anyone knows any better solution for this please suggest me. -
Trying to send response from an api to an active websocket connection
I am trying to push a api response to an active websocket, I have these functions in the consumer def send_message_from_api(message, chat): channel_layer = get_channel_layer() print('chann', channel_layer) chat_room = f"chat_{chat}" async_to_sync(channel_layer.group_send)( chat_room, { 'type': 'external.message', 'text': json.dumps(message), } ) def external_message(self, event): print('test', message) message = event['message'] self.send(text_data=message) and in the view function I call, Consumer.send_message_from_api(serializer.data, chat.id) I am new to websockets and django channels, the function def external_message is not getting called while I run the code. Can someone please help with this? Thanks -
Problem with making python DJANGO app working on hosting
My logs after error looks like that, but i dont have any idea what can i do.... My application is working perfectly on localserver, the site of hosting says that its problem with application??? I tried putting there only hello world, but it send same error. Traceback (most recent call last): File "/usr/local/lib/ruby/gems/2.5/gems/passenger-6.0.7/src/helper-scripts/wsgi-loader.py", line 379, in <module> app_module = load_app() File "/usr/local/lib/ruby/gems/2.5/gems/passenger-6.0.7/src/helper-scripts/wsgi-loader.py", line 80, in load_app return imp.load_source('passenger_wsgi', startup_file) File "/usr/local/lib/python3.8/imp.py", line 171, in load_source module = _load(spec) File "<frozen importlib._bootstrap>", line 702, in _load File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/usr/home/perqu/domains/perqu.usermd.net/public_python/passenger_wsgi.py", line 7, in <module> from django.core.wsgi import get_wsgi_application ModuleNotFoundError: No module named 'django' Traceback (most recent call last): File "/usr/local/lib/ruby/gems/2.5/gems/passenger-6.0.7/src/helper-scripts/wsgi-loader.py", line 379, in <module> app_module = load_app() File "/usr/local/lib/ruby/gems/2.5/gems/passenger-6.0.7/src/helper-scripts/wsgi-loader.py", line 80, in load_app return imp.load_source('passenger_wsgi', startup_file) File "/usr/local/lib/python3.8/imp.py", line 171, in load_source module = _load(spec) File "<frozen importlib._bootstrap>", line 702, in _load File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/usr/home/perqu/domains/perqu.usermd.net/public_python/passenger_wsgi.py", line 7, in <module> from django.core.wsgi import get_wsgi_application ModuleNotFoundError: No module named 'django' -
Is it possible to access to a pickle file saved in a directory in Django views?
Let me explain, here is my problem: In order not to get bothered with a database, I saved two machine learning models in .pickle in a folder in my Django project. Then in the corresponding views.py I want to open and use this model. The fact is that all this works well when I run the server locally but once deployed on heroku, impossible to access these models and the site does not work. Do you have an idea, is it possible to use this method once deployed or do I have to save them in a database project files organization : main_folder > models_folder > saved_models_folder > my_model.pickle (here the model that I want to open) app_folder > views.py ( here is the file in wich I try to open the .pickle model) Actually I have this code, but it can't work because I'm not in the models folder when I try to open it. def open_model(file_name): base_dir = 'models_folder\\saved_models_folder' file_path = os.path.join(base_dir, file_name) if os.path.exists(file_path): print("Loading Trained Model") model = pickle.load(open(file_path, "rb")) else: print('No model with this name, check this and retry') model = None return model If someone has a little idea I am greatly interested Thanks.