Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Stripe Webhook not consistent Statuscode 500 sometimes 201
L.S. I am working on my first Django project and struggling with the Stripe integration. My webhook is acting inconsistently—it worked fine when running locally on localhost with the Stripe CLI. However, after deploying with Nginx and Gunicorn, it has become unreliable. Sometimes it goes through, but in most cases, I receive a 500 status code. I want to send an email to the customer with a PDF attachment when the checkout.session.completed webhook is triggered. I read that the webhook should return a 200 status code as quickly as possible; otherwise, Stripe might time out. Or could the issue be caused by a time difference between the request and the server? Regardless, I’m unsure how to properly fix this. I’d really appreciate any guidance from someone with experience. import datetime import stripe from django.conf import settings from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt from webshop.models import Product, Customer, Order, OrderItem from django.core.mail import EmailMessage @csrf_exempt def stripe_webhook(request): payload = request.body sig_header = request.META.get("HTTP_STRIPE_SIGNATURE") endpoint_secret = settings.STRIPE_WEBHOOK_SECRET try: event = stripe.Webhook.construct_event( payload, sig_header, endpoint_secret ) except ValueError as e: return JsonResponse({"error": str(e)}, status=400) except stripe.error.SignatureVerificationError as e: return JsonResponse({"error": "Invalid signature"}, status=400) # Handle checkout success if event["type"] == "checkout.session.completed": … -
How to Prevent Screenshots and Screen Recording on a Payment Page (Django + Stripe Checkout)
I am working on a Django-based e-commerce website with Stripe Checkout for payments. I want to prevent users from taking screenshots or recording their screen on the payment page. ** What I Am Doing** Users are redirected to Stripe Checkout via a Django view: def checkout(request): session = stripe.checkout.Session.create( payment_method_types=['card'], line_items=[{"price_data": {...}, "quantity": 1}], mode='payment', success_url="https://yourdomain.com/success/", cancel_url="https://yourdomain.com/cancel/", ) return redirect(session.url) The checkout URL looks like: https://checkout.stripe.com/c/pay/cs_test_a1iAFc5as6... ** What I Want to Achieve** Block screenshots (PrtSc, Snipping Tool, etc.) Prevent screen recording software Stop screen-sharing via Zoom, Google Meet, etc. ** My Questions** How can I prevent screenshots and screen recording? Is this possible in a web browser, or only in mobile apps? What is the most secure way to implement this? Any guidance would be greatly appreciated! -
@action got an unexpected keyword argument 'id'
class CustomUserViewSet(UserViewSet): serializer_class = UserSerializer pagination_class = PageNumberPagination permission_classes = [permissions.IsAuthenticated] def get_queryset(self): queryset = User.objects.all() return queryset @action(detail=False, methods=['put', 'delete'], url_path='me/avatar') def set_avatar(self, request): if request.method == 'PUT': serializer = SetAvatarSerializer( request.user, data=request.data, partial=True ) serializer.is_valid(raise_exception=True) serializer.save() return Response(status=status.HTTP_200_OK) user = request.user user.avatar.delete() user.save() return Response(status=status.HTTP_204_NO_CONTENT) @action(detail=True, methods=['post', 'delete'], url_path='subscribe') def set_or_delete_subscribe(self, request, pk=None): user = request.user user_to_subscribe = self.kwargs['id'] if request.method == 'POST': _, created = Subscription.objects.get_or_create(user=user, subscribed=user_to_subscribe) if created: return Response(status=status.HTTP_201_CREATED) return Response(status=status.HTTP_400_BAD_REQUEST) if request.method == 'DELETE': subscription = Subscription.objects.filter(user=user, subscribed=user_to_subscribe).delete() if subscription: return Response(status=status.HTTP_204_NO_CONTENT) return Response(status=status.HTTP_400_BAD_REQUEST) model of Subscription class Subscription(models.Model): user = models.ForeignKey( User, on_delete=models.CASCADE, related_name='subscriptions' ) subscribed = models.ForeignKey( User, on_delete=models.CASCADE, related_name='subscribed' ) class Meta: constraints = [ models.UniqueConstraint(fields=['user', 'subscribed'], name='unique_subscription') ] urls router = DefaultRouter() router.register(r'tags', TagViewSet, basename='tags') router.register(r'recipes', RecipeViewSet, basename='recipes') router.register(r'ingredients', IngridientsViewSet, basename='ingredients') router.register(r'users', CustomUserViewSet, basename='users') TypeError: set_or_delete_subscribe() got an unexpected keyword argument 'id' [10/Mar/2025 08:38:23] "POST /api/users/11/subscribe/ HTTP/1.0" 500 88724 I can't figure out why get_object() expects id and doesn't accept pk ? Ьaybe I'm missing something, but I can't catch it. I need to subscribe to a user or delete them if already subscribed. -
Problem with the vite django integration (TypeError)
I'm currently working on integrating Vite with my Django project using the django-vite package. However, upon running the Django development server, I encounter the following error: TypeError: django_vite.core.asset_loader.DjangoViteConfig() argument after ** must be a mapping, not bool Project Setup: Django Version: 5.1.5 django-vite Version: [Specify Version] Vite Configuration: The vite.config.js is set to output build files to Django's static directory, and the manifest is enabled. Django Settings: django_vite is added to INSTALLED_APPS. DJANGO_VITE configuration is defined as follows: DJANGO_VITE = { "dev_mode": DEBUG, "manifest_path": os.path.join(BASE_DIR, "static", "manifest.json"), "static_url_prefix": STATIC_URL, } vite.config.ts export default defineConfig({ plugins: [react(), tailwindcss()], test: { globals: true, environment: "jsdom", setupFiles: "./src/setupTests.js", include: ["**/__tests__/**/*.{js,jsx,ts,tsx}"], }, base: "/static/", // Entspricht dem STATIC_URL in Django build: { outDir: "../backend/static/", // Pfad zum statischen Ordner von Django manifest: true, rollupOptions: { input: "src/main.jsx", // Haupteinstiegspunkt }, }, }); Error Details: The traceback indicates the error originates from the DjangoViteConfig class in the django_vite package: File "path_to_python_env\Lib\site-packages\django_vite\core\asset_loader.py", line 731, in _apply_django_vite_settings config = DjangoViteConfig(**config) TypeError: django_vite.core.asset_loader.DjangoViteConfig() argument after ** must be a mapping, not bool Configuration Verification: Ensured that the DJANGO_VITE settings are correctly defined as a dictionary. Dependencies Check: Verified that all related packages are up-to-date and compatible with each … -
Why is authenticate in drf not working and how do I make it work?
I am using Django with rest framework. Sign Up works fine, but when I log in, after passing the email and password to the backend, the authenticate() returns None even if the credentials are right. I am using a custom user model. Here are the relevant lines of code: models.py (does not include all fields) class CustomUserManager(BaseUserManager): def create_user(self, email, password, **kwargs): if not email: raise ValueError('The user must enter a valid email.') email = self.normalize_email(email) user = self.model(email=email, **kwargs) user.set_password(password) user.save() return user def create_superuser(self, email, password, **kwargs): kwargs.setdefault('is_staff', True) kwargs.setdefault('is_superuser', True) kwargs.setdefault('is_active', True) if kwargs.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if kwargs.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self.create_user(email, password, **kwargs) class CustomUser(AbstractBaseUser, PermissionsMixin): user_id = models.AutoField(primary_key=True) first_name = models.CharField(max_length=255, blank=True) middle_name = models.CharField(max_length=255, blank=True) last_name = models.CharField(max_length=255, blank=True) email = models.EmailField(unique=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) objects = CustomUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name'] groups = models.ManyToManyField( "auth.Group", related_name="customuser_set", blank=True ) user_permissions = models.ManyToManyField( "auth.Permission", related_name="customuser_set", blank=True ) viewsets.py @action(detail=False, methods=["post"], permission_classes=[AllowAny]) def login(self, request): email = request.data.get("email") password = request.data.get("password") user = CustomUser.objects.get(email=email) print(user) user = authenticate(request, email=email, password=password) # this returns None all … -
Django views' tests return 403 code instead of (presumably) 302
I'm testing views in my Django app. As the app is a backend of a forum site, I'm trying to test the creation, editing and deletion of a topic. Creation, editing and deletion of a topic are implemented in my app to work via redirect: create page redirects to a succefully created topic's page; editing the topic's initial comment redirects from the editing page to the edited topic's page; deletion page redirects to a subforum (a chapter of a forum) where the deleted topic had belonged. I presume (I'm not sure; and, most possibly, here is my mistake) that the successful redirect code is 302, and in the tests' assertion that's the code which should be checked. But for creation and editing of the topics tests return code 200, while for deletion test - code 403. And I, due to the lack of experience, hardly can explain why it happens this way and how to deal with it. views.py: class TopicListView(FilterView): paginate_by = 20 model = Topic template_name = "forum/subforum.html" slug_url_kwarg = 'subforum_slug' context_object_name = 'topics' filterset_class = TopicFilter def get_queryset(self): qs = self.model.objects.all() if self.kwargs.get('subforum_slug'): qs = qs.filter(subforum__slug=self.kwargs['subforum_slug']) return qs class ShowTopic(DetailView): model = Topic template_name = "forum/topic.html" slug_url_kwarg … -
How to save multiple related Django ORM instances in one go without separate database calls via the network?
Here is the example: article1 = Article(title="Global Warming", content="...") article2 = Article(title="Visiting Mars", content="...") comment1 = Comment(content="Some comment", article=article1) user1 = User(username="user1") some_updated_article.title = "updated title" article_to_delete.delete() In SQLAlchemy, I know you can save multiple instances to the database in one call as follows: db.session.add_all([article1, article2, comment1, user1]) db.session.commit() This approach sends all instructions to the database in one go (please correct me if I'm wrong). db.session.add_all() followed by db.session.commit() would work, and there wouldn’t be three separate calls to the database server. In Django, I know I can use bulk_create , bulk_update, for each model: Article.objects.bulk_create([article1, article2]) Comment.objects.bulk_create([comment1]) User.objects.bulk_create([user1]) Article.objects.bulk_update([some_updated_article], fields=["title"]) But this sends separate calls to the database server for each model. Is there a way to achieve something similar to SQLAlchemy's add_all() where I can send all objects in one go, regardless of the model? I was thinking about using transaction.atomic for this: with transaction.atomic(): Article.objects.bulk_create([article1, article2]) Comment.objects.bulk_create([comment1]) User.objects.bulk_create([user1]) Article.objects.bulk_update([some_updated_article], fields=["title"]) Using transaction.atomic() ensures that all operations either succeed or fail as one atomic transaction. However, in my use case, I don't want full rollback behavior. For example, if there’s an error while creating comments, I want to still save the articles and users successfully. I know … -
Django JSONField values aren't returned as a correct JSON-format in template when extracted using javascript
I have a model like class UserGroup(models.Model): owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, unique=False, related_name="group_owner") name = models.CharField(max_length=128) group_users = models.JSONField(models.EmailField(), default=list, blank=True) def get_absolute_url(self): return reverse("user_group_instance", kwargs={"pk": self.pk}) now, in my in another app I filter for a list of UserGroup instances for the given user, and I parse that query-set to a ModelMultipleChoiceField. That works fine and such, the issue is that I want to extract the group_users in the template and add them to an array, using java-script, thus I have create a div which stores the (I would assume) json-array in the data-members attribute <div id="group-modal"> {% for group in form.groups.field.queryset %} <label> <input type="checkbox" class="group-checkbox" value="{{ group.id }}" data-members="{{ group.group_users|safe }}"> {{ group.name }} </label> <br> {% endfor %} </div> now, when I in javascript get the data from the data-members the returned string is not a json-object e.g it is "['hello@world', 'foo@bar']". The javascript is (simplified) document.getElementById("save-groups").addEventListener("click", function() { let selectedPeople = []; document.querySelectorAll(".group-checkbox:checked").forEach(checkbox => { let members = JSON.parse(checkbox.getAttribute("data-members")); selectedPeople = [...new Set([...selectedPeople, ...members])]; }); and the JSON.parse fails. I simply cannot wrap my head around why; I don't do any manually serialization of the json-data thus I let django do that stuff. I could … -
i am trying to save data into mongodb doc, but its showing "a bytes-like object is required, not 'str'"
this is my code where error is apering while saving it is showing "a bytes-like object is required, not 'str'" error try: print(f'user ids : {current_user_ids} type : {type(current_user_ids)}') print(f'user email : {current_user_emails} type : {type(current_user_emails)}') group_obj.user_ids = json_user_ids.encode('utf-8') group_obj.user_emails = json_user_emails.encode('utf-8') group_obj.edited_at = timezone.now() group_obj.save() refreshed_group = Groups.objects.get(group_name=group) print(f'refreshed group data : {refreshed_group.user_emails}') except Exception as e: print(f'error occurred while saving group details : {e}') try: group_obj.user_ids = current_user_ids group_obj.user_emails = current_user_emails group_obj.save() except Exception as e: print(f'error saving group second time : {str(e)}') this is my models we are using jsonfield for user_ids and user_emails with default list class Groups(models.Model): group_id = models.UUIDField(primary_key=True, editable=False, default=uuid.uuid4, unique=True) group_id_str = models.CharField(max_length=100, null=True, blank=True, default='') group_name = models.CharField(max_length=100, null=True, blank=True) description = models.CharField(max_length=5000, null=True, blank=True) type = models.CharField(max_length=100, null=True, blank=True) cid = models.CharField(max_length=100, null=True, blank=True) user_ids = models.JSONField(default=list) user_emails = models.JSONField(default=list) created_at = models.DateTimeField(null=True, blank=True) edited_at = models.DateTimeField(null=True, blank=True) this is my groups MongoDB doc where user_ids and user_emails { "_id": { "$oid": "67c836a30b81d0c7f42f264c" }, "id": 148, "group_id": { "$binary": { "base64": "AHUV7hIpSWCu5mc7/gBC1w==", "subType": "03" } }, "group_id_str": "007515ee-1229-4960-aee6-673bfe0042d7", "group_name": "group-200-1", "description": null, "type": null, "cid": "650d3ba581d379707a3d2fa7", "user_ids": "[\"622c08ae-bae4-474c-8f6d-4f5c1e981b54\", \"b857e8e5-a96f-4cac-b96a-240aaea01ee6\"]", "user_emails": "[\"user2710-11@gmail.com\", \"user2710-1111@gmail.com\"]", "created_at": { "$date": "2025-03-05T11:33:55.301Z" }, "edited_at": { "$date": … -
How do I only query paginated data in django?
I have successfully paginated when returning all the objects but however, when I query the return for the searched result, it initially gets the correct pagination number of page. But clicking on any of the paginated searched result will immediately return the pagination of all the objects. My HTML pagination <ul class="pagination center" id="pagination" hx-swap-oob="true"> {% if data.has_previous %} <li class="waves-effect"> <a href="?page={{ data.previous_page_number }}"><i class="material-icons"><</i></a> </li> {% endif %} {% for page in data.paginator.page_range %} {% if page == data.number %} <li class="active purple lighten-2"><a href="?page={{ page }}">{{page}}</a></li> {% else %} <li class="waves-effect"><a href="?page={{ page }}">{{page}}</a></li> {% endif %} {% endfor %} {% if data.has_next %} <li class="waves-effect"> <a href="?page={{data.next_page_number}}"><i class="material-icons">></i></a> </li> {% endif %} </ul> paginate function and views.py, when i use AI, it shows me to change the html code, but i cannot understand it and i've spent hours to find something that mentions this very well and haven't found one def paginate(data, request): paginator = Paginator(data, 10) page_number = request.GET.get('page') data = paginator.get_page(page_number) return data def submission_portal(request): data = DataEntry.objects.all() data = paginate(data=data, request=request) text_count = DataEntry.objects.filter(category='text').count() image_url_count = DataEntry.objects.filter(category='image_url').count() context = { 'data': data, 'text_count': text_count, 'image_url_count': image_url_count } return render(request, 'submission_portal/submission_page.html', context=context) # Read … -
Django - Dictionary value set to returned as `None` in template but returns value in console
In my console I have this print: r_distance in context: {13: 7905.59} In my template, I get the following returned {13: None} , using: r_distance: {{ r_distance}} I dont understand what would turn the value to None in the my logic. views.py: for r in rps: if r.model_field: ref_v = rewardprogram.model_field if ref_v.latitude and ref_v.longitude and user_lat and user_lon: v_distance = distance.distance((user_lat, user_lon), (ref_v.latitude, ref_v.longitude)).km v_distance = round(v_distance, 2) r_distance[model.id] = v_distance # prints: {13: 7905.59} else: r_distance[model.id] = None context = { ... "r_distance": r_distance} } In my template: {% for r in rps%} <p>r_distance: {{ r_distance}}</p> # prints: {13: None} {% endfor %} Question: Considering r_distance is recognised in the template, it cannot be that the dictionaryy is not being passed to the template. The model object id is correct (13), why would the value not getting passed? -
It would be helpful if you explained the reason for using action in the search case?
Straightly, it works even if you don't give action to submit data on the login and registration pages. It would be helpful if you explained the reason for using action in the search case?? {% extends "base/index.html" %} {% load static %} {% block body %} <h1 class="display-4 text-center my-5">All Quizzes</h1> <div class="container"> <div class="d-flex"> <a href="{% url 'all_quizzes_view' %}" class="btn btn-light me-2">All Quiz</a> {% comment %} <a href="./all-quiz.html" class="btn btn-light me-2">English</a> {% endcomment %} {% for category in categories %} <a href="{% url 'cat_search' category.name %}" class="btn btn-sm btn-light m-1">{{category.name}}</a> {% endfor %} </div> </div> {% comment %} <form class="container d-flex my-4" role="search" method="get" action="{% url 'search' %}"> <input value="{{ query }}" name="q" class="form-control me-2" type="search" placeholder="Search" aria-label="Search"> <button type="submit" class="btn btn-primary ms-2">Search</button> </form> {% endcomment %} <form class="container d-flex my-4" role="search" method="get"> <input type="search" name="q" class="form-control me-2" placeholder="Search quizzes..." value=" " aria-label="Search"> <button type="submit" class="btn btn-primary ms-2">Search</button> </form> <div class="container"> <div class="row row-cols-1 row-cols-sm-1 row-cols-md-2 row-cols-lg-3 g-3"> {% if quizzes|length > 0 %} {% comment %} {{ quizzes|length }}, here quizzes object all properties will be counted {% endcomment %} {% for quiz in quizzes %} <div class="col"> <div class="card shadow-sm"> <div class="card-body"> <h4> {{quiz.title}} </h4> <p class="card-text">Total … -
Auth.jsx:38 POST http://127.0.0.1:8000/api/register/ 404 (Not Found) - Django / React
I'm trying to implement an authentication system and stack on the register part When I submit the form data I get back this error: POST http://127.0.0.1:8000/api/register/ 404 (Not Found) Here is some of my code url.py from django.urls import path from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView from .views import RegisterView, LoginView, RefreshTokenView urlpatterns = [ path("api/register/", RegisterView.as_view(), name="register"), path("api/login/", LoginView.as_view(), name="login"), path("api/token/refresh/", RefreshTokenView.as_view(), name="token_refresh"), ] view.py class RegisterView(APIView): permissions_classes = [AllowAny] def post(self, request): serializer = UserSerializer(data=request.data) if serializer.is_valid(): user = serializer.save() return Response({"message": "User registered succefully"}, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) On the client side; I have a utility that creates the baseURl import axios from "axios"; const API = axios.create({ baseURL: "http://127.0.0.1:8000/api/", headers: { "Content-Type": "application/json", } }); export default API; And my handleSubmit function looks like this; const handleSubmit = async (e) => { e.preventDefault(); setError(""); // Clear previous errors try { const endpoint = isSignup ? "register/" : "login/"; const response = await API.post(endpoint, formData); if (isSignup) { alert("Registration successful!"); setIsSignup(false); // Switch to login form } else { // Store JWT tokens localStorage.setItem("accessToken", response.data.access); localStorage.setItem("refreshToken", response.data.refresh); localStorage.setItem("role", response.data.role); console.log("Login successful:", response.data); alert("Login successful!"); const roleRedirects = { "admin": "/admin-dashboard", "student": "/student-dashboard", "lecturer": "/lecturer-dashboard", "academic_registrar": "/registrar-dashboard" }; window.location.href … -
Django: "Product matching query does not exist" After Stripe Payment
I am building a Django e-commerce website where users: Add products to the cart (stored in session) Complete Stripe payment Place an order Problem: After the payment, Django throws this error: An error occurred: Product matching query does not exist. The error happens when retrieving the Product model from the cart session data. ** My Session Data (Before Payment)** I print the session data before payment, and it looks like this: { 'cart_data_obj': { '71_32': { # Key format: productID_size 'title': 'Iphone 16 Black', 'qty': 1, 'price': '160000.00', 'image': '/media/user_1/iphone_4.jpg', 'pid': '71', # Product ID 'size': '32', 'old_price': '240000.00' } }, 'total_cart_items': 1, '_auth_user_id': '1' } Here, pid correctly exists in the session. ** My Cart View (Where Users See Their Cart)** View Code: def cart_view(request): cart_total_amount = 0 sub_category = SubCategory.objects.all() categories = Category.objects.prefetch_related('subcategories').order_by('?')[:4] wishlist = wishlist_model.objects.filter(user=request.user) if request.user.is_authenticated else None nav_category = Category.objects.filter(special_category=True).prefetch_related('subcategories').order_by('?')[:4] if 'cart_data_obj' in request.session: print(" Cart Data:", request.session['cart_data_obj']) # Debugging for p_id, item in request.session['cart_data_obj'].items(): try: item_price = float(item['price']) except (ValueError, TypeError): item_price = 0 item_quantity = int(item['qty']) cart_total_amount += item_quantity * item_price print(" Total Amount Before Discount:", cart_total_amount) return render(request, "core/cart.html", { "data": request.session['cart_data_obj'], "cart_total_amount": cart_total_amount, "sub_category": sub_category, "categories": categories, "w": wishlist, "nav_category": nav_category, … -
How can users modify cart prices using Burp Suite, and why is this a security risk in Django?
I recently discovered a serious security issue in Django e-commerce websites where users can modify product prices before adding items to the cart. Many developers allow users to send price data from the frontend, which can be easily tampered with using Burp Suite or browser developer tools. Example of the Issue: Consider a simple Django view that adds items to the cart: def add_item(request): product_id = request.GET.get('product_id') price = request.GET.get('price') # User-controlled value (security risk) qty = int(request.GET.get('qty', 1)) cart_item = { 'product_id': product_id, 'qty': qty, 'price': price, # This price comes from the user, not the database! } request.session['cart'] = request.session.get('cart', {}) request.session['cart'][product_id] = cart_item request.session.modified = True return JsonResponse({'message': 'Added to cart'}) How an Attacker Can Exploit This: A product costs $500 in the database. The user clicks "Add to Cart". Instead of sending the original price, the attacker intercepts the request using Burp Suite. The price field is changed to $1, and the request is forwarded. The cart now stores the manipulated price, and the user can proceed to checkout with the wrong amount. Why Is This a Security Risk? The backend trusts data from the frontend, which can be easily manipulated. The session stores the wrong … -
Django - ValueError at /selected-events/ Cannot assign ... must be a "Profile" instance
I have a Django project that consists of, essentially, 3 datasets: auth User (plus a Profile dataset), mem_ev and Events such that User --< mem_ev >-- Event, ie a classic many to many relationship such that members can go to many events and an event can be visited by many members. I want to update the mem_ev dataset with the 'events to be attended' selected by a member, but it's not working. my models.py file is: from django.db import models from django.utils.text import slugify from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) # Delete profile when user is deleted event_count = models.IntegerField(default=0) def __str__(self): return f'{self.user.username} Profile' #show how we want it to be displayed class Event(models.Model): title = models.CharField(max_length=50) slug = models.SlugField(max_length=50,default="", null=False) description = models.TextField() cost = models.DecimalField(max_digits = 5, decimal_places = 2, default = 0.0) event_date = models.DateTimeField(null=True,blank=True) attendees = models.IntegerField(default=0) class Meta: ordering = ['event_date'] def save(self, *args, **kwargs): self.slug = slugify(self.title) super(Event, self).save(*args, **kwargs) class Meta: ordering = ['event_date'] def __str__(self): return self.title class mem_ev(models.Model): member_id = models.ForeignKey("Profile",on_delete=models.CASCADE) event_id = models.ForeignKey("Event",on_delete=models.CASCADE) is_attending = models.BooleanField(default=False) amt_paid = models.DecimalField(max_digits = 5, decimal_places = 2, default = 0.0) date_paid = models.DateTimeField(null=True,blank=True) The relevant part of my … -
Django's SQL query has repeated subquery when using filters with annotations and subqueries
I have Camp Model that stores dates as an array of strings in a Json field. I'm trying to optimize a database query to retrieve Camp objects with future dates. class Camp(models.Model): dates = models.JSONField(default=None, blank=True, null=True, validators= [datesListValidator]) I'm using annotations and subqueries to filter out instances of that model where none of the dates are equal to or greater than the current date (basically I only want camps that have a date in the future). I'm using annotations and Subqueries to get the "max_date" from the dates for each camp and then filtering the camps based on the "max_date" I'm trying to optimize this filtering process, as getting all the camps and then filtering it in Python is too slow for my use case and as more time goes on the number of Camps that have to be filtered out would just keep increasing. The solution i came up with gives me the results I need, but the generated SQL query has multiple runs of the same subquery which I don't need. I'd like to avoid doing this using RawSQL and would like to find a way to achieve my desired result using the django ORM functions. I'm … -
How do I fix django.db.utils.OperationalError: no such table: when migrations don’t work?
Good day everyone, I’m a new intern and I’m trying to learn Django. I was tasked with looking over this new branch of the project that was recently updated. I downloaded a zip file from the github and I used this command python manage.py runserver then I got this error message django.db.utils.OperationalError: no such table: streaming_data_streaminginfo I tried using this command python manage.py makemigrations streaming_data but I’m still getting the same error. I tried python manage.py showmigrations and got the exact same error. Another possible solution is to delete and recreate the database but I don’t want to mess with the database. My supervisor told me to make a super user and connect on the admin page with my login credentials and go look at the tables. When I used python manage.py createsuperuser I got the django.db.utils.OperationalError: no such table: streaming_data_streaminginfo error again. So, I went to an older branch and opened the admin page, but I didn’t see the tables. Here's the complete error message PS C:\Users\OneDrive\Documents\music_data-map> python manage.py runserver Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\OneDrive\Documents\music_data-map\venv\Lib\site-packages\django\db\backends\utils.py", line 89, in _execute return self.cursor.execute(sql, params) ~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^ File … -
Getting 401 when attempting to signup or login in django allauth react-spa example
I am very new to using to Django-allauth, I'm wanting to integrate it with my Django backend. I was trying to use the react-spa example outlined in the docs https://react.demo.allauth.org/, but I 401 error when sending either a signup or login request. Why is this happening? The response looks like: { "status": 401, "data": { "flows": [ { "id": "login" }, { "id": "login_by_code" }, { "id": "signup" }, { "id": "provider_redirect", "providers": [ "dummy" ] }, { "id": "provider_token", "providers": [ "dummy" ] }, { "id": "mfa_login_webauthn" }, { "id": "verify_email", "is_pending": true } ] }, "meta": { "is_authenticated": false } } I understand that the flows array indicates those are the methods to authenticate. But how can I authenticate if the login / signup method preventing me from doing so? Steps to repro: I ran this example locally, cloned it here https://codeberg.org/allauth/django-allauth/src/branch/main/examples/react-spa Ran docker compose up Visit localhost:10000, when to signup - entered email and password + password confirmation. Request was successful and I was redirected to the enter email confirmation code screen I didn't input the code in step 3. Instead, went back to signup page to enter my actual email to get the code and input … -
Run EXE software using App in Windows IIS
I hosted my Django app on Windows IIS in Windows Server 2022 Standard But my application has a feature that opens software (.exe) and run specific user tasks provided in the request of the site. For example, a user provides some input from my site, and then it processes it with my app by opening software using python code in views.py script_path = "C:\inetpub\wwwroot\webapp\script\runthescript.py" subprocess.run(["C:/Program Files/My Soft/Soft.exe", "-runScriptFile", script_path]) MY PROBLEM When I tested my application locally using python manage.py runserver it was working due to admin privileges and session 1 access, but the same when I tried after hosting with IIS then everything working except software to start. WHAT I TRIED: I tried providing my AppPool Identity as (IIS APPPOOL\webapp) Administrator privileges. Tried using Task Scheduler, but it works with the background process but not with the GUI app. ISSUE When I googled it, I found that it is due to privileges and session 0 access. IIS has only session 0 isolation so that it is unable to access GUI. Your small help, idea or suggestion definitely be helpful for me. :) -
Pass value from one Django template to other
I want to build a Django template hierarchy like so: root.html |_ root-dashboard.html |_ root-regular.html root.html shall have an if statement: {% if style == "dashboard" %} {# render some elements in a certain way #} {% else %} {# render those elements in a different way #} {% endif %} And root-dashboard.html and root-regular.html should individually extend root.html by setting style: # root-dashboard.html {% extend 'root.html' with style='dashboard'%} # root-regular.html {% extend 'root.html' with style='regular'%} (with above is not an actual valid syntax, its just something similar I want) And a view can use either root-dashboard.html or root-regular.html to show the content in one style or the other. How do I achieve this without the view having to set the style context? -
How to handle authentication and AUTH_USER_MODEL in Django multi-tenant with separate databases?
I’m developing a multi-tenant SaaS application using Django, where each tenant has its own separate database with its own schema and relationships. However, I'm struggling with how to properly manage authentication and define AUTH_USER_MODEL in this environment. 📌 System Requirements Global superadmins that manage the system and are stored in the public database (public). Tenant users, who exist in their respective tenant database and have relationships with other tables inside their own database. Separate authentication: Superadmins should authenticate in the public database. Tenant users should authenticate within their specific tenant database. The main problem is that Django allows only one AUTH_USER_MODEL, but I need to manage users separately for each tenant while maintaining the ability to associate them with other tables within their respective databases. ❌ Current Issue If I define a single user model in AUTH_USER_MODEL, I cannot differentiate between global superadmins and tenant users, nor can I correctly manage relationships within each database. I tried defining two different user models, but Django does not allow multiple AUTH_USER_MODEL, which complicates authentication. ✅ Possible Solution I thought of defining a base model BaseUser that extends AbstractUser, and then creating two inherited models. But I am not sure which is the … -
I am trying to run uwsg-emporer vassal and it can't find my python
When I create a uwsgi vassal ini file, the server throws this error when I hit the site: --- no python application found, check your startup logs for errors --- The virtualenv is correct and if I do python manage.py check I do not have errors and python manage.py runserver runs a dev version fine. I first source in my venv so I know python is installed in the Virtual Envelope at this path: /var/www/webapps/lhhs/env this is my .ini file [uwsgi] uid = www-data socket = /var/www/webapps/lhhs/lhhs.sock chown-socket = %(uid):www-data chmod-socket = 660 chdir = /var/www/webapps/lhhs/ virtualenv = /var/www/webapps/lhhs/env binary-path = /var/www/webapps/lhhs/env/bin/uwsgi modue = lhhs.wsgi:application wsgi-file = lhhs/wsgi.py env = DJANGO_SETTINGS_MODULE=lhhs.settings.dev module = django.core.handlers.wsgi:WSGIHandler() stats = 127.0.0.1:9191 vacuum = true processes = 1 threads = 1 plugins = python3,logfile logger = file:/var/www/webapps/lhhs/log/uwsgi.log -
request.method == POST equaling true in next function causing it to run prematurely
so i am running this code def login_or_join(request): if request.method == "POST": option = request.POST.get("option") print('post request recieved') if option == "1": return login_screen(request) if option == '2': return in_game(request) return render(request,"login_or_join.html") and def login_screen() looks like this def login_screen(request): if request.method == "POST": username = request.POST.get("username") password = request.POSt.get("password") print(username) print(password) user = authenticate(request, username=username, password=password) print(user) if user is not None: return redirect('join_lobby') else: return render('login_page.html', {'error': 'Invalid login credentials' }) return render(request, 'login_page.html') Whenever I click "option 1" it runs login_screen but in a way I don't want it to. it seems to just follow that request.method == "POST" and prints username and password immediately, meaning it is setting username and password immediately making any log in attempt wrong. But I don't want it to set those (or print them) until I've pressed the button on the next page. Further more when I hit "enter" or "log in" it doesn't reshow the page with the error message, it just goes back login_or_join(). I feel like I am taking crazy pills as I've been working on this website for a while and this is the first time I'm having this kind of issue. I've tried messing with it … -
Django syntax highlighting/intellisense not working for undefined class methods
I'm working in a python/django repo and I'm having an issue where unknown methods are not being highlighted by VSCode with a red error squiggly line. As you can see from the screenshot, I have it setup to show python errors, but the non-existent method on the test_email class doesn't throw any errors or warnings. I have Black Formatter, isort, Pylance, Python, Pylint, Python Debugger extensions installed. The correct python interpreter + environment are setup and the python language server is also running. I'm happy to include any other information, but didn't want to dump unneeded info. Any insight, help or guidance is greatly appreciated!