Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
WebSocket Streaming Not Working in Django + Next.js — Only Getting First and Final Message
I'm building a ai chat app with Django (Channels) for the backend and Next.js for the frontend. The goal is to stream AI-generated responses chunk by chunk over a WebSocket connection — similar to how a REST API with ReadableStream works. However, on the frontend, Its only displaying the first chunk then final completed message, not the intermediate streaming chunks. Here’s a simplified version of my setup: Backend (Django WebSocket Consumer): I’m using an async generator (handle_chat_request) to produce message chunks. async def receive(self, text_data): logging.info(f"WebSocket message received: {text_data}") try: data = json.loads(text_data) message_type = data.get("type") if message_type == "message": jwt_token = data.get("token") if not jwt_token: await self.send(json.dumps({"type": "error", "message": "Missing Authorization token."})) await self.close(code=4001) return user_message = data.get("content") user_id = data.get("user_id") combined_response = "" # Stream response chunks async for chunk in handle_chat_request(user_message, user_id, jwt_token): combined_response += chunk await self.send(json.dumps({"type": "ai_response_chunk", "content": chunk})) await asyncio.sleep(0) # Yield control to allow chunk sending # Send final complete message await self.send(json.dumps({"type": "ai_response_complete", "content": combined_response})) except Exception as e: logging.error(f"WebSocket error: {e}") await self.send(json.dumps({"type": "error", "message": "An error occurred."})) Frontend (Next.js WebSocket Client): I’m listening for incoming chunks and trying to append them to the latest bot message: const handleWebSocketMessage = (event) … -
How to resolve VSCode Pylance type checking error in Django
I'm encountering a type checking error in VSCode with Pylance when accessing serializer.validated_data["code"] in a Django project. The errors are: "__getitem__" method not defined on type "empty" Pylance Object of type "None" is not subscriptable Pylance The property type is inferred as: (property) validated_data: empty | Unknown | dict[Unknown, Unknown] | Any | None VSCode settings: "python.languageServer": "Pylance", "python.analysis.typeCheckingMode": "basic" I've defined the serializer class like, class InputSerializer(BaseSerializer): code = serializers.CharField( required=True, max_length=255, validators=[voucher_code_validator], ) How can I fix this? -
Failed to load resource: the server responded with a status of 401 (Unauthorized) - react & django
Am facing a crisis in my authentication system, during registration some of the fields like first and lastname, password, etc are not stored in the database which makes the login attempts return a 401 error, I have also tested with postman and in preview it shows invalid credentials. I have put a print statement in my registerView class to check if all the data fields reach the backend and it shows that indeed they do class RegisterView(APIView): permission_classes = [AllowAny] def post(self, request): print("Incoming Data from React:", request.data) 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) I have tried to play with my register serializer class which i believe might be causing the issues just to ensure that the missing fields can also be saved to the database but still not achieving results class RegisterSerializer(serializers.ModelSerializer): class Meta: model = User fields = [ 'first_name', 'last_name', 'username', 'email', 'password', 'confirm_password', 'role', 'student_number', 'course_name', 'college', 'lecture_number', 'subject_taught', 'department' ] extra_kwargs = { 'password': {'write_only': True}, 'confirm_passwaord': {'write_only': True} } def validate(self, data): if data['password'] != data['confirm_password']: raise serializers.ValidationError({"password": "Passwords do not match."}) role = data.get('role') if role == 'student': if not all([data.get('student_number'), data.get('course_name'), … -
How do I enable a disabled button after moderators input some text into textarea using `hx-on`?
I want to disable the "Yes" button until moderators of my Django site provide a reason for banning users. Once the reason is provided in the textarea, then the "Yes" button would be enabled. It's a common pattern I've encountered when using React and Javascript, but since I'm using HTML and Django Templates for this project, I want to use HTMX for some interactivity. I'm still new using HTMX, so I'd appreciate some help, thanks! I've checked the questions on here, and I didn't find any answers for my question. Or am I using hx-on:input wrong in this context? I've also tried using hx-on:change but to no avail. I've looked into hx-disabled-elt but I don't think that's what I want. Because I'm not submitting a request just yet, I just want some interactivity for my form. I've also looked at this question but this requires me to communicate with the server, which I would like to minimise if I can. This is what I have currently and I'm not sure why it's not working: <form method="POST"> {% csrf_token %} <p>Please provide the reason for the ban.</p> <div class="input-group"> <textarea class="form-control" aria-label="Reason for ban" name="reason-for-ban" hx-on:input="htmx.removeClass(htmx.find(#yes-ban-this-user), 'disabled')"> </textarea> </div> <input type="submit" … -
Adding Markers to OpenStreetMap's Django/Python
I'm having issues with leaflet, and OpenStreetMap I cannot get a marker to be added for each job available. it just shows up as a blank map. Debugging shows that the information is being sent correctly but the map is not update. Here is the debug info. The list view works perfectly. and the map shows a correct marker when clicking on job from list view. (0.001) SELECT "users_job"."id", "users_job"."title", "users_job"."description", "users_job"."city", "users_job"."state", "users_job"."zip", "users_job"."latitude", "users_job"."longitude" FROM "users_job"; args=(); alias=default Jobs List: [{'id': 1, 'title': 'test job', 'description': 'this is a test', 'city': '*redacted*', 'state': '*redacted*', 'zip': '*redacted*', 'latitude': *redacted*, 'longitude': *redacted*}, {'id': 2, 'title': 'testjob2', 'description': 'This is a test', 'city': '*redacted*', 'state': '*redacted*', 'zip': '*redacted*', 'latitude': *redacted*, 'longitude': *redacted*}, {'id': 3, 'title': 'test job json', 'description': 'json test', 'city': '*redacted*', 'state': '*redacted*', 'zip': '*redacted*', 'latitude': *redacted*, 'longitude': *redacted*}, {'id': 4, 'title': 'jsontest2', 'description': 'asdofmasodfm', 'city': '*redacted*', 'state': '*redacted*', 'zip': '*redacted*', 'latitude': *redacted*, 'longitude': *redacted*}] (0.002) SELECT "django_session"."session_key", "django_session"."session_data", "django_session"."expire_date" FROM "django_session" WHERE ("django_session"."expire_date" > '2025-03-11T01:18:30.939183+00:00'::timestamptz AND "django_session"."session_key" = '*redacted*') LIMIT 21; args=(datetime.datetime(2025, 3, 11, 1, 18, 30, 939183, tzinfo=datetime.timezone.utc), '*redacted*'); alias=default (0.002) SELECT "users_user"."id", "users_user"."password", "users_user"."last_login", "users_user"."is_superuser", "users_user"."username", "users_user"."is_staff", "users_user"."is_active", "users_user"."date_joined", "users_user"."email", "users_user"."phone_number", "users_user"."address", "users_user"."city", "users_user"."state", "users_user"."zip", "users_user"."latitude", … -
Can I integrate PyTorch with Django Web framework?
Hello so I'm looking to create some games on a website using Django. I would like to have some machine learning with the games so that the players can play against a machine learning model. Is this possible with the combination of Django and PyTorch? I heard about something called ONNX that helps serves model into the frontend and I just wanted to double check that works with Django and not exclusively with NodeJS. If it doesn't work then I'd appreciate any alternative solutions. Thanks for any insight -
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 …