Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
changing primary key from username to uuid on POSTGREQL gives: django.db.utils.ProgrammingError: column "username" is in a primary key
I have a postgresql database and I am making a migration to switch my pk from username to uuid. I already made a data migration file where I add a uuid to every row in my model it worked fine on sqlite but when I was testing it on postgresql I got an error. The error was "django.db.utils.ProgrammingError: column "username" is in a primary key" I am not sure where to begin to debug this thing. Here is the model, data migration, migration, and stack trace of the error: # models.py class UserInformation(models.Model): uuid = models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True) user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=False) username = models.CharField(max_length=100, unique=True, blank=True, null=True) # data migration 42 import uuid from django.db import migrations def set_uuid_for_all_user_information(apps, schema_editor): UserInformation = apps.get_model('accounts', 'UserInformation') for userInformation_user in UserInformation.objects.all(): userInformation_user.uuid = uuid.uuid4().hex userInformation_user.save() class Migration(migrations.Migration): dependencies = [ ('accounts', '0041_auto_20211227_2113'), ] operations = [ migrations.RunPython(set_uuid_for_all_user_information), ] # migration 43 (this is where the postgresqsl error occurs) trying to change pk from username to uuid from django.conf import settings from django.db import migrations, models import django.db.models.deletion import uuid class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('accounts', '0042_auto_20211229_2319'), ] operations = [ migrations.AlterField( model_name='userinformation', name='user', field=models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to='auth.user'), ), migrations.AlterField( model_name='userinformation', name='username', field=models.CharField(blank=True, … -
How to apply multiple field options to one field in Django
I'm using Django, is there a way to apply foreign key and ChartField to one field at the same time? Sometimes I want to allow the user to enter a value that is not in the foreign key. I've googled for a long time and found various ways, but I can't find a solution. Please help. [models.py] class Supporting(models.Model): assignment = models.ForeignKey(Assignment, on_delete=models.CASCADE, blank=False, null=True) -
How to insert field in table from database using python script and print it in html page or print python result in html directly using pycharm django
so i'm new to django and python, i'm having a mini project to make a decision support system. so i already build a website, already connect it to the database and have the python code, now i'm having difficulties to push the result/target in python to existing field in table dataresponden from database and print it to html. the flow is like this: an user input a data (nama, umur, gejala, komorbid) and stored it in table dataresponden(nama, umur, gejala, komorbid, hasil_rekomendasi) in database. user didn't input hasil_rekomendasi because hasil_rekomendasi is the result from the decision support system. in python, i read query dataresponden as dataset, i set hasil_rekomendasi as a target and calculate the remaining column. so i get the result i want named hasil_prediksi, now the problem is i want to push hasil_prediksi to column hasil_rekomendasi in table dataresponden because when user input the data they don't input hasil_rekomendasi. after that i want print it in my html page. i tried this Execute a python script on button click but didn't work, i tried to use update table but it didn't work too, this is the code in hasil.html : <div class="modal-body text-center pb-5" id="hasilrekomendasi"> <div class="container"> <div … -
Github actions deploy django application to elastic beanstalk
I'm simply trying to deploy my django application to elastic beanstalk using github actions but keep getting these error: Warning: Environment update finished, but health is Red and health status is Degraded. Giving it 30 seconds to recover... Warning: Environment still has health: Red and health status Degraded. Waiting 19 more seconds before failing... Warning: Environment still has health: Red and health status Degraded. Waiting 8 more seconds before failing... Error: Deployment failed: Error: Environment still has health Red 30 seconds after update finished! This it the code I'm using below: name: AWS Deploy on: push: branches: - test-main-branch jobs: build: runs-on: ubuntu-latest steps: - name: Checkout source code uses: actions/checkout@v2 - name: Generate deployment package run: zip -r deploy.zip . -x '*.git*' - name: Get timestamp uses: gerred/actions/current-time@master id: current-time - name: Run string replace uses: frabert/replace-string-action@master id: format-time with: pattern: '[:\.]+' string: "${{ steps.current-time.outputs.time }}" replace-with: "-" flags: "g" - name: Deploy to EB uses: einaregilsson/beanstalk-deploy@v20 with: aws_access_key: ${{ secrets.AWS_ACCESS_KEY_ID }} aws_secret_key: ${{ secrets.AWS_SECRET_ACCESS_KEY }} application_name: project-pit environment_name: project-pit-cloud version_label: 12345 region: ap-southeast-2 deployment_package: deploy.zip - name: Deployed! run: echo App deployed The application is showing up in my s3 bucket but I still get a Degraded health … -
Get name From extra_field django allauth and save to name field on Users Model
I have Users Model like this from django.db import models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin from django.db.models.signals import pre_save from django.dispatch import receiver # Create your models here. from users.manager import UserManager class Users(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=254, unique=True) name = models.CharField(max_length=254) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) last_login = models.DateTimeField(null=True, blank=True) date_joined = models.DateTimeField(auto_now_add=True) # Setting field USERNAME_FIELD = 'email' EMAIL_FIELD = 'email' REQUIRED_FIELDS = [] # Setting Object Manager objects = UserManager() class Meta: abstract = False I need to get {"name": "Feri Lukmansyah",} from social_account model (from django allauth) and save to name field from Users Model, I already use signal like this from django.dispatch import receiver from allauth.socialaccount.signals import social_account_added, social_account_updated from .models import Users @receiver(social_account_added) @receiver(social_account_updated) def add_name_from_google(request, sociallogin, **kwargs): pass but I don't know how to use signal on django allauth, everybody can help me fix this problem? or have any example to use django allauth signal? -
How to Implement Django Loggers/Logging in the code?
As i am a newbie. I'm working on Django Rest Framework using ModelViewset. Can anyone help me out in explaining or understanding, how to implement the loggers/logging? Even i'm using the Django OAuth2 toolkit for authentication, so how can log a username & password? -
action.php page not found and failure to send data to MariaDB table
This is kind of a double question since the first issue correlates to the latter. My first issue is that the action attribute on my html form directing towards a file called action.php results in a 404 error during form submission and I am not sure how I would create a path in urls.py that would lead to the code in action.php being executed. My second issue is that once the first issue is fixed, action.php is supposed to send the data from the answers submitted in my html form into a MariaDB database I have configured. However, some of the code I have written is appearing on my webpage which leads me to believe that data wont be sent to my database table. Any help would be greatly appreciated. DATA TREE urls.py from django.shortcuts import render from django.http import HttpResponse def say_hello(request): context = {"name": "DUDE"} return render(request, "hello_page.php", context) hello_page.php {% extends "base.php" %} {% block content %} <?php //include('config.php'); $host = "localhost"; $username = "USER"; $password = "PASS"; $database = "donations"; $dbconnect=mysqli_connect($host, $username, $password, $database); if ($dbconnect->connect_error) { die("Database connection failed: " . $dbconnect->connect_error); } ?> <html> <h1> WHATS UP {{name}}!!!!!</h1><br> <form action="action.php" method = "POST"> <label … -
Image Display in Django
ERRORS: <class 'blog.admin.CategoryAdmin'>: (admin.E108) The value of 'list_display[0]' refers to 'image_tag', which is n ot a callable, an attribute of 'CategoryAdmin', or an attribute or method on 'blog.Category'. System check identified 1 issue (0 silenced). -
django redirects to non existing url
Two days ago I created a django project and it worked all right. But, now when I am working on another django project still when I run server it's redirecting me to the older project. I am using different virtual environment for both of them. Even after deleting the old one the issue is not resolved. Thanks in advance. -
Creating an autocomplete search form (probably w/ jQuery) using a comprehensive (huge) movie title list (Django project) from IMDBPy
I am in the early stages of retrieving IMDB data via the Python package IMDBPy (their site) (proj github). I have been referring to this nice IMDBPy implementation for help with aspects of what I'm doing here. Several of the queries that I'm using generate datasets that come in "nested dictionary" form, e.g. 'movie_1':{'title':'One Flew Over the Cuckoo's Nest', 'director': 'Milos Forman'...}. My early version of the title retrieval takes this form in VIEWS.PY: def index(request): imdb = IMDb() test_movies = {} for i in range(1100000, 1100015): test_movies[f'movie_{i}'] = imdb.get_movie(f'{i}') context = { 'test_movies':test_movies, } return render(request, 'index.html', context) And this in my INDEX.HTML template: <div id="search-part1"> <ul> {% for k1,v1 in test_movies.items %} {% for k2,v2 in v1.items %} {% if 'title' in k2 %} <li>{{v2}}</li> {% endif %} {% endfor %} {% endfor %} </ul> <input type="text" name="search" id="search" class="form-control" placeholder="Search for Movies"> </div> Right now, the HTML is just to show that I *can generate a list of these titles. My actual implementation of the dropdown from the search bar (via jQuery's Autocomplete), is a little further down the road at this point. Here is an example that they provide of the Autocomplete in action, in the … -
django how to set form ModelChoiceField drop down to required if specific value is selected from the previous drop down
I have the following form: class RegisterForm(UserCreationForm): company_role = forms.ModelChoiceField(queryset=CompanyRole.objects, empty_label='Select Company Role') office = forms.ModelChoiceField(queryset=Office.objects, empty_label='Select Office', required=False) location = forms.ModelChoiceField(queryset=Country.objects.all(), empty_label="Select Location", required=False) class Meta: model = User fields = ["first_name", "last_name", "username", "email", "password1", "password2", "company_role", "location", "office"] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['office'].queryset = Office.objects.none() Is it possible through this form to set office ModelChoiceField drop down to be required if the first item (id 1) is selected in company_role ModelChoiceField drop down and also if second item (id 2) is selected in company_role ModelChoiceField drop down then set location ModelChoiceField drop down to be required? If so would greatly apprecaite some help on how to do so. Thanks in advance -
Send both POST and GET parameters in Django test client
I've created a view created in Django which accepts both GET and POST parameters. When trying to test it using django-rest-framework test APIClient, it's not clear how I can send both GET and POST parameters. self.client.post has a signature as follows: self, path, data=None, format=None, content_type=None, follow=False, **extra Using data would probably send POST data, is there any workarounds for this? -
How to query and update nested JSON data in Django
I have below class defined to do statistics for voting system. class FormPage(AbstractForm): submission_stats = models.JSONField(null=True, editable=False) Now, I have submission_stats in below format: [ { "id":4, "label":"checkboxes", "choices":[ { "content":"option-A", "num_vote":0, "user_list":[ ] }, { "content":"option-B", "num_vote":0, "user_list":[ ] }, { "content":"option-C", "num_vote":0, "user_list":[ ] } ] }, { "id":7, "label":"Radio Button", "choices":[ { "content":"option-1", "num_vote":0, "user_list":[ ] }, { "content":"option-2", "num_vote":0, "user_list":[ ] }, { "content":"option-3", "num_vote":0, "user_list":[ ] } ] } ] When I receive a vote submission, I want to update num_vote and user_list field in this JSONField accordingly. How to query and update elements in nested JSONField data please ? -
Cloning existing python project anyjson setup command error
I have this project shared to me via github, after I clone and run this steps: python -m venv ./venv venv\scripts\activate pip install -r requirements.txt in pip install -r: It gives me this errors: error in anyjson setup command: use_2to3 is invalid. ERROR: Could not find a version that satisfies the requirement anyjson==0.3.3 (from versions: 0.1, 0.2.0, 0.2.1, 0.2.2, 0.2.3, 0.2.4, 0.2.5, 0.3, 0.3.1, 0.3.2, 0.3.3) ERROR: No matching distribution found for anyjson==0.3.3 Here is what inside the requirements.txt amqp==1.4.9 anyjson==0.3.3 billiard==3.3.0.23 celery==3.1.25 certifi==2019.3.9 chardet==3.0.4 dj-database-url==0.5.0 Django==2.0.13 django-appconf==1.0.3 django-axes==1.7.0 django-celery==3.2.2 django-compressor==2.2 django-crispy-forms==1.7.2 django-dynamic-formsets==0.0.8 django-polymorphic==2.1.2 django-reversion==3.0.1 djangorestframework==3.7.4 ffs==0.0.8.2 gunicorn==20.0.4 idna==2.7 Jinja2==2.10 kombu==3.0.37 letter==0.5 MarkupSafe==1.1.1 opal==0.14.2 Pillow==8.1.0 psycopg2==2.8.6 python-dateutil==2.7.5 pytz==2019.1 rcssmin==1.0.6 requests==2.20.1 rjsmin==1.0.12 six==1.12.0 urllib3==1.24.3 whitenoise==4.1.4 mysqlclient==2.0.3 cryptography==3.4.1 Already tried removing anyjson from requirements.txt but still gives me error. What Am I missing here? -
Why we must have form with model in django, why model alone can't work?
In django: request.POST--1-->corresponding_SQL--2-->database . And we use form = ModelForm(requst.POST).save() to save a form to database. The form has well designed "consructor", which take value and key inside queryDict(request.POST) and convert them to data inside the instance of form one by one. I guess this 'Form' object is kindof an agent,which can be easily stored to database (like above) and can be rendered out in HTML using form.as_p(). Actually I wonder why we don't put all the functions of a form into the model itself, I think that is more intuitive than create a new class called "form". We could just use model.save() or model.is_valid() or model.as_p(), emmm why bother to design a new class called form? -
LISTAR EL NUMERO DE CATEGORIA CONSULTADAS DENTRO DE UNA ITERACION
Hola, buenas noches ¿Por favor me podrían ayudar con la siguiente duda? En mi vista cree una consulta que me lista todas las categorías exceptuando una, esas categorías las itere en un bucle For en la página html, el modelo Categoría está relacionado con otro que se llama Post, mi intención ahora es que en la parte que dice (N. Post) de mi template, se liste el número de Post que tiene esa categoría. ¿Como podría implementar esa consulta en mi Views? ¿Puedo directamente dentro de ese bucle For contar las categorías y ahí mismo listarlas en la etiqueta ? [1]: https://i.stack.imgur.com/Q4jhU.jpg [2]: https://i.stack.imgur.com/LxxcX.jpg [3]: https://i.stack.imgur.com/kmC6m.jpg [4]: https://i.stack.imgur.com/nz1PV.jpg -
Deploying django app to EC2.. server is running through docker compose, but times out when trying to reach the host?
First time deploying an application, so bear with me... I have my EC2 instance up. I have my code on the server with docker-compose being run (docker-compose -f docker-compose.yml up), and the logs say that it is running with Starting development server at http://0.0.0.0:8000/ I have my allowed_hosts to specify the ec2 instance. When i attempt to hit the server in my browser, im getting nothing. It times out, and no logs in the ec2 instance. Any idea of what im potentially missing? -
Django Channels: WebSocket messages are not sent in production
I have Django server which uses WebSockets to send real time updates to web clients. This is all running perfectly fine locally (with manage.py runserver), but in production I am running into the problem that most messages are simply not sent at all. I test this by opening two browsers, making a change in one, which should then be reflected in the other browser. Like I said, this all works locally, but not in production. In production some WebSocket messages are sent by the server and received by the web client, but maybe 20% or so? The rest is just not sent at all. # /websocket/__init__.py import logging from asgiref.sync import async_to_sync from channels.layers import get_channel_layer from djangorestframework_camel_case.util import camelize logger = logging.getLogger("django.server.ws.critical-notes") def ws_send(model_type, action, model_data, user_ids): logger.info(f"Called ws_send for model {model_type}, action {action}, user_ids: {user_ids}") channel_layer = get_channel_layer() for user_id in user_ids: group_name = f"user-{user_id}" async_to_sync(channel_layer.group_send)( group_name, { "type": "send.data", # this calls Consumer.send_data "data": {"type": model_type, "action": action, "model": camelize(model_data)}, }, ) # /websockets/consumers.py import logging from channels.generic.websocket import AsyncJsonWebsocketConsumer from channels.db import database_sync_to_async from django.db import close_old_connections from knox.auth import TokenAuthentication logger = logging.getLogger("django.server.ws.critical-notes") class Consumer(AsyncJsonWebsocketConsumer): def __init__(self, *args, **kwargs): super().__init__(args, kwargs) self.group_name = None @database_sync_to_async … -
Django Rest Framework Patch Request with Image Upload
I'm trying to make an endpoint for updating the profile image of a user. However, whenever I make the PATCH request, the profile_image field does not change to the uploaded file. I've tested on postman using form-data and I get the response "Updated completed" but the profile_image field remains null. views.py class ProfileImageView(APIView): parser_classes = [MultiPartParser, FormParser] def patch(self, request, user_email, format=None): print(request.data) profile = ProfileImage.objects.get(user_email=user_email) serializer = ProfileImageSerializer(profile, data=request.data, partial=True) data = {} if serializer.is_valid(): serializer.update(profile, request.data) data["response"] = "Update completed." data["user_email"] = user_email data["profile_image"] = ( profile.profile_image.url if profile.profile_image else None ) return Response(serializer.data) data["response"] = "Wrong parameters." return Response(data) models.py class ProfileImage(models.Model): user_email = models.CharField(max_length=255) profile_image = models.ImageField( upload_to="uploads/", height_field=None, width_field=None, null=True, blank=True, ) serializers.py class ProfileImageSerializer(serializers.ModelSerializer): class Meta: model = ProfileImage fields = ["user_email", "profile_image"] urls.py urlpatterns = [ path("api-auth/", include("rest_framework.urls")), path("admin/", admin.site.urls), path("register/", RegisterView.as_view(), name="register"), path("login/", obtain_auth_token, name="login"), path("log/add/", LogView.as_view(), name="log"), path("log/all/", LogView.getAll, name="logall"), path("log/<str:user_email>/", LogView.getByUserEmail, name="logbyuseremail"), path("profile/<str:user_email>/", ProfileView.profile, name="profile"), path("edit-profile/<str:user_email>/", ProfileView.as_view(), name="profile"), path( "profile-image/<str:user_email>/", ProfileImageView.getProfileImage, name="profile-image", ), path( "edit-profile-image/<str:user_email>/", ProfileImageView.as_view(), name="profile-image", ), path("events/", EventView.as_view(), name="events"), ] urlpatterns += staticfiles_urlpatterns() urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) enter image description here -
How to pass data from one View function to another for a multi-step form?
I'm currently working a developing a Hockey League management website. The feature I am currently working on, is entering a "Game Report". This is where a score keeper enters in all the details for that game once it has been completed. The Game report feature itself requires 3 steps to be completed. Selecting the game for which you want to enter the report for. A form which populates the roster of both teams, with a checkbox for each player to mark off if they played in the game. In addition, there is 2 separate formsets to add players for either team if they aren't already on the roster. The final part of the game report, where you enter in the goals, penalties, and the game results. Where the goals and penalties are formsets, and the game results are a simple model form. The confusion comes from the fact that data from the prior step, is required for the current step. SelectGame View (Step 1) - No issues here @login_required(login_url="/login/") def selectGame(request): games = Game.objects.all().values( 'iceSlot__date', 'homeTeam__name', 'awayTeam__name', 'id' ) context = {'games': games} return render(request, "home/select-game.html", context) Transition From Step 1 to Step 2 occurs in select-game.html (Also No issue) … -
Django - Why is full URL being returned for some FileFields, but not others?
So I have this view that returns a list of posts that are like a facebook wall post. As you can see in the above image this encompasses: images, videos maybe, avatar, text, and metadata about the post and metadata about the user. I get all the relevant data for the post via table joins. For some reason Video and Photo are returning the full URL with the domain of MEDIA_URL prepended, but creator_avatar_url is only returning the tail end of the url (i.e something like /media/user/avatar.jpeg). Why is my code not returning the full URL for creator_avatar_url? model.py class User(AbstractDatesModel): uuid = models.UUIDField(primary_key=True) username = models.CharField(max_length=USERNAME_MAX_LEN, unique=True, validators=[ MinLengthValidator(USERNAME_MIN_LEN)]) created = models.DateTimeField('Created at', auto_now_add=True) updated_at = models.DateTimeField('Last updated at', auto_now=True, blank=True, null=True) avatar = models.ImageField(upload_to=avatar_directory_path, blank=True, null=True) @property def avatar_url(self): return self.avatar.url class Post(models.Model): uuid = models.UUIDField(primary_key=True) created = models.DateTimeField('Created at', auto_now_add=True) updated_at = models.DateTimeField('Last updated at', auto_now=True, blank=True, null=True) creator = models.ForeignKey( User, on_delete=models.CASCADE, related_name="post_creator") body = models.CharField(max_length=POST_MAX_LEN, validators=[MinLengthValidator(POST_MIN_LEN)]) class Photo(AbstractBaseModel): post = models.OneToOneField(Post, on_delete=models.CASCADE) image = models.ImageField(upload_to=images_directory_path) @property def image_url(self): return self.image.url class Video(AbstractBaseModel): post = models.OneToOneField(Post, on_delete=models.CASCADE) video = models.FileField(upload_to=videos_directory_path) @property def video_url(self): return self.video.url helper.py def query_to_full_post_data_serializer(request, post_query_set: QuerySet): query_set_annotated = post_query_set.annotate( creator_username=F('creator__username'), creator_avatar_url=F('creator__avatar'), ).prefetch_related( … -
Django view with slug and id
I have this URL path('kategorie/<slug:slug>-<int:pk>', views.category_view, name="category_view"), And this view def category_view(request,slug,pk): categories = EcommerceProductCategory.objects.all().filter(slug=slug, pk=pk).order_by('-created_at') product = Product.objects.filter(slug=slug).order_by('-created_at') context = { 'categories': categories, 'product': product, } return render(request, 'ecommerce/category_view.html', context=context) Now i wanna show on that page category_view.html only the products that have particular slug and pk. Lets say kategorie/cat-4. Cat is the category.slug and the category.pk is 4 and i only wanna show the products that have this category and this pk. (Btw yes product is connected with Ecommerce via M2M) -
Multiple Widgets in Form Field - Django Forms
I'm working on a form in Django and it has a select element with a unique ID. This is what I'm currently doing: instance_type = forms.CharField(label='Instance Type', widget=forms.Select(choices=INSTANCE_TYPES), widget=forms.TextInput(attrs={'id':'instance_type'})) The problem is that Django is giving me a syntax error that says: SyntaxError: keyword argument repeated: widget I need to combine these two widgets into one, but haven't found a solution to it. Any help is appreciated. Thank you all! -
pipenv.exceptions.ResolutionFailure; ERROR: Disabling PEP 517 processing is invalid
I ran into what seems to be a dependency conflict when trying to run pipenv lock but can't seem to figure out what is causing this: [pipenv.exceptions.ResolutionFailure]: Warning: Your dependencies could not be resolved. You likely have a mismatch in your sub-dependencies. You can use $ pipenv install --skip-lock to bypass this mechanism, then run $ pipenv graph to inspect the situation. Hint: try $ pipenv lock --pre if it is a pre-release dependency. ERROR: Disabling PEP 517 processing is invalid: project specifies a build backend of setuptools.build_meta:__legacy__ in pyproject.toml I tried to debug using the suggested pipenv install --skip-lock and pipenv graph and wasn't able to spot any conflicts in the output below: bleach==4.1.0 - packaging [required: Any, installed: 21.3] - pyparsing [required: >=2.0.2,!=3.0.5, installed: 3.0.6] - six [required: >=1.9.0, installed: 1.16.0] - webencodings [required: Any, installed: 0.5.1] bpython==0.21 - curtsies [required: >=0.3.5, installed: 0.3.5] - blessings [required: >=1.5, installed: 1.7] - six [required: Any, installed: 1.16.0] - cwcwidth [required: Any, installed: 0.1.4] - cwcwidth [required: Any, installed: 0.1.4] - greenlet [required: Any, installed: 1.1.1] - pygments [required: Any, installed: 2.10.0] - pyxdg [required: Any, installed: 0.27] - requests [required: Any, installed: 2.26.0] - certifi [required: >=2017.4.17, installed: 2021.5.30] … -
Django: Script that executes many queries runs massively slower when executed from Admin view than when executed from shell
I have a script that loops through the rows of an external csv file (about 12,000 rows) and executes a single Model.objects.get() query to retrieve each item from the database (final product will be much more complicated but right now it's stripped down to the barest functionality possible to try to figure this out). For right now the path to the local csv file is hardcoded into the script. When I run the script through the shell using py manage.py runscript update_products_from_csv it runs in about 6 seconds. The ultimate goal is to be able to upload the csv through the admin and then have the script run from there. I've already been able to accomplish that, but the runtime when I do it that way takes more like 160 seconds. The view for that in the admin looks like... from .scripts import update_products_from_csv class CsvUploadForm(forms.Form): csv_file = forms.FileField(label='Upload CSV') @admin.register(Product) class ProductAdmin(admin.ModelAdmin): # list_display, list_filter, fieldsets, etc def changelist_view(self, request, extra_context=None): extra_context = extra_context or {} extra_context['csv_upload_form'] = CsvUploadForm() return super().changelist_view(request, extra_context=extra_context) def get_urls(self): urls = super().get_urls() new_urls = [path('upload-csv/', self.upload_csv),] return new_urls + urls def upload_csv(self, request): if request.method == 'POST': # csv_file = request.FILES['csv_file'].file # result_string = …