Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Reverse for "not found." is not a valid view or function name error [closed]
I am working on my major project for software engineering in highschool and I keep coming up with this error when I run my Django project. I followed the tutorials set out by my teacher but I still don't know what's going on. This is the error message that keeps coming up. Reverse for "not found." is not a valid view or function name. This is my project urls.py file """ Software_Engineering_Major_Project URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.urls import path,include import Dark_Library_store.Urls urlpatterns = [ path('',include('Dark_Library_store.Urls')), ] This is my app Urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('store/', views.Store, name='store'), path('featured/', views.Featured, name='featured'), path('cart/', views.Cart, name='cart'), path('contact/', views.Contact, name='contact'), path('login/', views.Login, name='login'), path('sign_up/', views.Sign_up, name='sign_up'), ] This is my … -
django image cropping error : 'ImageField' object has no attribute 'image_field'
I am using Amazon S3 as File Storage. I tried to use django image chopping 1.7 to handle photo it works for showing image without django image chopping on website and I read official documentation cover_photo = models.ImageField(upload_to='package_inner_photos', null=True, blank=True) cover_photo_cropping = ImageRatioField('inner_photo',free_crop=True) {% if package.cover_photo %}style="background-image: linear-gradient(rgba(0,0,0,0.1), rgba(0,0,0,0.1)), url('{{ package.cover_photo.url }}');"{% endif %} it can show the photo but no cropping effect, of coz however {% load cropping %} {% if package.cover_photo %},url('{% cropped_thumbnail package "cover_photo" %}');"{% endif %} debug page show the error that 'ImageField' object has no attribute 'image_field' Django generated thumbnail file on Amazon S3 actually I double checked particular entries p = Package.objects.get(slug="ozen-reserve-bolifushi") print(p.inner_photo) print(p.cover_photo.name) print(p.cover_photo.url) it return the file name correctly I made Amazon S3 ACL almost public, I am not sure which part go wrong. Can anyone help please? -
Django Crispy Forms with Tailwind CSS 4.0: Unwanted downward caret appears within the form
I'm using: Django 5.2.1 Tailwind CSS 4.0 crispy-tailwind 1.0.3 django-crispy-forms 2.4 I am using the Tailwind template pack, which is defined in my settings.py. When I render my form in my template 'concert_form.html' using crispy-forms, a large upside-down caret symbol appears after one of the fields in the middle of the form. If I comment out crispy-forms, then the form renders properly. Using the developer tools, with crispy-forms active, I can see there is a new in the code with an svg definition. That is not present with crispy-forms inactive. The only CSS I'm using is what is generated from the tailwind --watch command. Is there any way I can control crispy-forms to prevent this from happening? Here are the relevant code sections: concert_form.html html {% extends "_base.html" %} {% load tailwind_filters %} ... <div class="bg-white rounded-lg shadow-lg p-6"> <form method="post" class="space-y-6"> {% csrf_token %} {% form|crispy %} <div class="flex justify-end space-x-3 pt-4"> ... the balance of the code, navigation buttons to 'Cancel' or 'Submit' the form models.py python from django.db import models from django.urls import reverse class ConcertForm(forms.ModelForm): name = models.CharField(max_length=100) date = models.DateField() time = models.TimeField() venue = models.ForeignKey(Venue, on_delete=models.CASCADE) conductor = models.ManyToManyField(Conductor, blank=True) guests = models.ManyToManyField(Guest, blank=True) … -
Stripe InvalidRequestError at /subscription/ Request req_F6PVTyTtfDXnIf: You passed an empty string for 'line_items[0][price]'. We assume empty values
I am trying to set a subscription service on my website using Django. models.py from django.db import models from django.contrib.auth.models import User from django.utils.timezone import now class Subscription(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) customer_id= models.CharField(max_length=255) subscription_id = models.CharField(max_length=225, unique=True) product_name = models.CharField(max_length=255) price = models.IntegerField() interval = models.CharField(max_length=50, default="month") start_date = models.DateTimeField(null=True, blank=True) end_date = models.DateTimeField(null=True, blank=True) canceled_at = models.DateTimeField(null=True, blank=True) @property def is_active(self): if self.end_date: if now() < self.enddate: return True else: return False else: return True @property def tier(self): tier_mapping = { 'Basic Membership': 1, 'Premium Membership':2, 'Pro Membership':3, } tier = tier_mapping.get(self.product_name, None) return tier def __str__(self): return f"{self.user.username} - {self.product_name} Active: {self.is_active}" views.py from django.shortcuts import render, redirect, reverse import stripe from django.conf import settings stripe.api_key = settings.STRIPE_SECRET_KEY def subscription_view(request): subscription = { 'Basic Membership' :'price_1RNgLNIoFyCdZSrgu83irObA', 'premium' :'price_1RNgLvIoFyCdZSrg9j87OiP7', 'pro' :'price_1RNgMUIoFyCdZSrgEIxgO9HP', } if request.method == 'POST': if not request.user.is_authenticated: return redirect(f"{reverse('account_login')}?next={request.get_full_path()}") price_id = request.POST.get('price_id') checkout_session = stripe.checkout.Session.create( line_items=[ { 'price':price_id, 'quantity':1, }, ], payment_method_types=['card'], mode='subscription', success_url = request.build_absolute_uri(reverse("create_subscription")) + f'?session_id={{CHECKOUT_SESSION_ID}}', cancel_url=request.build_absolute_uri(f'{reverse("subscription")}'), customer_email=request.user.email, metadata={ 'user_id': request.user.id, } ) return redirect(checkout_session.url, code=303) return render(request, 'a_subscription/subscription.html', {'subscription' : subscription}) def create_subscription(request): #create subscription object in database return redirect('my_sub') def my_sub_view(request): return render(request, 'a_subscription/my-sub.html') Error message: InvalidRequestError at /subscription/ Request req_F6PVTyTtfDXnIf: You … -
How to send video(mp4) as a response
I need to know how i can send a video file as a response in django. React+Django this is my djanog code which is handling the request. u/csrf_exempt def get_video(request): view_logger.info("Fetching video") try: if not LOGS_FOLDER_PATH: view_logger.warning("LOGS FOLDER PATH not present") return HttpResponseNotFound("Logs folder path not set.") videos_path = os.path.join(LOGS_FOLDER_PATH, "videos") if not os.path.exists(videos_path): return HttpResponseNotFound("Videos folder does not exist.") videos_list = os.listdir(videos_path) if not videos_list: return HttpResponseNotFound("No videos found.") video_path = os.path.join(videos_path, videos_list[0]) view_logger.info(f"Video path:- {video_path}") video_response = FileResponse( open(video_path, 'rb'), ) view_logger.info(f"\n\n\n{video_response}") return video_response except Exception as error: view_logger.error(f"Error fetching terminal video. Error: {error}") return JsonResponse({'error': 'Internal server error'}, status=500) LOGS_FOLDER_PATH - I can't add this as static cuz I receive this during runtime. React Code:- import React from "react"; import "./CSS/VideoDisplay.css"; const VideoDisplay = ({ api_url_name }) => { return ( <div className="video-display-div"> <video width="100%" controls aria-label="video"> <source src={`${api_url_name}/api/dashboard/get-video/`} type="video/mp4" /> Your browser does not support the video tag. </video> </div> ); }; export default VideoDisplay; I tried returning the video as response using FileResponse but the video is not displaying the Frontend. -
Django ModelForm not prepopulating fields when updating instance – "This field is required" errors
I'm making a project in Django--UniTest. The idea is to let our university's faculty create and conduct online surprise tests on it. The issue I'm facing is with the update_test.html page which is not prepopulating the data. Here's the view function. @login_required def update_test(request, test_id): test = get_object_or_404(Test, id=test_id) questions = test.questions.all() print(test) print(test.name, test.course, test.batch, test.total_marks, test.total_questions, test.duration) if request.method == 'POST': form = testForm(request.POST, instance=test) print("Form Data:", request.POST) print("Form Errors:", form.errors) print(form.initial) # Check if the form is valid # and if the test ID matches the one in the URL if form.is_valid(): form.save() # Update questions and choices for question in questions: question_text = request.POST.get(f"question_{question.id}") question_marks = request.POST.get(f"question_marks_{question.id}") question.text = question_text question.marks = question_marks question.save() # Update choices for each question for choice in question.choices.all(): choice_text = request.POST.get(f"choice_{question.id}_{choice.id}") is_correct = request.POST.get(f"is_correct_{question.id}_{choice.id}") is not None choice.text = choice_text choice.is_correct = is_correct choice.save() return redirect('list_tests') else: form = testForm(instance=test) return render(request, 'update_test.html', {'form': form, 'test': test, 'questions': questions}) Output: Dummy | Computer Networking 2 | BCA | 3 marks | 2 questions Dummy Computer Networking 2 | CSE309 BCA | 2022-2025 | 4th sem | A 3 2 10:00:00 Form Data: <QueryDict: {'csrfmiddlewaretoken': ['7WtmPpjyY1Ww1cCRuRxEOpwKmESSSjVv8jXToOQ5PSb4MEU5tZXgA93tUwzkGTeU']}> Form Errors: <ul class="errorlist"><li>name<ul class="errorlist"><li>This … -
Is it possible to use DRF's datetime picker and include the UTC offset for timestamps in the response JSON?
I am trying to use the Web browsable API in Django Rest Framework. I have objects with timestamp data in this format, "2025-05-08T22:02:58.869000-07:00". But the required format for Django's datetime picker does not support UTC offset or the last three significant digits for microseconds as shown below: I can trim the input data to satisfy the datetime picker like this: class MillisecondDateTimeField(serializers.DateTimeField): def to_representation(self, value): return value.astimezone().strftime("%Y-%m-%dT%H:%M:%S") + ".{:03d}".format( int(value.microsecond / 1000) ) But then the UTC offset is also missing from the timestamp in the POST/PUT response. { ... "start_datetime": "2025-05-08T22:02:58.869", ... } How can I make the value for "start_datetime" appear as "2025-05-08T22:02:58.869000-07:00" in the JSON response from POST/PUT while also using "2025-05-08T22:02:58.869" in the datetime picker? I have been researching online and trying for days. -
How can I set a javascript const to a value in a form element that could be either a dropdown select or a checked radio button?
I have an html form in a django site that is used for both add and update. If the form is for a new entry, I want the field estimateType to be radio buttons with three choices, one of which is checked by default. If the form is for an edit to an existing entry, I want the form widget to change to a select dropdown with additional choices to pick from. In the javascript in the onchange event, I need to know what the value of the estimateType field is. I can get it to work for select, or radio input, but not both. For example, what I have right now is: const estimateType = document.querySelector(input[name=estimateType]:checked).value; That works for a radio button but not the select dropdown. How can I use the same const declaration but account for heterogeneous form input types? -
Django filter objects which JSONField value contains in another model's JSONField values LIST of same "key"
I'm not sure if the title of this post made you understand the problem but let me explain: I have models: class ItemCategory(models.Model): name = CharField() class Item(models.Model): brand = CharField() model = CharField() category = ForeignKey(ItemCategory) attributes = JSONField(default=dict) # e.g {"size": 1000, "power": 250} class StockItem(models.Model): item = ForeignKey(Item) stock = ForeignKey(Stock) quantity = PositiveIntegerField() This models represent some articles on stock. Now I want to implement functionality to allow user create "abstract container" where he can input data and monitor how many of "abstract containers" may be produced based on stock remainings. Example: class Container(models.Model): name = CharField() class ContainerItem(models.Model): container = models.ForeignKey(Container) item_category = models.ForeignKey(ItemCategory) attributes = models.JSONField(default=dict) quantity = models.PositiveIntegerField() To handle aggregation I build a view: class ContainerListView(ListView): model = models.Container def get_queryset(self): items_quantity_sq = models.Item.objects.filter( item_category=OuterRef('item_category'), attributes__contains=OuterRef('attributes'), ).values('item_category').annotate( total_quantity=Sum('stock_items__quantity') ).values('total_quantity') min_available_sq = models.ContainerItem.objects.filter( container_id=OuterRef('pk') ).annotate( available=Coalesce(Subquery(items_quantity_sq), Value(0)) ).order_by('available').values('available')[:1] base_qs = super().get_queryset().annotate( # Attach the minimum available quantity across all items potential=Subquery(min_available_sq) ).prefetch_related( Prefetch( "items", queryset=models.ContainerItem.objects.all() .annotate(available=Subquery(items_quantity_sq)) .order_by("available"), ) ) return base_qs.order_by("potential") It works until ContainerItem attributes field contains a single value: {"size": 1000} but I want to allow user to input multiple values ("size": [1000, 800]) to find all Item objects which attributes … -
How to create a form Django (names and elements) from a column of a DataFrame or QuerySet column.?
How can I create a form - even if it's not a Django form, but a regular one via input? So that the names and elements of the form fields are taken from a column of a DataFrame or QuerySet column. I would like the form fields not to be set initially, but to be the result of data processing - in the form of data from a column of a DataFrame or QuerySet column. The name of the form fields to fill in from the data in Views. Maybe send a list or a single DataFrame or QuerySet to the template via JINJA? from django import forms # creating a form class InputForm(forms.Form): first_name = forms.CharField(max_length = 200) last_name = forms.CharField(max_length = 200) roll_number = forms.IntegerField( help_text = "Enter 6 digit roll number" ) password = forms.CharField(widget = forms.PasswordInput()) from django.shortcuts import render from .forms import InputForm # Create your views here. def home_view(request): context ={} context['form']= InputForm() return render(request, "home.html", context) <form action = "" method = "post"> {% csrf_token %} <table> {{ form.as_table }} </table> <input type="submit" value="Submit"> </form> How to create a form Django (names and elements of the form fields) from a column of a … -
Django Application: Model field or app for conditions
I'm currently planning a Django-application that runs jobs regurarly based on conditions. Regurarly the application should check if any of the jobs has the conditions met and should run those with positive outcome. Think of the conditions of an automation in HomeAssistant as an example of what I'm trying to construct. I also want to include "OR" or "AND" conditions to link multiple conditions together. Ideally a frontend component should allow for comfortable editing these conditions. As I already initiated to implement it as a JSON-Field with a custom syntax that is checked in a method inside the model. But it seems to be such a common problem to me, that I'm sure someone has already developed an app for that. But unfortunately I was not able to find anything in that direction - maybe because of lack of words. Has anybody a pointer to for an application? -
Django PWA not installable on android
I have develop a simple django PWA project (without the published django-pwa app) to test for offline features. I have deployed my project on pythonanywhere: lecarrou.pythonanywhere.com. When I get my app in my desktop, my app is installable (Chrome and Edge). But I have issues when trying to install on android mobile (Chrome, Edge, Firefox). I have tested many configurations (last following django-pwa structure) but I never get option to install app and beforeinstallprompt event seems not to be fired. I have build manifest.json following 'rules'. I debug using Chrome DevTools : Service worker is activated manifest is available (display:standalone ; Icons are available ; start_url and scope: '/') As many tests I've made : console.log(window.matchMedia('display-mode: standalone)).'matches) return false fired manually beforeinstallprompt but failed I have open and navigate many times in my app on Chrome for several days. I have no idea what is going wrong and how I can solve this issue. #serviceworker.js const CACHE_NAME = "cdss-cache-v1"; const urlsToCache = [ '/', '/cdss/select/', '/cdss/screening/', '/cdss/scoring/', '/cdss/recommandation/', '/static/css/styles.css', '/static/js/script.js', '/static/materialize/css/materialize.min.css', '/static/materialize/js/materialize.min.js', '/static/fonts/fonts.css', '/static/fonts/lobster-v30-latin-regular.woff2', '/static/fonts/material-icons-v143-latin-regular.woff2', '/static/pwa/images/icons/72x72.png', '/static/pwa/images/icons/96x96.png', '/static/pwa/images/icons/128x128.png', '/static/pwa/images/icons/144x144.png', '/static/pwa/images/icons/152x152.png', '/static/pwa/images/icons/192x192.png', '/static/pwa/images/icons/384x384.png', '/static/pwa/images/icons/512x512.png', '/static/pwa/images/icons/favicon.ico', // '/static/admin/' // ajoute toutes les routes et fichiers nécessaires pour le mode offline ]; self.addEventListener("install", … -
Flutter local api connection wont work on Emulator/Android sid
I created an endpoint on my Django app like: /accounts/api/login/. It checks the login inputs and returns JSON. On the Visual Studio Code side, the flutter run command allows me to log in successfully. But if I try the app on the Android Studio Emulator or my Android mobile, the same log occurs: 2025-05-13 11:25:45.485 11034-11034 flutter com.example.depo_app I Login Exception: Connection failed 2025-05-13 11:25:45.485 11034-11034 flutter com.example.depo_app I #0 IOClient.send (package:http/src/io_client.dart:94) 2025-05-13 11:25:45.485 11034-11034 flutter com.example.depo_app I <asynchronous suspension> 2025-05-13 11:25:45.485 11034-11034 flutter com.example.depo_app I #1 BaseClient._sendUnstreamed (package:http/src/base_client.dart:93) 2025-05-13 11:25:45.485 11034-11034 flutter com.example.depo_app I <asynchronous suspension> 2025-05-13 11:25:45.485 11034-11034 flutter com.example.depo_app I #2 _withClient (package:http/http.dart:166) 2025-05-13 11:25:45.485 11034-11034 flutter com.example.depo_app I <asynchronous suspension> 2025-05-13 11:25:45.485 11034-11034 flutter com.example.depo_app I #3 _LoginPageState._login (package:depo_app/main.dart:76) 2025-05-13 11:25:45.485 11034-11034 flutter com.example.depo_app I <asynchronous suspension> 2025-05-13 11:25:45.485 11034-11034 flutter com.example.depo_app I I think it's happening because the web side is not https, but my system needs to work on a local server. I tried to use the runserver_plus ... --cert-file ... method too, but this time, pyOpenSSL library installation errors occurred, and I gave up. Any ideas about the Flutter side or publishing Django side for https would be awesome. However, solving the issue … -
Django runserver fails with "AttributeError: class must define a 'type' attribute" when using Python 3.13
python manage.py runserver But I get the following traceback: Traceback (most recent call last): File "C:\Users...\manage.py", line 22, in main() ... File "...django\core\files\locks.py", line 32, in from ctypes import ( File "...\Python313\Lib\ctypes_init_.py", line 157, in class py_object(_SimpleCData): AttributeError: class must define a 'type' attribute -
FieldError at /chat/search/ Unsupported lookup 'groupchat_name' for CharField or join on the field not permitted
I'm trying to be able to search chat groups by looking up the chatroom name. I'm using Django Q query... models.py class ChatGroup(models.Model): group_name = models.CharField(max_length=128, unique=True, default=shortuuid.uuid) groupchat_name = models.CharField(max_length=128, null=True, blank=True) picture = models.ImageField(upload_to='uploads/profile_pictures', default='uploads/profile_pictures/default.png', blank=True) about = models.TextField(max_length=500, blank=True, null=True) admin = models.ForeignKey(User, related_name='groupchats', blank=True, null=True, on_delete=models.SET_NULL) users_online = models.ManyToManyField(User, related_name='online_in_groups', blank=True) members = models.ManyToManyField(User, related_name='chat_groups', blank=True) is_private = models.BooleanField(default=False) def __str__(self): return self.group_name views.py from django.db.models import Q class ChatSearch(View): def get(self, request, *args, **kwargs): query = self.request.GET.get('chat-query') chatroom_list = ChatGroup.objects.filter( Q(group_name__groupchat_name__icontains=query) ) context = { 'chatroom_list': chatroom_list } return render(request, 'chat/search.html', context) `` -
Using django-okta-auth library: Problem Circular Login while running in LocalHost
I have been using the Okta platform and Django to develop a web application, and I am facing a situation in my localhost that I can't seem to circumvent. I sign into the Okta Sign-In Widget, it brings me to the Okta Verify and then redirects back to Okta Sign-In Widget in a circular pattern. I have the setup as follows for my settings.py: INSTALLED_APPS = [ 'appname', 'okta_oauth2.apps.OktaOauth2Config', 'rest_framework', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] 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', 'okta_oauth2.middleware.OktaMiddleware' ] AUTHENTICATION_BACKENDS = [ "okta_oauth2.backend.OktaBackend", ] OKTA_AUTH = { "ORG_URL": "dev.okta.com", "ISSUER": "https://dev.okta.com/oauth2/default", "CLIENT_ID": os.getenv("client_id"), "CLIENT_SECRET": os.getenv("client_secret"), "SCOPES": "openid profile email offline_access", # this is the default and can be omitted "REDIRECT_URI": "http://localhost:8000/accounts/oauth2/callback", "LOGIN_REDIRECT_URL": "http://localhost:8000/redirect-user/", # default "CACHE_PREFIX": "okta", # default "CACHE_ALIAS": "default", # default "PUBLIC_NAMED_URLS": (), # default "PUBLIC_URLS": (), # default "USE_USERNAME": False, # default } I have the redirect_URI defined in my Okta dev box, and the login_redirect_url as well. This is my apps urls.py: urlpatterns = [ path('admin/', admin.site.urls), path('accounts/', include(("okta_oauth2.urls", "okta_oauth2"), namespace="okta_oauth2")), path('accounts/login/', okta_views.login, name='login'), path('accounts/oauth2/callback', views.custom_callback, name='callback'), path('redirect-user/', view=views.login_redirect_view), path('appname/Admin/', include("admin.urls")), ] I have the following views.py: import logging logger = logging.getLogger("okta") def custom_callback(request): logger.info("==> Entered … -
Django allauth social account autoconnect
I got a Django-allauth backed site with legacy local users most of which eventually should be connected to social login upon their next sign-in, whenever that might be. Only supported social provider is Microsoft Graph. All emails from the provider are to be treated as verified, and in case it matches any existing user, these are also treated as the same user without further verification. Relevant allauth settings as below: ACCOUNT_LOGIN_METHODS = {"email"} ACCOUNT_USER_MODEL_USERNAME_FIELD = None SOCIALACCOUNT_PROVIDERS = { "microsoft": { "EMAIL_AUTHENTICATION_AUTO_CONNECT": True, "EMAIL_AUTHENTICATION": True, "EMAIL_VERIFICATION": False, "VERIFIED_EMAIL": True, "APPS": [ #client id, secret masked ] } } Signing in with a social account that has its e-mail registered (and which should be connected upon login) works, but no connected social account is created. Signing in with a social account without an existing user creates a new user with the respective social account as expected and desired. If I write my own hooks to customized SocialAccountAdapter (or add receivers to allauth's signals), I can achieve my target, but at least according to my interpretation of the allauth documentation, this seems a bit hacky and does not seem like the intended way in the current version. Allauth version is 65.7.0 -
Django test database creation fails: permission denied to create extension vector
poetry run python manage.py test minigames.test.models response in terminal: The currently activated Python version 3.12.9 is not supported by the project (^3.13). Trying to find and use a compatible version. Using python3.13 (3.13.3) Found 4 test(s). Creating test database for alias 'default'... Got an error creating the test database: database "test_aivector_db" already exists Type 'yes' if you would like to try deleting the test database 'test_aivector_db', or 'no' to cancel: This is a consistent issue I am facing I have already assigned superuser permission to this db, and also some times it never happens (mostly it resolves or stopes asking after I change the port (from 5432 to 5431)) but when i type yes it gives error that super user permission required to create vector extension (it is already created in db) but as i understand Django test creates a test db separately I don't think a superuser test db is possible but what I understand from all the previous attempts that this is issue with not deleting the previous test db or I maybe completely wrong. here is the error I get if I type 'yes': Creating test database for alias 'default'... Got an error creating the test database: … -
Trying to deploy Django web app on PythonAnywhere, "no python application found"
I have a Django web app (Python 3.11) that runs on Azure, and I'm trying to migrate it to PythonAnywhere. I've followed the setup instructions. The web page itself says "Internal Server Error". The error log is empty. The server log has the following: --- no python application found, check your startup logs for errors --- as well as a most peculiar 'import math' error (see below) that may be relevant. (Starting python in my virtual environment, I'm unable to import anything there either, so possibly a PYTHONPATH or other env problem?) Where are these startup logs? I assume something is just pointing to the wrong place, I just need the information to work out what. The server log in more detail: 2025-05-12 11:23:16 SIGINT/SIGTERM received...killing workers... 2025-05-12 11:23:17 worker 1 buried after 1 seconds 2025-05-12 11:23:17 goodbye to uWSGI. 2025-05-12 11:23:17 VACUUM: unix socket /var/sockets/avoca999.eu.pythonanywhere.com/socket removed. 2025-05-12 11:23:23 *** Starting uWSGI 2.0.28 (64bit) on [Mon May 12 11:23:22 2025] *** 2025-05-12 11:23:23 compiled with version: 11.4.0 on 16 January 2025 20:41:13 2025-05-12 11:23:23 os: Linux-6.5.0-1022-aws #22~22.04.1-Ubuntu SMP Fri Jun 14 16:31:00 UTC 2024 2025-05-12 11:23:23 nodename: blue-euweb3 2025-05-12 11:23:23 machine: x86_64 2025-05-12 11:23:23 clock source: unix 2025-05-12 11:23:23 pcre … -
./manage.py runserver on mac
I'm setting up a new dev environment for Django development on a mac as a new Python dev but I'm receiving an error running a basic django app so I think my python setup is incorrect I have python3 installed so to make it easy to access, in my .zshrc I have added the line alias python='python3' I have used homebrew to install python, django-admin, pipx as well as python-language-server and ruff-lsp and installed jedi-language-server via pipx as a basic setup for helix I have used the dango ninja tutorial to get a project started django-admin startproject ninjaapidemo cd ninjaapidemo which gives me a project structure # ~/dev/ninjaapidemo . ├── manage.py └── ninjaapidemo ├── __init__.py ├── asgi.py ├── settings.py ├── urls.py └── wsgi.py I have updated urls.py to the following (as per the django ninja tutorial) from django.contrib import admin from django.urls import path from ninja import NinjaAPI api = NinjaAPI() @api.get("/add") def add(request, a: int, b: int): return {"result": a + b} urlpatterns = [path("admin/", admin.site.urls), path("api/", api.urls)] and attempted to run the project from ~/dev/ninjaapidemo ./manage.py runserver but I get the following error env: python: No such file or directory Can anyone make a recommendation for what I'm … -
Scroll and nesting issues when rendering multiple reports with Leaflet on a single HTML page
I'm generating a combined report in Django by looping through several database entries and rendering the same HTML template multiple times, each with different data. The template includes Leaflet maps and some inline scripts. The problem is: when I combine the reports into a single page, the layout breaks — it looks like the reports are either nested inside each other or overlapping. I also see multiple scrollbars (one inside another), which shouldn't happen. This only occurs when I render several reports together. Each individual report works fine on its own. The issue only appears when I generate them together in a loop. Any help or direction would be appreciated. -
Orderby and distinct at the same time
I have tabels like this id sku 1 C 2 B 3 C 4 A Finally I want to get the raws like this. 1 C 2 B 4 A At first I use distinct queryset = self.filter_queryset(queryset.order_by('sku').distinct('sku')) It depicts the raw like this, 4 A 1 C 2 B Then now I want to sort this with id, queryset = queryset.order_by('id') However it shows error like this, django.db.utils.ProgrammingError: SELECT DISTINCT ON expressions must match initial ORDER BY expressions LINE 1: SELECT DISTINCT ON ("defapp_log"."sku") "d... -
Django: Applying Multiple Coupons Adds Discounts Incorrectly Instead of Sequentially
I'm building a Django e-commerce checkout system where multiple coupon codes can be applied. Each coupon can be either a fixed amount or a percentage. Coupons are stored in a Coupon model, and applied coupons are tracked in the session. Problem: Suppose I have a product costing ₹30,000. When I apply the first coupon CODE001 (10% discount), the total should become ₹27,000. Then I apply the second coupon CODE002 (90% discount), which should apply on ₹27,000, making the final total ₹2,700. But currently, both coupons are being applied independently on the full cart total of ₹30,000, not on the discounted total. So the discount appears as ₹30,000 for both coupons. My Current View Logic: In the view, I'm looping over all the applied coupons like this: if 'applied_coupon_codes' in request.session: applied_coupon_codes = request.session['applied_coupon_codes'] applied_coupons = [] for code in applied_coupon_codes: try: coupon = Coupon.objects.get(code__iexact=code, is_active=True) if coupon.valid_to >= timezone.now() and cart_total_amount >= float(coupon.min_cart_total): applied_coupons.append(coupon) if coupon.discount_type == 'percent': percent_discount = (cart_total_amount * coupon.discount_value) / 100 if coupon.max_discount_value is not None: percent_discount = min(percent_discount, coupon.max_discount_value) coupon_discount += percent_discount else: coupon_discount += float(coupon.discount_value) except Coupon.DoesNotExist: continue Here, cart_total_amount is used for each coupon, so all coupons calculate their discount on the full … -
Django Static Files Not Uploading to Digital Ocean Spaces Despite Correct Configuration
I'm having issues with Django's static files not being uploaded to Digital Ocean Spaces (S3-compatible storage) in production since I've upgraded to Django 5.2 from 4.2. As part of this upgrade I also updated python, boto3 and django-storages. The collectstatic command appears to run successfully locally, but files are not being updated in the Spaces bucket. Additionally, some static files (particularly CSS) are being served as downloads instead of being rendered in the browser. Current Setup Django 5.2 Digital Ocean Spaces (S3-compatible storage) Custom storage backend using django-storages Production environment (DEBUG=False) Here is my Pipfile using pipenv for dependencies [[source]] url = "https://pypi.org/simple" verify_ssl = true name = "pypi" [packages] django = "==5.2" pillow = "*" python-dotenv = "*" stripe = "*" mailchimp-marketing = "*" dotenv = "*" gunicorn = "*" psycopg2 = "*" django-storages = "==1.14.2" boto3 = "==1.34.69" weasyprint = "*" [dev-packages] [requires] python_version = "3.12" Configuration # settings.py (production settings) AWS_ACCESS_KEY_ID = os.getenv('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.getenv('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = 'equine-pro' AWS_S3_ENDPOINT_URL = 'https://ams3.digitaloceanspaces.com' AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', 'ACL': 'public-read' } AWS_DEFAULT_ACL = 'public-read' AWS_LOCATION = 'static' AWS_S3_CUSTOM_DOMAIN = 'equine-pro.ams3.cdn.digitaloceanspaces.com' AWS_S3_REGION_NAME = 'ams3' AWS_S3_FILE_OVERWRITE = True AWS_QUERYSTRING_AUTH = False AWS_S3_VERIFY = True AWS_S3_SIGNATURE_VERSION = 's3v4' AWS_S3_ADDRESSING_STYLE = 'virtual' … -
ModuleNotFoundError: No module named 'rest_framework_simplejwt'. I have tried the methods listed in other posts
I am building an authentication system with the JWT token. I have done pip install djangorestframework-simplejwt and pip install --upgrade djangorestframework-simplejwt in my virtual environment. This is my installed-apps in settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework_simplejwt', 'rest_framework_simplejwt.token_blacklist', ] And here is my urls.py: from django.contrib import admin from django.urls import path, include from api.views import CreateUserView from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView urlpatterns = [ path("admin/", admin.site.urls), path("api/user/register",CreateUserView.as_view(), name="register"), path("api/token/",TokenObtainPairView().as_view(),name="get_token"), path("api/token/refresh/",TokenRefreshView.as_view(),name="refresh"), path("api-auth/", include("rest_framework.urls")) ] I have these on my pip list: django-rest-framework 0.1.0 djangorestframework 3.16.0 djangorestframework-jwt 1.11.0 djangorestframework_simplejwt 5.5.0 pip 25.1.1 PyJWT 1.7.1 python-dotenv 1.1.0 pytz 2025.2 rest-framework-simplejwt 0.0.2 But when I run the code, it still says ModuleNotFoundError: No module named 'rest_framework_simplejwt'. I have checked the documentation and other posts. Is there anything else I am missing?