Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Reverse for 'listing' with arguments '('',)' not found. 1 pattern(s) tried: ['listing/(?P<listing_id>[0-9]+)$']
the error occurs at views.py in def categoriess when i passed listingss as "listings"to return render(request, "auctions/index.html", {"listings": listingss, 'categories': 'True'}) the program runs fine when listingss=auction_listings.objects.all() but not listingss=auction_listings.objects.all().values_list('category', flat=True) urls.py from django.urls import path from . import views urlpatterns = [ path("watchlist", views.watchlist, name='watchlist'), path("category/<str:category_>", views.category, name="category"), path("comment/<int:listing_id>", views.comment, name="comment"), path("categories", views.categoriess, name="categories") ] views.py from django.contrib.auth import authenticate, login, logout from django.db import IntegrityError from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render from django.urls import reverse from django.contrib.auth.decorators import login_required from django import forms from .models import User, auction_listings, bids, comments from django.core.exceptions import ObjectDoesNotExist def categoriess(request): listingss = list( set(auction_listings.objects.all().values_list('category', flat=True))) return render(request, "auctions/index.html", {"listings": listingss, 'categories': 'True'}) html where I link it <li class="nav-item"> <a class="nav-link" href="{% url 'categories' %}">Categories</a> </li> auctions/index.html {% extends "auctions/layout.html" %} {% block body %} {%for listing in listings%} <div class='border'> <a href="{% url 'listing' listing.id %}"> <h3> {{listing.name}}</h3> <a/> <img src="{{listing.image_url}}" alt="{{listing.name}} photo" style="width:200px;"> {% if listing.bids.last %} <big><b>price: {{listing.bids.last}}</b></big> {% else %} <big><b>price: ${{listing.initial_price}}</b></big> {% endif %} <p>{{listing.description}}</p> <br> created {{listing.date_created}} </div> {%endfor%} {% endblock %} I've also tried setting listingss to list(set(auction_listings.objects.all().values_list('category', flat=True))) so that it return list and not QuerySet -
changeing ListView get_queryset? pagination in django
Good day everyone. I am having some trouble with the paginator in django. I have in my db all the customers info, so what I want to do is to display that info, but I made a search function in which you clic a letter button, for example you clic A and it will filter all the customers that their last name starts with the letter A, if you clic B , it will filter all customers with their last name start with B, and so on. This works correctly, the problem is that I also want to display 10 customers per page, so if I have 20 customers that their last name starts with the letter A, what you will see, will be 10 customers and a bar that says ( <<< page 1 page 2 >>> ) or something like that, and that should be solved with the paginator, I added it, but its not working. I think the problem is that maybe my get function is rewriting the get_query function from ListView perhaps? I tryed different things but I'm not sure. Here is my code in views: class ExpedientView(ListView): queryset = Portfolio.objects.filter(products__isnull=True).order_by('owner__last_name') template_name = 'dashboard-admin/portfoliorecords.html' paginate_by = … -
Django ORM converting date to datetime which is slowing down query 30x
I'm attempting query a table and filter the results by date on a datetime field: .filter(bucket__gte = start_date) where bucket is a datetimefield and start_date is a date object. However django converts the start_date to a timestamp in the raw sql ex 2020-02-01 00:00:00 when I want it just be a date ex 2020-02-01. For some reason casting bucket to a date or casting start_time to a timestamp makes the query 30x slower. When I manually write a query and compare bucket directly to a date ex bucket >= '2020-02-01' the query is blazing fast. How can I get the django orm to do this? -
403 error when sending POST request using ajax (csrf token set)
Django==3.2.3 django-cors-headers==3.7.0 views class LoginView(FormView): form_class = LoginForm template_name = "users/login.html" def form_valid(self, form): ... super().post(self.request) return template <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Login</button> </form> js $.ajax({ type: 'POST', url: "http://localhost:8000/users/login/", processData: false, contentType: false, cache: false, beforeSend: function (xhr) { xhr.setRequestHeader('X-CSRFToken', $('[name=csrfmiddlewaretoken]').val()); }, data: { ... }, }) I look at the network - the token in the header is the same as in the form. Also installed corsheaders INSTALLED_APPS = [ .... "corsheaders", .... ] MIDDLEWARE = [ "corsheaders.middleware.CorsMiddleware", .... ] CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_WHITELIST = ["http://127.0.0.1:8000"] CORS_ALLOW_METHODS = ["*"] CORS_ALLOW_HEADERS = ["*"] -
How can I solve Django Rest Framework ParseError in PATCH method?
I am writing an API with Django RF and I am trying to write the PATCH method with update method of the ModelViewSet. Then I am trying it out using the API View in my browser by passing a simple update to the field name. However, I keep getting the ParseError meaning my request.data is malformed. Below you can see that I am actually passing a JSON-like structure to the request. And when setting up a breakpoint in the update method, my request.data looks like {'name': 'Some Name'} (but I guess the single quotes are just because I'm in the breakpoint. Any ideas on what am I missing here? rest_framework.exceptions.ParseError: JSON parse error - Expecting property name enclosed in double quotes: line 3 column 1 (char 29) def update(self, request, pk=None, **kwargs): cm = get_object_or_404(self.get_queryset(), pk=pk) obj = self.serializer_class(cm, data=request.data, partial=True) obj.is_valid(raise_exception=True) obj.update(cm, obj.validated_data) return Response(obj.data) -
Django on the production server (nginx + gunicorn), after changes in the files, sometimes the changes are displayed, sometimes they are not displayed
On the production server (nginx + gunicorn), after changes in the files, sometimes the changes are displayed, sometimes they are not displayed. After restarting the server, everything works correctly. I thought it might be related to caches and tried different options (disabling caches, cleaning caches, etc.), but the problem remained. Also tried deleting the __pycache__ folders in different project directories, but that didn't help either -
Django- Can only concatenate str (not "ManyRelatedManager") to str
I am trying to save my model. But when I try to save my model I throws the following error TypeError at /admin/user/teacher/add/ can only concatenate str (not "ManyRelatedManager") to str My models.py file looks like this class Class(models.Model): Class = models.CharField(max_length=50) section_choices = (('A','A'),('B','B'),('C','C'),('D','D'),('E','E')) Section = models.CharField(max_length=100, choices=section_choices) def __str__(self): return self.Class + "," + self.Section class Subject(models.Model): subject = models.CharField(max_length=100) def __str__(self): return self.subject class Teacher(models.Model): User = models.ForeignKey(User, on_delete=models.CASCADE) Subject = models.ManyToManyField(Subject) Name = models.CharField(max_length=50) Profile = models.ImageField(upload_to = upload_teacher_profile_to, default = 'defaults/teacher_profile.png') Class = models.ManyToManyField(Class) Number = models.IntegerField(blank=True) is_banned = models.BooleanField(default=False) def __str__(self): return self.Name + "of" + self.Class -
I want to write to a Django model from a standalone python script that generates a CSV file but seem to be in the wrong environment
I have a standalone python script that I run regularly to generate a CSV file from external data. I would like if this script could also update a corresponding model in a Django app running in a virtualenv. I have added the following lines to the script from django.conf import settings settings.configure() from app.models import BER_assessors The model is BER_assessors and is defined in the model.py file in the app directory at the root of the django application. The script is also at the root of the django application ( the one that contains the app/authentication/core/env/media etc. folders ) When I run my script I get the error message "django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet." The Django application itself runs fine. I think there is a question of context or environment, i.e. I am not "in" the app and as such cannot write to the models etc. How can I correct this ? Best regards / Colm -
MySQL command line client is Not installed
I have installed msi version of mysql from this link. https://dev.mysql.com/downloads/windows/installer/8.0.html I have installed all the below. I need MySQL command line client but it is not installed and cannot be found either. What should i do, i have tried other methods but they are not working too. I need it for a django project. -
Django Rest Framework ModelSerializer giving error for primary field
I am working on a project where I have created custom user by extending AbstractBaseUser and PermissionMixin, the model class is following. class User(AbstractBaseUser, PermissionsMixin): phone_number = models.CharField( primary_key=True, validators=[MinLengthValidator(10)], max_length=10 ) password = models.CharField( null=False, blank=False, validators=[MinLengthValidator(8)], max_length=225 ) date_joined = models.DateTimeField(null=False, blank=False, default=timezone.now) last_login = models.DateTimeField(null=True, blank=True) last_logout = models.DateTimeField(null=True, blank=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) USERNAME_FIELD = "phone_number" REQUIRED_FIELDS = [] objects = CustomUserManager() @staticmethod def hash_password(sender, instance, *args, **kwargs): if not instance.is_staff and not instance.is_superuser: instance.set_password(instance.password) def get_token(self): return Token.objects.get(user=self) def __str__(self): return self.phone_number # signals for Model User pre_save.connect(User.hash_password, sender=User) And the following ModelSerializer corresponding to it. class UserLoginSerializer(serializers.ModelSerializer): class Meta: model = User fields = ["phone_number", "password"] Now if If I pass the post data as:- { "phone_number":8888888888, "password":12345678 } What I am getting: The serializer.is_valid() is returning False. if I am doing serializer.is_valid(raise_exception=True) then I am getting response as: { "phone_number": [ "user with this phone number already exists." ] } My Doubts are: I know that 8888888888 is already in the DataBase but I still want to access it using serializer.validated_data.get('phone_number', None) I also want to know the reason, why this is happening, it is acting like as if I am … -
Serializer field values based on request
In Haystack, I have the following view set: class ArtistSearchViewSet(HaystackViewSet): index_models = (Artist,) serializer_class = ArtistSearchResultSerializer pagination_class = LimitOffsetPagination This is the serializer: class ArtistSearchResultSerializer(HaystackSerializer): class Meta: index_classes = (ArtistIndex,) fields = ( "id", "name", ) search_fields = ("text",) For each returned search result I want to add a boolean field that indicates whether the corresponding artist has been starred by the current user or not. How would you do that? -
how do i count up when there is a unique value but when there is a duplicate value the count remains the same
Question_id Question part_model_ans part_total_marks answer_mark number 16 What's a potato It's a vegetable 1 5 1 16 What's a potato It's a seed 2 5 1 16 4+4 8 2 5 2 17 What's a dog It's a mammal 1 5 1 17 What's a dog It's a pet 2 5 1 17 8+8 16 2 5 2 SELECT Q.question_id,Q.question, PMA.part_model_ans,QP.part_total_marks,MA.answer_mark DENSE_RANK() over(Partition by QP.question_id) as number FROM "QUESTIONS" Q LEFT JOIN "QUESTIONS_PART" QP ON QP.question_id = Q.question_id LEFT join "PART_MODEL_ANSWER" PMA ON PMA.part_id = QP.part_id LEFT join "MODEL_ANSWER" MA ON MA.question_id = Q.question_id ORDER BY Q.question_id ASC What i would like to do is increase the count when there is a unique question but when there is a duplicate question the count remains the same, the count also resets after every question, i tried using dense rank but it makes the value for all in the column number as 1 -
Inter-app model import lead to RuntimeError doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS
Context I need to add an app to an existing django 2.2 project. The existing app is called rest. What I am trying to achieve is to interact with models defined in rest from cluster_service (the new app) emc2_backend/ project/ rest/ cluster_service/ rest/models.py class Fichier(models.Model): checksum = models.CharField(primary_key=True, max_length=64, validators=[ RegexValidator(regex="[a-f0-9]{64}")], help_text="SHA 256 du fichier en guise de clef primaire") nom = models.CharField(max_length=100) chemin = models.CharField(max_length=255) class Meta: unique_together = (('nom', 'chemin'),) abstract = True class InputFile(Fichier): def __str__(self): return "{}".format(self.nom) class FichierPy(Fichier): forked_from = models.ForeignKey( "self", on_delete=models.DO_NOTHING, blank=True, null=True) input_files = models.ManyToManyField(InputFile, blank=True) def __str__(self): return "{}".format(self.nom) All apps have been properly defined in INSTALLED_APPS (to my knowledge) Issue I have no problem importing various models from rest using from emc2_backend.rest.models import Site, Etude However, when it comes to FichierPy InputFile, I get the following error while running my tests: ERROR: cluster_service.tests (unittest.loader._FailedTest) ---------------------------------------------------------------------- ImportError: Failed to import test module: cluster_service.tests Traceback (most recent call last): File "c:\users\zarebskid\appdata\local\programs\python\python36\lib\unittest\loader.py", line 428, in _find_test_path module = self._get_module_from_name(name) File "c:\users\zarebskid\appdata\local\programs\python\python36\lib\unittest\loader.py", line 369, in _get_module_from_name __import__(name) File "C:\Users\zarebskid\Documents\projects\emc2-backend\emc2_backend\cluster_service\tests.py", line 1, in <module> from emc2_backend.rest.models import Calcul File "C:\Users\zarebskid\Documents\projects\emc2-backend\emc2_backend\rest\models.py", line 31, in <module> class InputFile(Fichier): File "C:\Users\zarebskid\AppData\Local\pypoetry\Cache\virtualenvs\emc2-backend-Ay5lD4CN-py3.6\lib\site-packages\django\db\models\base.py", line 111, in __new__ "INSTALLED_APPS." % (module, … -
Django SocialAuth / Django AllAuth: How to save user details into user profile upon login with Facebook if Account does not exist?
Django SocialAuth / Django AllAuth: How to save user details into user profile upon login with Facebook if Account does not exist? I have set up Django SocialAuth and AllAuth into my project for login using Facebook. This is my Profile model. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length=300, blank=True) image_url = models.URLField(max_length=200) email = models.EmailField(max_length=254) profile_url = models.URLField(max_length=200) bio = models.TextField(max_length=500, blank=True) location = models.CharField(max_length=30, blank=True) birth_date = models.DateField(null=True, blank=True) def __str__(self): return self.user How do I get these details when a new user logs in and save them to profile model? Thank you for your time. -
How to use timezones in Django Forms
timezones in Django... I am not sure why this is so difficult, but I am stumped. my settings.py timezone settings look like: LANGUAGE_CODE = 'en-us' TIME_ZONE = 'America/Toronto' USE_I18N = True USE_L10N = False USE_TZ = True I am in Winnipeg, my server is hosted in Toronto. My users can be anywhere. I have a modelfield for each user that is t_zone = models.CharField(max_length=50, default = "America/Winnipeg",) which users can change themselves. with respect to this model: class Build(models.Model): PSScustomer = models.ForeignKey(Customer, on_delete=models.CASCADE) buildStart = models.DateTimeField(null=True, blank=True) ... I create a new entry in the DB using a view like: views.py ... now = timezone.now() newBuild = Build(author=machine, PSScustomer = userCustomer, buildStart = now, status = "building", addedBy = (request.user.first_name + ' ' +request.user.last_name), ... ) newBuild.save() buildStart is saved to the database in UTC, and everything is working as expected. When I change a user's timezone in a view with timezone.activate(pytz.timezone(self.request.user.t_zone)) it will display the UTC time in their respective timezone. All is good (I think) so far. Here is where things go sideways. When I want a user to change buildStart in a form, I can't seem to get the form to save the date to the DB … -
How to format (succinctly) a date when returning django validation?
For a string type foo, you can write print('The value is %s' % foo) But how do you do this if foo is a datetime? from datetime import date foo = date.today() print('The value is %?' % foo) i.e. what do you write in place of ? to format as a date; preferably dd-mmm-yyyy say? Here is what I'm really trying to do. In django, I'm validating a date: if start_date < date.today(): raise ValidationError( _('%(start_date)s must be on or after today.'), params={'start_date': start_date}, ) But I need something better than s -
django - get first record for each day
I have a model Sales with: Saler Product sold Date I would like to get the first sale for each date and for each saler, how can I do that? Thanks -
Handle IntegrityError on signup for allauth Django
I'm using Django allauth for google user signup and login. Now I wanted to have unique email address for each user that tries to signup be it through google or normal django signup. For unique email I wrote the following in models.py User._meta.get_field('email')._unique = True this is working perfectly fine but the issue arises when signing up through google login. settings.py 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'django_filters', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', 'crispy_forms', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] AUTHENTICATION_BACKENDS = [ # Needed to login by username in Django admin, regardless of `allauth` 'django.contrib.auth.backends.ModelBackend', # `allauth` specific authentication methods, such as login by e-mail 'allauth.account.auth_backends.AuthenticationBackend', ] I just want to handle the exception. Thanks in advance -
Gunicorn - ModuleNotFound crispy_forms (But is installed)
I am trying to setup Crispy Forms on my Django environment. I have installed Crispy Forms using pip3 install --user django_crispy_forms and I have added the 'crispy_forms' to the INSTALLED APPS within my settings.py file. Although, I am unable to boot up my gunicorn service file, as an error is displaying "ModuleNotFound Error crispy_forms" Just to ensure that Crispy Forms is installed, I tried to rerun the installation to which I receive a message "requirements are already satisfied". Any ideas to what could be causing this behaviour? Edit: If I remove 'crispy_forms' from the INSTALLED APPS area, my gunicorn service boots up perfectly fine. Thanks! -
Django + Bootstrap collapsed table front-end issue?
I have been trying to figure out a front-end issue I've been on for a few days. I am using Django + Bootstrap collapsed accordion. What I am trying to do is completely hide a div, and all spacing until the collapsable button is clicked (eyeball). For some reason it's throwing a couple weird front-end issues like below. Basically what the collapsed div does, is show details if the user provides them which are new table rows. But on page load it shows all of this extra spacing where the collapsed rows are, and also throws some odd border issues? The first entry with the issue is an instance where a user has provided Address Phone Position Concern This is the HTML I have in place as of now, <style> .hiddenRow { border-top-style: hidden; border-bottom-style: hidden; } </style> <div class="table-responsive"> <table class="table small"> <thead> <tr> <th></th> <th>Entry Date</th> <th>Employee First Name</th> <th>Employee Last Name</th> </tr> </thead> {% for employee_entry in employee_entries %} <tbody> <tr data-toggle="collapse" class="accordion-toggle" data-target=".employee-entry-{{ employee_entry.id }}"> <td><button><span class="glyphicon glyphicon-eye-open"></span></button></td> <td>{{ employee_entry.created_at|date:'M d, Y' }}</td> {% if employee_entry.first_name %} <td>{{ employee_entry.first_name }}</td> {% else %} <td></td> {% endif %} {% if employee_entry.last_name %} <td>{{ employee_entry.last_name }}</td> {% else … -
Unable to Migration Django models
I am having the issue on unable to migrate models on Django. It has worked for the first time and then again I tried on the next project folder and it has never worked for me. -
How to test image upload on Django Rest Framework
i'm on a struggle. The problem is with the unit testing ("test.py"), and i figured out how to upload images with tempfile and PIL, but those temporary images never get deleted. I think about making a temporary dir and then, with os.remove, delete that temp_dir, but the images upload on different media directorys dependings on the model, so i really don't know how to post temp_images and then delete them. This is my models.py class Noticia(models.Model): ... img = models.ImageField(upload_to="noticias", storage=OverwriteStorage(), default="noticias/tanque_arma3.jpg") ... test.py def temporary_image(): import tempfile from PIL import Image image = Image.new('RGB', (100, 100)) tmp_file = tempfile.NamedTemporaryFile(suffix='.jpg', prefix="test_img_") image.save(tmp_file, 'jpeg') tmp_file.seek(0) return tmp_file class NoticiaTest(APITestCase): def setUp(self): ... url = reverse('api:noticia-create') data = {'usuario': usuario.pk, "titulo":"test", "subtitulo":"test", "descripcion":"test", "img": temporary_image()} response = client.post(url, data,format="multipart") ... So, to summarize, the question is, ¿How can i delete a temporary file from different directories, taking into account that those files strictly have to be upload on those directorys? -
Django ecommerce: Reverse for 'cart_add' with arguments '('',)' not found. 1 pattern(s) tried: ['cart/add/(?P<product_id>[0-9]+)/$']
This is my first ecommerce web-site with django and it's a little tough to wrap my head around all the routing and cart function, and I fixed lots of stuff, but I just can't fix this error. I tried doing some stuff in urls but it just didn't work out. onlineshop/models.py: from django.db import models from django.urls import reverse class Category(models.Model): name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, unique=True) class Meta: ordering = ('name',) verbose_name = 'category' verbose_name_plural = 'categories' def __str__(self): return self.name def get_absolute_url(self): return reverse('onlineshop:product_list_by_category', args=[self.slug]) class Product(models.Model): category = models.ForeignKey( Category, related_name='product', on_delete=models.CASCADE) name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True) image = models.ImageField(upload_to='products/%Y/%m/%d', blank=True) description = models.TextField(blank=True) price = models.DecimalField(max_digits=10, decimal_places=2) available = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: ordering = ('name',) index_together = (('id', 'slug')) def __str__(self): return self.name def get_absolute_url(self): return reverse('onlineshop:product_detail', args=[self.id, self.slug]) onlineshop/views.py: from django.shortcuts import render, get_object_or_404 from .models import * from cart.forms import CartAddProductForm def product_list(request, category_slug=None): category = None categories = Category.objects.all() products = Product.objects.filter(available=True) if category_slug: category = get_object_or_404(Category, slug=category_slug) products = products.filter(category=category) context = { 'categories': categories, 'category': category, 'products': products, } return render(request, 'onlineshop/product/list.html', context) def product_detail(request, id, slug): product = get_object_or_404(Product, … -
Django and Ajax. js not running
I hope anyone can help me with my code. I have here this html that was a js function with the goal that, whenever someone changes the "filament" option, it will change the "colors" available options available in the select: <form method="post" enctype="multipart/form-data" style="max-width: 1000px;"> {% csrf_token %} {{ form.as_p }} {% for message in messages %} <div class="alert alert-success"> <a class="close" href="#" data-dismiss="alert">×</a> {{ message }} </div> {% endfor %} <h2 class="sr-only">Login Form</h2> <div class="illustration"> <div class="form-group"> <input type="file" name="printingfile"/ style="font-size: medium;"> <select class="form-select" aria-label="Default select example" id="=filament"> <option value="1">PLA</option> <option value="2">ABS</option></select> <select class="form-select" aria-label="Default select example" id="=color"></select> <button class="btn btn-primary btn-block" type="submit">Submit</button></div> </div> </form> </section> <div></div> <script src="{% static 'assets/js/jquery.min.js'%}"></script> <script src="{% static 'assets/bootstrap/js/bootstrap.min.js'%}"></script> <script src="{% static 'assets/js/Animated-Text-Background.js'%}"></script> <script src="{% static 'assets/js/Cookie-bar-footer-popup.js'%}"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> {% block javascript %} <script> //updating the colors available $("#filament").change(function () { var filament = $(this).val(); var color = $('#color'); console.log(filament); $.ajax({ url: '/get_colors/', data: { 'filament': filament }, dataType: 'json', success: function (data) { color.empty(); for (var i = 0; i < data.lenght; i++) { color.append('<option value=' + data[i].name + '>' + data[i].name + '</option>'); } } }); }); </script> {% endblock javascript %} </body> </html> This calls a view in Django. I … -
how to use a singleton instance in multiple django apps
I'm creating a website using django framework. I am using a singleton in one django application and I use it to store some variables . Now that I have created another app in my project, how can I import the data from my singleton to the new app. class SingleInstanceMetaClass(type): def __init__(self, name, bases, dic): self.__single_instance = None super().__init__(name, bases, dic) def __call__(cls, *args, **kwargs): if cls.__single_instance: return cls.__single_instance single_obj = cls.__new__(cls) single_obj.__init__(*args, **kwargs) cls.__single_instance = single_obj return single_obj class MyClass(metaclass=SingleInstanceMetaClass): def __init__(self): self.df = None self.del_var = None self.quali_col = None self.quanti_col = None self.target_var = None self.date_col = None And this what my project looks like without the other django files(models,urls,...) Project Description -views.py Transformation -views.py