Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
How to join data from two API in Python
So, far I have only used get/post data from one API at a time. I am not sure how can I join data from two API. Similar like SQL, is there a some sort of Join tables to achieve same with the API? I would like to display staff photos with other staff details in html template. API 1 https://test.com/api/Staff/GetStaffDetails StaffId, Firstname, Lastname, Email API 2 https://test.com/api/Staff/GetStaffPhotos Id (this matches with the StaffId), Photo Staff Details def StaffDetails(request, *, context): url = "https://test.com/api/Staff/GetStaffDetails" headers = { "X-DOMAIN": "test", "X-TOKEN": "123456789qwertyuiop", "User-Agent": "", } response = requests.post(url, headers=headers) data = response.json() random_data = random.sample(data, min(5, len(data))) context = {"data": random_data} return render(request, "StaffDetails.html", context) StaffDetails.html <table border="1"> <tr> <td>STAFFID</td> <td>FIRSTNAME</td> <td>LASTNAME</td> <td>EMAIL</td> </tr> {% for row in data %} <tr> <td>{{ row.StaffId }}</td> <td>{{ row.Firstname }}</td> <td>{{ row.Lastname }}</td> <td>{{ row.Email }}</td> </tr> {% endfor %} </table> Staff Photo def StaffPhoto(request, *, context): url = "https://test.com/api/Staff/GetStaffPhotos" headers = { "X-DOMAIN": "test", "X-TOKEN": "123456789qwertyuiop", "User-Agent": "", } response = requests.post(url, headers=headers) data = response.json() random_data = random.sample(data, min(5, len(data))) context = {"data": random_data} return render(request, "StaffPhoto.html", context) StaffPhoto.html <table border="1"> <tr> <td>ID</td> <td>PHOTO</td> </tr> {% for row in data %} <tr> <td>{{ … -
Mixin for making third-party Django model fields typed
Given the problem that not all libraries add type annotations, I am trying to build a mixin that would allow me to add type hints easily. Without that, the type-checker infers the type of the model instance field as that of the underlying built-in field’s value (e.g., str, int, date, etc.) that the custom field is built upon (or Unknown). Here is an example: from django.db import models # ========== defined in a third-party library ========== class StructuredCountry: iso_code: str ... class CountryField(models.CharField): # Not shown: the textual value from the database # is converted to a StructuredCountry object. pass # ========== defined in my own code ==================== class MyModel(models.Model): country = CountryField() reveal_type(MyModel().country) # ⇒ str MyModel().country.iso_code # E: Attribute "iso_code" is unknown For the above example, I would like to be able to: class TypedCountryField(FieldAnnotationMixin, CountryField): pass class MyModel(models.Model): country = TypedCountryField() reveal_type(MyModel().country) # ⇒ StructuredCountry MyModel().country.iso_code # ✔ So far I have come up with the following (inspired by VSCode’s stubs), which indeed works. if TYPE_CHECKING: class FieldAnnotationMixin[FieldClassType: type[models.Field], ValueType]: def __new__(cls, *args, **kwargs) -> FieldClassType: ... # Class access @overload def __get__(self, instance: None, owner: Any) -> Self: ... # type: ignore[overload] # Model instance access … -
pythonanywhere - ModuleNotFoundError: No module named 'posthog'
I'm uploading my django web app project to pythonanywhere and I'm getting this error : ModuleNotFoundError: No module named 'posthog' I tried following the pythonanywhere.com page that talks about debugging import error issues but I'm confused on how to go about it wsgi: import os import sys path = '/home/Shalz/UniHustle_back_iv' if path not in sys.path: sys.path.append(path) os.environ['DJANGO_SETTINGS_MODULE'] = 'unihustle.settings' from django.core.wsgi import get_wsgi_application application = get_wsgi_application() in my settings.py file, I have import posthog posthog does not appear in my requirements.txt file though, despite installing it via my project terminal. -
ORA-00001: unique constraint (SDESERP.UK_CODELKUP) violated, django inlineformset
Hi I am trying to create a form with parent-child models using python Django Inlineformset_factory but when I am trying to update the child, its giving me unique constraint error. Here I am sharing my model code, forms code, views code. I am trying to solve this issue since last two days but not succeeded. please help me to solve the issue. Models code--> class CodeList(models.Model): listname = models.CharField(db_column='LISTNAME', max_length=20, primary_key=True) description = models.CharField(db_column='DESCRIPTION', max_length=100) adddate = models.DateField(db_column='ADDDATE') addwho = models.CharField(db_column='ADDWHO', max_length=20) editdate = models.DateField(db_column='EDITDATE') editwho = models.CharField(db_column='EDITWHO', max_length=20) class Meta: db_table ='CODELIST' def __str__(self): return f"{self.listname}" class CodeLkup(models.Model): listname = models.ForeignKey(CodeList, db_column='LISTNAME', on_delete=models.CASCADE) code = models.CharField(db_column='CODE', max_length=30, primary_key=True) #, eng_desc = models.CharField(db_column='ENG_DESC', max_length=250) bl_desc = models.CharField(db_column='BL_DESC', max_length=250, blank=True) adddate = models.DateField(db_column='ADDDATE') addwho = models.CharField(db_column='ADDWHO', max_length=20) editdate = models.DateField(db_column='EDITDATE') editwho = models.CharField(db_column='EDITWHO', max_length=20) class Meta: db_table = 'CODELKUP' unique_together = ('listname', 'code') def __str__(self): return f"{self.code}-{self.eng_desc}"``` forms code--> class CodeListForm(forms.ModelForm): class Meta: model = CodeList fields = ['listname','description'] widgets ={ 'listname' : forms.TextInput(attrs={'class' : 'form-control form-control-sm', 'autocomplete' : 'off'}), 'description' : forms.TextInput(attrs= {'class' : 'form-control form-control-sm' , 'autocomplete' : 'off'}) } def __init__(self, *args, **kwargs): is_edit = kwargs.pop('is_edit', False) self.request = kwargs.pop('request', None) super(CodeListForm, self).__init__(*args, **kwargs) if is_edit: self.fields['listname'].widget.attrs['readonly']=True def … -
Im trying to create an order for my application i have a big issue with the webhook
@login_required def cart_detail(request): # Try to fetch the cart for the logged-in user cart = Cart.objects.filter(user=request.user).first() if not cart or not cart.items.exists(): # Ensure that cart has items # If no cart exists or cart is empty, pass a flag to indicate an empty cart context = {'cart_exists': False} return render(request, 'services/cart_detail.html', context) # Calculate the total price for the cart total_price = sum(item.total_price() for item in cart.items.all()) context = { 'cart': cart, 'total_price': total_price, 'cart_exists': True, 'STRIPE_PUBLISHABLE_KEY': settings.STRIPE_PUBLISHABLE_KEY, } return render(request, 'services/cart_detail.html', context) Payment is initiated with the cart detail goes to create checkout class CreateCheckoutSessionView(View): def post(self, request, *args, **kwargs): cart = get_object_or_404(Cart, user=request.user) if not cart.items.exists(): return JsonResponse({'error': 'Cart is empty'}, status=400) line_items = [] total_price = 0 # To calculate total price of the cart for the order # Prepare line items for Stripe for item in cart.items.all(): name = item.plan.name if item.plan else item.extra_service.title amount = int(item.get_price() * 100) # Amount in cents for Stripe total_price += item.total_price() line_items.append({ 'price_data': { 'currency': 'usd', 'unit_amount': amount, 'product_data': { 'name': name, }, }, 'quantity': item.quantity, }) success_url = request.build_absolute_uri('/success/') cancel_url = request.build_absolute_uri('/cancel/') # Create Stripe Checkout session checkout_session = stripe.checkout.Session.create( payment_method_types=['card'], line_items=line_items, mode='payment', success_url=success_url, cancel_url=cancel_url, ) # … -
Using Password Recovery system in django.contrib.auth through email
In my Django project I am trying to use user password management as provided in django.contrib.auth. My set up works as expected (and as explained in Django docs) except: password recovery through Email, when the sites options (django.contrib.sites and SITE_ID) are added in settings.py. Before adding the sites options, the password recovery "link" (received in terminal console) would be something like: http://127.0.0.1:8000/reset/MQ/xxx123-11111a0c4a6czz43b314b089a544v666hhh2/ In the this instance (sites options are not added), using the link brings up the Password reset page as expected. However, after the sites options are added, the link received changes to be: http://example.com/reset/MQ/xxx123-11111a0c4a6czz43b314b089a544v666hhh2/ In the 2nd instance (i.e. received link starting with domain example.com), the password reset page does not show up (browser issues a message: No internet). If sites domain and name field values are changed (in Admin) and changed to say, xyz.com; the link received changes to: http://<domain>/reset/MQ/xxx123-11111a0c4a6czz43b314b089a544v666hhh2/ and in this case also, the Password reset page fails to show up (with a message like): `This site can’t be reached` As the process for implementing password recovery is well documented, I am not adding them here. My question is: Why does the recovery system fails when sites options are added to settings.py? Is it possible … -
having an error while hosting a django website on a heroic suggest me some good platform [closed]
I have made a website using django and purchased a domain on go daddy but could not find any platform to host. found one heroic but having some error into vs code while trying to install heroku. Any idea where can I host it ?? suggest me guys -
Django ValueError: Cannot query "instructor": Must be "User" instance
I'm getting the following error when trying to access my homepage: ValueError at / Cannot query "instructor": Must be "User" instance. Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 5.2 Exception Type: ValueError Exception Value: Cannot query "instructor": Must be "User" instance. Exception Location: C:\Users\User LENOVO\OneDrive\Bureau\E-Learning\venv\Lib\site- packages\django\db\models\sql\query.py, line 1346, in check_query_object_type Raised during: base.views.Accueille class User(AbstractUser): instructor = models.BooleanField(default=False) # ... other fields class Course(models.Model): title = models.CharField(max_length=255) description = models.TextField() instructor = models.ForeignKey(User, on_delete=models.CASCADE, related_name='courses') # ... other fields class Home(View): def get(self, request): try: courses = Course.objects.select_related('instructor').all() # ... rest of the view -
How to Deploy Django API without zero downtime?
I have a Django API project that I need to deploy using CI/CD on an on-premises Linux server without requiring maintenance. because previous build user can using without downtime how to deploy new build version. I need to Deploy Django API without downtime to Linux server -
How can i use yopmail as django email backend?
I Wanted to use yopmail as my Django Email Service can anyone know about how to use this? Using yopmail service as django email backend. Curious to learn different email service in django. yopmail is one the temporary mail service so wanted to learn such service in my django project in staging.