Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Problems referencing model in function based view
As the title states, I'm having trouble referencing my account model in my cmsUserDetailEdit view. The site itself doesn't break, but it seems like its just not able to find the model, as all the placed where the model is referenced is empty. I've tried placing the account in the context. E.g: 'account': account, but without luck. views.py def cmsUserDetailEdit(request, pk): account = Account.objects.all() accounts = Account.objects.get(pk=pk) if request.method == 'POST': u_form = UserEditPersonalForm(request.POST, instance=accounts.user) a_form = AccountEditPersonalForm(request.POST, instance=accounts) if u_form.is_valid() and a_form.is_valid(): u_form.save() a_form.save() messages.success(request, f'Account updated') return redirect('/cms/test/') else: u_form = UserEditPersonalForm(instance=accounts.user) a_form = AccountEditPersonalForm(instance=accounts) context = { 'u_form': u_form, 'a_form': a_form, } return render(request, 'cms/users/cms-users-user-edit.html', context) cms-users-user-edit.html <div class="note-card-content"> <div class="content"> {{ account.note }} <!-- This part is empty --> </div> </div> -
Django Rest Framework ViewSets is returning selected records rather than all records in list view
I have a django application. I have one part of my app that is not working as I was expecting. As of now I am using the django rest framework view sets. What I want is two basically have 2 different list views in the same viewset. 1 that returns all of the accounts in the accountviewset and another list view that returns all of the accounts associated with a user based on the user foreignkey in the account model. The code below returns all the acccounts associated with a specific person, but I am not able to have a list view that returns all of the accounts in the database. class AccountViewSet(viewsets.ModelViewSet): serializer_class = AccountSerializer queryset = Account.objects.all() lookup_field = 'user__username' def list(self, request): queryset = Account.objects.all() serializer_class = AccountSerializer def get_object(self): return self.queryset.get(user__username=self.kwargs.get('username')) -
Django: Get queryset of nested objects in Retrieve API View
I'm creating a Django application with django-rest-framework and using djongo to connect to MongoDB. I have a nested model as such: class Group(models.Model): group_code = models.CharField( max_length=15, blank=False, unique=True ) users = models.ArrayModelField( model_container=User ) class User(models.Model): name = models.CharField( max_length=100 ) user_code = models.CharField( max_length=32, default=hex_uuid, editable=False ) class Meta: abstract = True I'm attempting to set up a view to retrieve a User at the following URL: urlpatterns = { url(r'^user/(?P<group_code>[\w]+)/(?P<user_code>[\w]+)/$', UserDetail.as_view(), name='user-detail') } Essentially, I want the view to display just the User's information instead of the Group's information. This didn't work, but is what I attempted: class UserDetail(generics.RetrieveUpdateDestroyAPIView): serializer_class = UserFullSerializer def get_queryset(self, *args, **kwargs): return Group.objects.get(team_code=self.kwargs['group_code']).users lookup_field = 'user_code' lookup_url_kwarg = 'user_code' However, users in this case is a normal list instead of a QuerySet. Therefore, the lookup_field attribute is not working correctly. Any thoughts on how to access the nested list users of type User as a QuerySet so that this view can work properly? -
django request.POST.get() returns nothing
Trying to get a users input from django forms using request.POST.get(). It doesn't return anything even thought the user submits something. django form <form action="" method="post" > {%csrf_token%} <input name="choosestorename" id="choosestorename" placeholder="Choose a store name" type="text"></input> </form> django views def dashboard(request): if request.method == "POST": choosestorename = request.post.get("choosestorename") print(choosestorename) -
How do I run my python command as a cron while loading my environment vars?
I'm using Python 3.7 with Django. I want to set up a cron job ("crontab -e") where I run davea$ /bin/bash -l -c 'cd /Users/davea/Documents/workspace/mainpage_project; ./venv/bin/activate; python manage.py runstats' However, upon running that, I get the error File "manage.py", line 14 ) from exc If I run cd /Users/davea/Documents/workspace/mainpage_project; ./venv/bin/activate; python manage.py runstats everything runs fine, but I want to load environment variables which is why I was trying the former command. Is there a way to fix the first command so that I can load my environment vars and also execute my script? Below is my "manage.py" file ... #!/usr/bin/env python import os import sys if __name__ == '__main__': os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mainpage_project.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc # line 14 execute_from_command_line(sys.argv) -
Reverse querry with different users error and how to restrict the users allowed
I'm quite new to django, I wanted to create a project model. I don't know how to make this restrictions on the ManyToManyField, etc... Only teachers can be either the director or a coordinator Only students can be student Both, students and teachers can be the author of the project Moreover, I get these errors and I don't know why doing what the hint does will help or what would it do: unihub.Project.director: (fields.E305) Reverse query name for 'Project.director' clashes with reverse query name for 'Project.student'. HINT: Add or change a related_name argument to the definition for 'Project.director' or 'Project.student'. class Project(models.Model): PENDING = 0 APROVED = 1 ONGOING = 2 COMPLETED = 3 STATUS_CHOICES = ( (PENDING, 'pending'), (APROVED, 'aproved'), (ONGOING, 'ongoing'), (COMPLETED, 'completed') ) # serial number project_id = models.AutoField(primary_key=True) # Basic fields title = models.CharField(max_length=50, blank=False) description = models.CharField(max_length=250, blank=False) content = models.TextField(blank=False) tags = models.ManyToManyField(Tag) status = models.CharField(choices = STATUS_CHOICES, default=PENDING, max_length=15) # Date fields date_posted = models.DateTimeField(default=timezone.now) last_modified = models.DateTimeField(auto_now=True) # People working on project author = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) student = models.OneToOneField(User, null=True, on_delete=models.SET_NULL) director = models.ManyToManyField(User) coordinators = models.ManyToManyField(User) # Files files = models.ManyToManyField(File) -
How do I select information in other table based on the ID provided using a loop
Super new to django, working on my 1st test project. I have an app that's called customers. Inside of that, I have a few models. The 2 main, once I am trying to get to work right now, are Customer_Info, and Company_Info. On the template side I want to pull information in the for loop from both templates. Companies could have multiple customers (contacts). So inside of the customer info table, I am storing the company uuid they might belong to. Some customers would not have that ID as they are individuals and do not have a company association. Here are the 2 models. class Customer_Info(models.Model): #Name of the table id = models.AutoField(primary_key=True) cust_uuid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) first_name = models.CharField(max_length=32, blank=False) middle_name = models.CharField(max_length=32, blank=True) last_name = models.CharField(max_length=32, blank=False) phone = models.CharField(max_length=10, blank=False) email = models.CharField(max_length=64, blank=False) address_1 = models.CharField(max_length=64, blank=True, null=True) address_2 = models.CharField(max_length=64, blank=True, null=True) city = models.CharField(max_length=16, blank=True, null=True) state = models.CharField(max_length=2, blank=True, null=True) zipcode = models.IntegerField(blank=True, null=True) country = models.CharField(max_length=16, blank=True, null=True) company_uuid = models.ForeignKey('company_info', to_field='company_uuid', db_column='company_uuid', on_delete=models.PROTECT, blank=True, null=True) # miht need a nullable defaul https://docs.djangoproject.com/en/2.1/ref/models/fields/#foreignkey user_id = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, blank=False) # miht need a something else https://docs.djangoproject.com/en/2.1/ref/models/fields/#foreignkey date_added = models.DateTimeField(auto_now=True) def __str__(self): return … -
replace() method not working in custom template filter (Django 2.1)
I am writing a custom template filter that highlights the keyword put into the search engine in the search results page, just like in Google search results. Search engine code in view.py: def query_search(request): articles = cross_currents.objects.all() search_term = '' if 'keyword' in request.GET: search_term = request.GET['keyword'] articles = articles.annotate(similarity=Greatest(TrigramSimilarity('Title', search_term), TrigramSimilarity('Content', search_term))).filter(similarity__gte=0.03).order_by('-similarity') context = {'articles': articles, 'search_term': search_term} return render(request, 'query_search.html', context) Custom template filter code: @register.filter @stringfilter def highlight(value, search_term): return mark_safe(value.replace(search_term, "<span class='highlight'>%s</span>" % search_term)) HTML template code with the filter highlight applied to article.Content: <ul> {% for article in articles %} <li><a href="{% url 'search:article_detail' article.ArticleID %}">{{ article }}</a></li> <p> {{ article.Content|highlight:search_term }} </p> {% endfor %} </ul> CSS code for <span class='highlight'>: .highlight {color:red;} I get no error message but I don't see the highlighted effects. I tried doing other things with value.replace() here but I don't see the effects either. I think the replace() method is not working here. Maybe search_term is not recognized. Any idea what's the issue? -
Session doesn't work after applying Django security recommendations
I ran python manage.py check --deploy and got the following recommendations: System check identified some issues: WARNINGS: ?: (security.W004) You have not set a value for the SECURE_HSTS_SECONDS setting. If your entire site is served only over SSL, you may want to consider setting a value and enabling HTTP Strict Transport Security. Be sure to read the documentation first; enabling HSTS carelessly can cause serious, irreversible problems. ?: (security.W006) Your SECURE_CONTENT_TYPE_NOSNIFF setting is not set to True, so your pages will not be served with an 'x-content-type-options: nosniff' header. You should consider enabling this header to prevent the browser from identifying content types incorrectly. ?: (security.W007) Your SECURE_BROWSER_XSS_FILTER setting is not set to True, so your pages will not be served with an 'x-xss-protection: 1; mode=block' header. You should consider enabling this header to activate the browser's XSS filtering and help prevent XSS attacks. ?: (security.W008) Your SECURE_SSL_REDIRECT setting is not set to True. Unless your site should be available over both SSL and non-SSL connections, you may want to either set this setting True or configure a load balancer or reverse-proxy server to redirect all connections to HTTPS. ?: (security.W012) SESSION_COOKIE_SECURE is not set to True. Using a secure-only … -
Struggling to use two forms with same function based view, connecting it to specific profiles
First off, I have a model named Account which ties into Django's native User model thorough a one to one field. I'm building an admin panel, where the goal is to be able to edit registered accounts (users) information through forms on their backend profile page. I have managed to create a view using two forms (form for changing the user model and a form for changing the account model), but since the instance is request.user, I'm only able to edit my own information on the different profiles. I'm not sure how to tie the pk for account into the code. The ultimate goal is for example: http://path/to/user/profile/1 - Able to edit account 1's information http://path/to/user/profile/2 - Able to edit account 2's information I have tried to add pk to the definition of test, but without luck. urls.py urlpatterns = [ path("test/<int:pk>", views.test, name="test"), ] views.py def test(request, pk): if request.method == 'POST': u_form = UserEditPersonalForm(request.POST, instance=request.user) a_form = AccountEditPersonalForm(request.POST, instance=request.user.account) if u_form.is_valid() and a_form.is_valid(): u_form.save() a_form.save() messages.success(request, f'Account updated') return redirect('/cms/test/') else: u_form = UserEditPersonalForm(instance=request.user) a_form = AccountEditPersonalForm(instance=request.user.account) context = { 'u_form': u_form, 'a_form': a_form } return render(request, 'cms/test.html', context) -
How to checkout branches if there are files created in docker image?
In my pet project I set up docker-compose for development. The issue is that I've create django migration inside dockerimage and created commit. After checkout to main branch I see an error. These files become untracked and I cannot merge sub branch into the main. git checkout master warning: unable to unlink 'apps/app_name/migrations/0001_initial.py': Permission denied warning: unable to unlink 'apps/app_name/migrations/0002_auto_20190127_1815.py': Permission denied warning: unable to unlink 'apps/app_name/migrations/__init__.py': Permission denied Switched to branch 'master' Also I tried to it with sudo. All new files will appear untracked in main branch but no new commits will be added(based on git log) -
Problem on adding Django app to installed apps and can't migrate
I'm trying to use visual studio for my Django project. My visual studio version is 2017, my Python version is 3.6 and my Django version at the beginning is 1.1.18. Then I upgrade it to 2.1.5. I make an app then add it to installed apps. But when I migrate the project get this error: Traceback (most recent call last): File "E:\Django_Try\Test4\Test4\manage.py", line 17, in <module> execute_from_command_line(sys.argv) File "E:\Django_Try\Test4\Test4\env\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "E:\Django_Try\Test4\Test4\env\lib\site-packages\django\core\management\__init__.py", line 357, in execute django.setup() File "E:\Django_Try\Test4\Test4\env\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "E:\Django_Try\Test4\Test4\env\lib\site-packages\django\apps\registry.py", line 89, in populate app_config = AppConfig.create(entry) File "E:\Django_Try\Test4\Test4\env\lib\site-packages\django\apps\config.py", line 90, in create module = import_module(entry) File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked ModuleNotFoundError: No module named 'saeed' The interactive Python process has exited. The interactive Python process has exited. >>> it seems can' identify my app. Please inform me. Saeed -
Simple way to re-run try block if a specific exception occurs?
I'm using Python 3.7 and Django and trying to figure out how to rerun a try block if a specific exception is thrown. I have for article in all_articles: try: self.save_article_stats(article) except urllib2.HTTPError as err: if err.code == 503: print("Got 503 error when looking for stats on " + url) else: raise What I would like is if a 503 errors occurs, for the section in the "try" to be re-run, a maximum of three times. Is there a simple way to do this in Python? -
Python Two Dimensional Array
Please guide please tell me how i can get a single value out for each of this multi dim array in python well i have tried to print out using for loop. [dict_keys(['section_001', 'section_002', 'section_003']), dict_keys(['section_001', 'section_002', 'section_003']), dict_keys(['section_001', 'section_002', 'section_003']), dict_keys(['section_001', 'section_002', 'section_003']), dict_keys(['section_001']), dict_keys(['section_001']), dict_keys(['section_003', 'section_004', 'section_007', 'section_008', 'section_002', 'section_006', 'section_005', 'section_001']), dict_keys(['section_003', 'section_004', 'section_007', 'section_008', 'section_002', 'section_006', 'section_005', 'section_001']), dict_keys(['section_001', 'section_002', 'section_003']), dict_keys(['section_001', 'section_002', 'section_003'])] expect result should be: section_001 section_002 for each array -
How to use range slider with django-filter
How can I use a range slider (for example the jQuery one) with django-filter package? I've tried to use NumericRangeFilter with new field (I don't know how to overwrite the filter class from one specific field). class ProductFilter(django_filters.FilterSet): price = django_filters.NumericRangeFilter() class Meta: model = Product fields = '__all__' exclude = 'price' I wish to know how to use the field in the template to render a range slider and filter the results. I expect too to know how can I change the filter class of just one model field. -
Use data in foreign key model prior to saving in Django admin
I'm prototyping an estimating application. Each Estimate model will have one or more Part models. Here is the beginning of my models: class Part(models.Model): estimate = models.ForeignKey('Estimate', on_delete=models.CASCADE) description = models.CharField(max_length=255) class Estimate(models.Model): number = models.CharField(max_length=255, primary_key=True) customer = models.CharField(max_length=255, null=True, blank=True) description = models.CharField(max_length=255, null=True, blank=True) price = models.IntegerField(null=True, blank=True) stitch = models.BooleanField(null=True, blank=True) stitch_speed = models.IntegerField(null=True, blank=True) stitch_rate = models.IntegerField(null=True, blank=True) boxes = models.IntegerField(null=True, blank=True) freight = models.IntegerField(null=True, blank=True) overall_markup = models.IntegerField(null=True, blank=True) date_created = models.DateField(auto_now_add=True) def __str__(self): return self.number I have the Estimate model appearing in the admin with Part models in a StackedInline. class PartInline(admin.StackedInline): model = Part extra = 1 class EstimateAdmin(admin.ModelAdmin): model = Estimate inlines = [PartInline] list_display = ['number', 'description', 'customer', 'price'] Ideally, I would go into the admin, create a new Estimate, fill out its Parts, and then click Save. Ultimately, my Estimate model will need to use data from the Part model to perform calculations before saving to the database. For example, each Part will contain its own price. The price from each Part will need to be added to the total Estimate price. I'm having trouble figuring out how to send data from the Part model to the Estimate model … -
Is there any way to access the variable inside a function from another function within the same class in TemplateView of django
how to access the variable within a function from another function within the same class in django's TemplateView class add_question_main(TemplateView): template_name = 'add_question_paper/index.html' def get(self,request,*args,**kwargs): form = question_details_form() no_txt = request.GET.get('num') return render(request,self.template_name,{'form':form}) def post(self,request,*args,**kwargs): form = question_details_form(request.POST) return render(request,self.template_name,{'form':form}) I wonder how could I use the value of no_txt in function post? -
Django CreateView - created_by, modified_by mixin not working
I have followed spapas tutorial on CBV's and tried to apply a mixin on a create view. But looks like it doesn't evaluate correctly the if not form.invoice.requester for a user foreign key because it always says: RelatedObjectDoesNotExist and it points to the field evaluated in the if not line. What can be wrong? views.py class AuditableMixin(object, ): def form_valid(self, form, ): if not form.instance.requester: form.instance.requester = self.request.user form.instance.modified_by = self.request.user return super().form_valid(form) class NewOrderView(LoginRequiredMixin, PermissionRequiredMixin, AuditableMixin, generic.CreateView): permission_required = 'orders.add_order' form_class = NewOrderForm model = Order title = 'New Order' extra_context = {'title': title} forms.py class NewOrderForm(forms.ModelForm): class Meta: model = Order widgets = { 'order_details': forms.Textarea, } exclude = ( 'status', 'invoice', 'requester', 'modified_by', ) Thank you. -
Django URLS int returns with trailing slash
I am trying to take a primary key out of a url, e.g. site.com/content/1/ with urls.py like: urlpatterns = [ ... path('content/<int:pk>/', views.ContentView.as_view(), ] But when I access pk it has the / appended and is not an int. Is there a way to have django not pass the trailing slash? -
How to merge local branch with migrations created in docker
In my pet project I set up docker-compose for development. The issue is that I've create django migration inside docker and when I want to checkout to main brain and merge commits from sub branch I got an error: error: The following untracked working tree files would be overwritten by merge: apps/users/migrations/0002_auto_20190127_1652.py -
what is the best way/architecture to trigger celery calcualtion with many account?
I have my django/celery/sqs service ready for a set of calculations with one account. I would like to trigger calculations for many accounts. Currently, I am thinking two ways to do implement this: 1. upload accounts through a csv file, process these accounts and trigger the calculations one by one through rest api. 2. again, upload accounts through a csv file, but directly implement the service inside application, this might be a repeating work since I have the calculation for a single account already. Thanks for any suggestion. -
DRF Serializer sets provided field to None
i'm currently at a project where i want to test the validation of my serializers. I run into the problem that the Serializers set's a provided field to None in the process of validation which does not seem reasonable to me. Here more details (shorted for simplicity): models.py : class Contract(models.Model): start_date = models.DateField() end_date = models.DateField() serializers.py: class ContractSerializer(serializers.ModelSerializer): class Meta: model = Contract fields = "__all__" def validate(self, attrs): """ Object-level validation. Here we validate : start_date is, timewise, prior to end_date :param attrs: :return: """ if not attrs["start_date"] < attrs["end_date"]: raise serializers.ValidationError("Sample Error Message.") return attrs I use pytest for testing and pytest-django. My conftest.py : from pytz import datetime @pytest.fixture def valid_contract_json(): start_date = datetime.date(2019, 1, 1) end_date = datetime.date(2019, 1, 31) data = { "start_date": start_date, "end_date": end_date, } return data My test(s) looks like : test_serializers.py: from app.serializers import ContractSerializer class TestContractSerializer: def test_validation(self, valid_contract_json): ContractSerializer(data=valid_contract_json).is_valid(raise_exception=True) When running this Test it fails and show the following message: TypeError: '<' not supported between instances of 'datetime.date' and 'NoneType' I did some investigation on this: Comment the validate method out. Modify Test to : def test_validation(self, valid_contract_json): pprint.pprint(valid_contract_json) seri = ContractSerializer(data=valid_contract_json).is_valid(raise_exception=True) # Serialization won't throw exception … -
Django Migrate Operation Fails with error "the database system is in recovery mode"
I was migrating an old project, but for some reason the migration always failed at this file, i tried executing just this migration file, still same error. I have attached the command i used, the logs from the python terminal on the command and the logs from the database below. The command used python3 manage.py migrate content 0037_auto_20180618_1711 The Migration file # -*- coding: utf-8 -*- # Generated by Django 1.11.1 on 2018-06-18 17:11 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('content', '0036_trivia_original_description'), ] operations = [ migrations.AlterField( model_name='trivia', name='is_approved', field=models.CharField(blank=True, max_length=32, null=True), ), ] The logs from the migrate operation > File > "/usr/local/lib/python3.5/dist-packages/django/db/backends/utils.py", > line 65, in execute > return self.cursor.execute(sql, params) psycopg2.OperationalError: server closed the connection unexpectedly > This probably means the server terminated abnormally > before or while processing the request. > > > The above exception was the direct cause of the following exception: > > Traceback (most recent call last): File > "/usr/local/lib/python3.5/dist-packages/django/db/migrations/executor.py", > line 244, in apply_migration > state = migration.apply(state, schema_editor) File "/usr/local/lib/python3.5/dist-packages/django/db/migrations/migration.py", > line 129, in apply > operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File > "/usr/local/lib/python3.5/dist-packages/django/db/migrations/operations/fields.py", > line 215, in database_forwards > schema_editor.alter_field(from_model, from_field, to_field) … -
optimizing Django REST Viewset with 1k+ queries for a single object
I have a ViewSet with nested serializers which is making over 1000 SQL queries and taking over 15 seconds to load a single object. I feel I must be doing something catastrophically wrong to get such horrendous performance, but I'm having trouble pinning it down. Similar posts recommend select_related() and prefetch_related(), but their use has brought my SQL query count from 1066 to 1062 -- not even a start. ViewSet: class PostViewSet(DetailAndListViewSet, VoteMixin, SaveMixin, MarkdownToHTML): queryset = Post.objects.select_related('posted_in') \ .prefetch_related('comments') \ .select_related('author', 'author__user') \ .filter(is_visible=True) permission_classes = (IsAuthenticatedOrReadOnly, IsAuthorOrReadOnly) authentication_classes = (TokenAuthentication,) serializer_class = PostSerializer detail_serializer_class = PostDetailSerializer lookup_field = 'slug' slug_field = 'slug' class DetailAndListViewSet(viewsets.ModelViewSet): def get_serializer_class(self): if self.action == 'retrieve': if hasattr(self, 'detail_serializer_class'): return self.detail_serializer_class return super(DetailAndListViewSet, self).get_serializer_class() Serializer: class PostDetailSerializer(serializers.ModelSerializer, GetScoresMixin): author = AccountLimitedInfoSerializer(read_only=True) comments = CommentSerializer(many=True, read_only=True) posted_in = SubInPostDetailSerializer() num_comments = serializers.SerializerMethodField() user_upvoted = serializers.SerializerMethodField() user_downvoted = serializers.SerializerMethodField() score = serializers.SerializerMethodField() class Meta: model = Post read_only_fields = ('comments', 'body_html', 'url', 'slug', 'upvoted_by', 'downvoted_by', 'created', 'num_comments', 'score') fields = ('id', 'author', 'title', 'created', 'body_text', 'comments', 'url', 'link_url', 'image_url', 'posted_in', 'score', 'user_upvoted', 'user_downvoted', 'num_comments') lookup_field = 'slug' extra_kwargs = { 'url': {'lookup_field': 'slug'} } -
How to instantiate a class one time and access it in views
I have a class that runs once, which I had in myapp/__init__.py, but each time django starts it would run twice. It also runs when I migrate models, when I don't need it to. I've read about the ready function https://docs.djangoproject.com/en/dev/ref/applications/#django.apps.AppConfig.ready, but cannot access the instantiated class outside of apps.py Here is my current workflow: in init.py: from .my_module import ResourceHeavyClass resource_heavy_instance = ResourceHeavyClass() in my views.py from . import resource_heavy_instance This currently works, but I only want to load the module when the server starts, not when I make migrations. Appreciate any tips/advice.