Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
OG text and image are not showing in a format i want
So I have a django project where I have written OG info for facebook, <meta property="og:type" content="website" /> <meta property="og:image" content="{% block og_image %}{{ request.scheme }}://{{ request.get_host }}{% static 'HRCP-FB.png' %}{% endblock %}" /> So the problem is that when i share that link of FB, it gives me preview-"An image above and texts under that",I want to have a small image on the left and content on the right, I searched for the answers and read that you need to have "Website" in the OG:TYPE,so i changed article to website,after that i tested the url in the facebook sharing debugger but it is showing me the article(yes i have updated/scraped again the debugger, also i have checked whereas there is an article or website in the page source too and "website is there"),but on the other hand "Ahrefs seo extension" shows me that there is a website written in there and not Article,So i have waited ,i thought it needed time but no,The article is there not too. After that i searched more and read that image must be 1200x600 or smth, so I resized my 500x500 image to 1200x600 and uploaded it, but it gives me the same … -
Azure WebJobs won't get triggered from Azure Storage Queue
Context I am using Python 3.12 / Linux setup on Azure I have deployed Django on Azure Web Services I also have Django Celery deployed as Azure WebJobs on the same service Problem The celery runs absolutely fine. However, when I set up a trigger from the storage queue, it doesn't work. I try by manually sending a message in the Queue. Here are some code for reference function.json { "bindings": [ { "name": "myQueueItem", "type": "queueTrigger", "direction": "in", "queueName": "%AZURE_STORAGE_QUEUE_NAME%", "connection": "AzureWebJobsStorage" } ], "disabled": false } settings.job { "stopping_wait_time": 60, "is_singleton": true } run.sh #!/bin/bash # Activate the Python environment echo "Triggerd" Attempts I was initially trying Managed Identity so I set up following environment variables (or app settings) AzureWebJobsStorage__credential: 'managedidentity' AzureWebJobsStorage__accountName: storageAccount.name AzureWebJobsStorage__queueServiceUri: 'https://${storageAccount.name}.queue.${storageSuffix}/' I have also attempted to setup via Connection String. I copied from Azure Storage Account UI/UX. I was able to connect from my local system. I have tried combination of 1 and 2 along with different configuration in function.json, nothing works. -
Django - Queryset with manytomany related values
With Django, I want to build a queryset with related objects from a ManyToManyField relation. My goal is to aggregate related values in a list, as a group by or string_agg in SQL. Here is my setup: models.py class BaseModel(models.Model): id = models.UUIDField( primary_key = True, default = uuid.uuid4, editable = False, verbose_name='identifier') created_at = models.DateTimeField(auto_now_add=True, verbose_name='created at') updated_at = models.DateTimeField(auto_now=True, verbose_name='last update') class Meta: abstract = True class Topping(BaseModel): name = models.CharField(max_length=100, blank=False, unique=True, verbose_name='topping') def __str__(self): return self.name class Pizza(BaseModel): name = models.CharField(max_length=100, blank=False, verbose_name='nom') fk_toppings = models.ManyToManyField(Topping, default=None, related_name='toppings_data', verbose_name='toppings') def __str__(self): return f"{self.name} - {self.fk_toppings}" views.py class PizzaView(TemplateView): def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) qs = Pizza.objects.all() print(qs) header = list(qs.values().first().keys()) print(f"Header: {header}") context['pizzas'] = qs return context Returned queryset doesn't display any related objects: <QuerySet [<Pizza: Margherita - my_app.Topping.None>]> And header doesn't contains the ManyToManyField field: Header: ['id', 'created_at', 'updated_at', 'name'] Why fk_toppings isn't here ? How to get a queryset with a list of related objects like: <QuerySet [<Pizza: Margherita - (Basil, Mozzarella, Tomato)]> I found this package, but I'm surprised there isn't any build-in method in Django ORM to make this standard relational operation. -
How to save Oracle specific tables into a MySQL database?
I have two databases MySQL and Oracle. I create a view to get data from Oracle and display it into HTML template. I want to add every selected row (from the table on HTML template) into MySQL table. Is it possible to do that? -
How to Build a Django App for Manipulating VuFind Records Using PySolr?
I am working on a project where I need to fetch, manipulate, and manage metadata records stored in a VuFind Solr index. The goal is to create a Django-based application that leverages PySolr to: Fetch data from the VuFind Solr core. Search and edit records within the Solr index. Identify and manage duplicates, including: (Finding duplicate records based on specific fields; Merging duplicate records; Standardize records by normalizing data in selected fields) I've written some custom code to interact with VuFind's Solr core, but I am facing challenges with: Efficient querying for large datasets (e.g., searching through millions of records). Implementing a robust deduplication logic (considering multiple fields and weighted matching). Updating records in Solr without affecting unrelated data. Designing a user-friendly interface for reviewing, editing, and merging records. Code execution issue: When I run the code, it doesn't execute properly. The browser doesn't open, and I can't figure out what might be going wrong. here is the full code file