Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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! -
I am confused....whether Mern is better or django....and which is more in use in companies? [closed]
please tell me which one is better MERN or Django and what is more prefferd in companies these days? -
Raspberry Pi based POS: what do you think?
I have finished a simple but hopefully complete and useful Order Management and POS System built on a RaspBerry Pi based on Django and a Apache web server. I know it is perhaps too ambitious to call it "POS", given its simplicity. Anyhow, please feel free to take a look and provide your feedbacks: https://github.com/simOrderS/simOrder -
Account creation and authentication using Django
I'm hitting a wall with this code. I am able to create a user and store the data. I can see the user in django admin panel. When I try logging into that user, I get a failure message. Ive tried changing the password in the django-admin panel. That did not work either. Here is my code. login.html {% extends "users/base.html" %} {% block title %} Login Page {% endblock title %} {% block content %} <div class="container"> <div class="row justify-content-center align-items-center" style="min-height: 100vh;"> <div class="col-lg-5"> <div class="card shadow-lg border-0 rounded-lg"> <div class="card-body"> <h3 class="font-weight-light my-1 text-center">Sign In</h3> {% if form.errors %} <div class="alert alert-danger alert-dismissible" role="alert"> <div id="form_errors"> {% for key, value in form.errors.items %} <strong>{{ value }}</strong> {% endfor %} </div> <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> {% endif %} <form method="POST"> {% csrf_token %} <div class="form-row"> <div class="col-md-10 offset-md-1"> <div class="form-group"> <label class="small mb-1">Username</label> {{ form.username }} </div> </div> </div> <div class="form-row"> <div class="col-md-10 offset-md-1"> <div class="form-group"> <label class="small mb-1">Password</label> {{ form.password }} </div> </div> </div> <div class="form-row"> <div class="col-md-10 offset-md-1"> <div class="form-group"> {{ form.remember_me }} <label> Remember me</label> </div> </div> </div> <div class="form-row"> <div class="col-md-10 offset-md-1"> <div class="form-group mt-0 mb-1"> <button name="login" class="col-md-12 … -
How to Enable Web Push Notification Permissions on iOS for a Django Web App?
I am building a Django web app for status checking and need real-time background updates using the Web Push API. The web app will be accessed on both Android and iOS devices. To enable push notifications, I am using the Notification API to request user permission. The implementation works on Windows, Linux, Android, and Mac, but it does not work on iOS. However, I do not want to convert my web app into a Progressive Web App (PWA). I need guidance on how to request notification permissions on iOS and ensure web push notifications function correctly. Can someone help me find a solution to complete my project? Current Implementation I am using the following JavaScript code to request notification permissions from users: document.getElementById('grant-permission').addEventListener('click', ()=> { Notification.requestPermission().then(permission => { console.log("permission:", permission); if (permission === "granted") { console.log("Notifications allowed!"); } else { console.log("Notifications denied!"); } }); }); Issue This code works as expected on Windows, Linux, Android, and Mac. However, on iOS (Safari), it does not work. The permission prompt does not appear, and notifications are not allowed. What I Have Tried Tested on different browsers (Safari, Chrome) on iOS. Confirmed that Web Push API only works for installed PWAs on iOS. … -
I've been working on buildings a password reset system on my django site
I intend on also using a similar system for account creation confirmation but i am unable to test the system at the moment as i am having issues with my mailgun account def password_reset_request(request): if request.method == 'POST': email = request.POST.get('email') try: user = get_user_model().objects.get(email=email) # Generate reset token and expiry profile, created = UserProfile.objects.get_or_create(user=user) profile.generate_reset_token() # Prepare the email context with the reset token context = { 'user': user, 'reset_token': profile.reset_token, # Send the reset token in the email } # Render email templates email_html = render_to_string('password_reset_email.html', context) email_plain = strip_tags(email_html) # Mailgun API setup mailgun_url = f"https://api.mailgun.net/v4/{MAILGUN_DOMAIN_NAME}/messages" mailgun_auth = ("api", MAILGUN_API_KEY) mailgun_data = { "from":DEFAULT_FROM_EMAIL, "to": user.email, "subject": "Password Reset Request", "text": email_plain, "html": email_html } # Send email via Mailgun API try: response = requests.post(mailgun_url, auth=mailgun_auth, data=mailgun_data, verify=False) if response.status_code == 200: messages.success(request, "A password reset token has been sent to your email.") else: messages.warning(request, "Password reset requested, but there was an issue sending the email.") except requests.exceptions.RequestException as e: messages.warning(request, f"Password reset requested, but we couldn't send the email: {str(e)}") return redirect('password_reset_verify') except get_user_model().DoesNotExist: messages.error(request, "Email address not found.") return render(request, 'password_reset_request.html') def password_reset_verify(request): if request.method == 'POST': token = request.POST.get('token') # Assuming the user inputs … -
Error: { "detail": "Authentication credentials were not provided." }
Hello community enter image description here I have a problem: When i want to get into information in postman, This sends me the next error: "detail": "Authentication credentials were not provided." Attach: The code in Django Settings.py in (A) that shows the REST_FRAMEWORK REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'authentication.customJWTAuthentication.CustomJWTAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), } Views.py in (B1 and B2) that indicates the code POST from django.shortcuts import get_object_or_404 from rest_framework.response import Response from rest_framework.decorators import api_view, permission_classes from rest_framework import status from roles.models import Role from roles.serializers import RoleSerializer from users.models import User, UserHasRoles from users.serializers import UserSerializer import bcrypt from rest_framework_simplejwt.tokens import RefreshToken from rest_framework.permissions import AllowAny from django.conf import settings` Create your views here. GET -> OBTENER POST -> CREAR PUT -> ACTUALIZAR DELETE -> BORRAR 200 RESPUESTAS EXITOSAS 400 O 500 ERRORES` @api_view(['POST']) @permission_classes([AllowAny]) def register(request): serializer = UserSerializer(data=request.data) if serializer.is_valid(): user = serializer.save() client_role = get_object_or_404(Role, id='CLIENT') UserHasRoles.objects.create(id_user=user, id_rol=client_role) roles = Role.objects.filter(userhasroles__id_user=user) roles_serializer = RoleSerializer(roles, many=True) response_data = { **serializer.data, 'roles': roles_serializer.data } return Response(response_data, status=status.HTTP_201_CREATED) error_messages = [] for field, errors in serializer.errors.items(): for error in errors: error_messages.append(f"{field}: {error}") error_response = { "message": error_messages, "statusCode": status.HTTP_400_BAD_REQUEST } return Response(error_response, status=status.HTTP_400_BAD_REQUEST) def getCustomTokenForUser(user): refresh_token = … -
Django ignores urlpatterns
I have created a very basic urlpattern but it is ignored. def hallo(request): return JsonResponse("Hallo", safe=False) urlpatterns = [ # path('admin/', admin.site.urls), # path('admin/', JsonResponse("Hallo", safe=False) ), path("", hallo), path("hallo/", hallo) ] It will always be shown the "standard" page instead of "hallo", and even the admin page. And the page hallo cannot be found. I stopped the server and run it with different ports but there is always the same behaviour. -
I keep getting this issue Invalid block tag on line 5: 'static', expected 'endblock'. Did you forget to register or load this tag?
<!-- about.html --> 1 {% extends 'book/base.html' %} 2 3 {% block title %} About {% endblock %} 4 {% block extra_head %} 5 <link rel="stylesheet" href="{% static 'css/style.css' %}"> 6 {% endblock %} 7 {% block header %} 8 <h1> About Me </h1> 9 {% endblock %} 10 {% block main %} 11 <article> 12 <section> <p>My name is Uyiosasere Idemudia Oduware</p> 13 </section> 14 </article> 15 {% endblock %} base.html {% load static %} <!DOCTYPE html> <html> <head> <title>{% block title %} Uyi's Page {% endblock %}</title> {% block extra_head %} {% endblock %} </head> <body> <header> {% block header %} {% endblock %} </header> <main> {% block main %} {% endblock %} </main> <footer> {% block footer %} {% endblock %} </footer> </body> </html> my css file is inside LearnSphere/book/static/css/style.css the base.html and about.html file is inside Learnsphere/book/templates/book/base.html about.html -
django mongo db conection - All auth - Social account extra field error
raise ValueError( ValueError: Cannot alter field socialaccount.SocialAccount.extra_data into socialaccount.SocialAccount.extra_data - they do not properly define db_type (are you using a badly-written custom field?) class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length=100) address = models.CharField(max_length=255) profile_picture = models.ImageField(upload_to='account/profilepicture/', blank=True, null=True) mobile_number = models.CharField(max_length=15, blank=True, null=True) def __str__(self): return f"{self.user.username}'s Profile" -
Can't run Pycharm Debugger using WSL2
I have a project that has in PostgreSQL, Celery, Redis, RabbitMQ via docker containers. I'm facing an issue with PyCharm's debugger when running a DRF project in WSL2(Ubuntu). The project runs success in normal mode, but when I start the debugger, it hangs and eventually fails with "Handshake failed" errors in the logs. The full command executed is: /home/myuser/myproject/venv/bin/python3.11 /home/myuser/.pycharm_helpers/pydev/pydevd.py --multiprocess --qt-support=auto --port 29781 --file /home/myuser/myproject/manage.py runserver 8000 Here’s a snippet of the PyCharm logs: 025-03-06 12:48:04,336 [6128385] WARN - #c.j.p.PythonHelpersLocator - Helpers pro root does not exist C:\Users\user\AppData\Local\Programs\PyCharm Professional\plugins\python-ce\helpers-pro 2025-03-06 12:48:04,337 [6128386] WARN - #c.j.p.PythonHelpersLocator - Helpers pro root does not exist C:\Users\user\AppData\Local\Programs\PyCharm Professional\plugins\python-ce\helpers-pro 2025-03-06 12:48:04,337 [6128386] WARN - #c.j.p.PythonHelpersLocator - Helpers pro root does not exist C:\Users\user\AppData\Local\Programs\PyCharm Professional\plugins\python-ce\helpers-pro 2025-03-06 12:48:04,338 [6128387] WARN - #c.j.p.PythonHelpersLocator - Helpers pro root does not exist C:\Users\user\AppData\Local\Programs\PyCharm Professional\plugins\python-ce\helpers-pro 2025-03-06 12:48:04,454 [6128503] INFO - #c.i.e.wsl - WSL mount root for Ubuntu is /mnt/ (done in 114 ms) 2025-03-06 12:48:04,493 [6128542] WARN - #c.i.u.Alarm - Do not create alarm without coroutineScope: com.intellij.ui.GotItTooltip.(GotItTooltip.kt:94) 2025-03-06 12:48:04,508 [6128557] INFO - #c.i.u.WinFocusStealer - Foreground lock timeout set to 0 2025-03-06 12:48:06,295 [6130344] WARN - #c.j.p.d.p.t.ClientModeDebuggerTransport - [92734501] Handshake failed 2025-03-06 12:48:11,303 [6135352] WARN - #c.j.p.d.p.t.ClientModeDebuggerTransport - [1988656345] Handshake failed … -
Why is Django not using the specified cache backend?
As a simple test, I'm attempting to set the cache backend used by Django to something other than the default django.core.cache.backends.locmem.LocMemCache. I'm using a custom backend defined in the django-bmemcached package, which uses the python-binary-memcached module to access a Memcached instance with authentication. I've set the backend in the settings.py file, with the relevant snippet below: CACHES = { 'default': { 'BACKEND': 'django_bmemcached.memcached.BMemcached', 'LOCATION': <ip>:<port>, 'OPTIONS': { 'username': <username>, 'password': <password>, } }, } The settings.py file is being used by the application, but the default cache being used is not the specified cache backend: >>> from django.conf import settings >>> print(settings.CACHES) {'default': {'BACKEND': 'django_bmemcached.memcached.BMemcached', 'LOCATION': <ip>:<port>, 'OPTIONS': {'username': <username>, 'password': <password>}}} >>> from django.core.cache import caches >>> print(caches['default']) <django.core.cache.backends.locmem.LocMemCache object at 0x73bf66531720> This isn't caused by a third party package overriding the cache backend, and the Memcached instance can be accessed and operations performed successfully if a client for the backend is instantiated: bmemcached.Client(<ip>:<port>, <username>, <password>). Using a different binding, such as pymemcache, and setting the backend to a Django supported django.core.cache.backends.memcached.PyMemcacheCache still results in the above issues described where the default cache being used is not the specified cache backend. If at all possible, I'd like to be … -
How to Conditionally Render Mobile and Desktop Ads in Django to Prevent JavaScript Overlap?
I'm working on a Django project where I need to display different ads for mobile and desktop users. Currently, both mobile and desktop ad JavaScript is being loaded, which causes conflicts as the mobile ad scripts interfere with the desktop ads. Here's a simplified version of my template code: <div class="ads-mobile"> {% ad_simple_tag "mobile_ads" %} </div> <div class="ads-desktop"> {% ad_simple_tag "desktop_ads" %} </div> I'm using Cloudflare, which caches the pages, so I can't rely on server-side logic (like middleware) to determine which ads to display, as the result would be cached. I attempted to use JavaScript and/or css to detect the device type and hide/show or remove the ad blocks accordingly, but both ad scripts are still being loaded, causing issues. How can I ensure that only the relevant ad scripts are loaded based on the user's device type, considering that the page is cached by Cloudflare? Is there a client-side approach or best practice for handling this kind of situation in Django? -
How to apply Apache BasicAuth with IP-based access control for django project
I have a Django application and I am using Apache to manage access control. I want to restrict access to django project with this logic -> Allow access only from specific IP addresses. If the request comes from an IP address outside the allowed list, users should be prompted to authenticate using username and password defined in .htpasswd Apache .htpasswd username:encryptedpassword Apache virtual Host <VirtualHost *:80> LoadModule wsgi_module "/var/www/example.com/venv/lib/python3.10/site-packages/mod_wsgi/server/mod_wsgi-py310.cpython-310-x86_64-linux-gnu.so" DocumentRoot /var/www/example.com ServerName example.com WSGIDaemonProcess myapp python-home=/var/www/example.com/venv python-path=/var/www/example.com:/var/www/example.com/venv/lib/python3.10/site-packages WSGIScriptAlias / /var/www/example.com/example/wsgi.py process-group=myapp <Directory "/var/www/example.com/"> AllowOverride All Require all granted <Files wsgi.py> Require all granted </Files> </Directory> Alias /static/ /var/www/example.com/static/ <Directory /var/www/example.com/static/> Require all granted </Directory> <Directory /var/www/example.com/> AllowOverride All Require all granted </Directory> <Location /> AuthType Basic AuthName "Restricted Access" AuthUserFile /var/www/example.com/.htpasswd Require valid-user <RequireAny> Require ip x.x.x.x Require ip x.x.x.x Require valid-user </RequireAny> </Location> </VirtualHost> Desired behaviour Users accessing any URL in the application from allowed IP addresses should have unrestricted access. Users from non-allowed IP addresses should be prompted for authentication via apache(.htpasswd) Problem is If I am inputing username and password prompted by apache, django gives { "detail": "Invalid username/password." } I dont want to remove headers at apache level because some of my url requires authentication implemented … -
Django images not loading after setting `DEBUG = False` on PythonAnywhere
I have deployed my Django project on PythonAnywhere, and everything was working fine when DEBUG = True. However, after setting DEBUG = False, none of my images (media files) are loading. What I Tried: I have set up MEDIA_URL and MEDIA_ROOT correctly in settings.py: MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') I also ran python manage.py collectstatic --noinput and my static files are loading correctly. The images are uploaded and exist in the /home/myusername/django_ecom_web/ecomprj/media/ directory. I checked the file paths in the browser and they return a 404 Not Found error. How I Fixed It: After some research, I found that Django does not serve media files in production when DEBUG = False. To fix this in PythonAnywhere, I had to: Go to Dashboard → Web → Static Files section. Add the following mapping: /media/ → /home/myusername/django_ecom_web/ecomprj/media/ Reload my web app. After doing this, my images started loading correctly. My Question: Why does Django not serve media files in production when DEBUG = False? Is setting up a manual media mapping the only way to serve media files on PythonAnywhere, or is there a better approach? -
Django returns old form data in HTMX response
I changed UpdateView do that it can handle create requests as well if pk=0: class ObjectView(UpdateView): hx_url = "" def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) self.hx_url = f"{self.model._meta.app_label}:{self.model._meta.model_name}" context["hx_url"] = reverse( self.hx_url, args=[self.object.id if self.object else 0] ) return context def get_object(self, queryset=None): if self.kwargs.get(self.pk_url_kwarg) == 0: return None return super().get_object(queryset) def form_invalid(self, form): messages.add_message( self.request, messages.ERROR, "Invalid input.", ) return self.render_to_response(self.get_context_data(form=form)) def form_valid(self, form): messages.add_message( self.request, messages.SUCCESS, "Data saved.", ) if self.request.htmx: return self.render_to_response(self.get_context_data(form=form)) return redirect(self.object.get_absolute_url()) In my View I am checking if price field was updated and if yes update the price_date field as well: class PartView(ObjectView): model = Part form_class = PartForm def form_valid(self, form): if self.object: old = Part.objects.get(id=self.object.id) old_price = old.price self.object = form.save(commit=False) if self.object.price != old_price: self.object.price_date = date.today() self.object.save() form.save_m2m() else: self.object = form.save() return super().form_valid(form) I make an htmx call to it from my template: <div id="modalContent" hx-target="this"> <form method="post" hx-post="{{ hx_url }}" hx-on:htmx:validation:failed="this.reportValidity()" hx-trigger="click from:#btn-save"> {% csrf_token %} <div> {% include "form_field.html" with form_field=form.price %} {% include "form_field.html" with form_field=form.price_date %} </div> </div> </form> {% include "btn_save.html" %} {% include "messages.html" %} </div> The problem is even though it successfully updates the price_date in the DB it still … -
Django ModuleNotFoundError: No module named 'ecomprj' on PythonAnywhere Deployment
Body: I am deploying my Django project on PythonAnywhere, but I keep getting this error in my logs: ModuleNotFoundError: No module named 'ecomprj' Project Structure: My Django project is located at: /home/Sagarmoy007/django_ecom_web/ecomprj/ Running ls -l /home/Sagarmoy007/django_ecom_web/ecomprj gives: __pycache__ core customercare db.sqlite3 deladmin ecomprj errorriders locustfile.py manage.py media migrate.bat notification_app others requirements.txt returnadmin staffdata static staticfiles templates useradmin userauths vendorpannel videoshareing whoosh_index Inside /home/Sagarmoy007/django_ecom_web/ecomprj/ecomprj/, I have: __init__.py settings.py urls.py wsgi.py asgi.py My WSGI File (/var/www/sagarmoy007_pythonanywhere_com_wsgi.py): import os import sys # Add the correct project paths sys.path.append('/home/Sagarmoy007/django_ecom_web/ecomprj') # The main directory sys.path.append('/home/Sagarmoy007/django_ecom_web/ecomprj/ecomprj') # The Django project folder # Set Django settings module os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ecomprj.settings') from django.core.wsgi import get_wsgi_application application = get_wsgi_application() What I Have Tried: Verified that manage.py exists inside /home/Sagarmoy007/django_ecom_web/ecomprj. Checked that the Django settings module is correctly set (ecomprj.settings). Restarted the web app from the PythonAnywhere dashboard. Ran python manage.py shell inside /home/Sagarmoy007/django_ecom_web/ecomprj, but it fails with the same ModuleNotFoundError. Questions: Is my WSGI configuration correct? Do I need to modify my PythonAnywhere environment? How can I properly set up Django on PythonAnywhere to recognize my project? -
How to replace super().save() in MyCustomSignupForm when recaptcha is not confirmed
How to replace super().save() in MyCustomSignupForm when recaptcha is not confirmed class MyCustomSignupForm(SignupForm): def save(self, request): token = request.POST['g-recaptcha-response'] action = "signup" r_result = recaptcha(request, token, action) if r_result: user = super(MyCustomSignupForm, self).save(request) else: messages.warning(request, '...robot...') user = ??? return user -
Cannot resolve keyword 'mem_ev' into field in Django
I have a small Django project that consists of 2 models (Event, mem_ev) plus auth User and Profile such that Users --< mem_ev >-- Events (ie a classic many to many relationship between Users & Events). I want to be able to list all events for a member and all members for an event both of which entail a join between the main dataset and mem_ev. I have the list of events attended by a member working fine (list_member_events) but cannot get a list of members attending an event (list_event_members) working. My models.py 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) amt_paid = models.DecimalField(max_digits = … -
Cannot determine region size; use 4-item box
I'm trying to make a QR code and I'm using pillow=11.1.0. Here's the code to generate and save the QR code: def save(self, *args, **kwargs): ## TODO:Generate QR Code # qr_code_url = f"{os.environ['HOST_URL']}/inventory/{self.part_type_id}" qrcode_img = qrcode.make(self.part_number) canvas = Image.new('RGB', (290, 290), 'white') draw = ImageDraw.Draw(canvas) canvas.paste(im=qrcode_img, box=(0,0)) buffer = BytesIO() canvas.save(buffer, 'PNG') self.qr_code_data.save(f'{self.part_name}.png', File(buffer), save=False) canvas.close() super().save(*args, **kwargs) However when I do save it I'm faced with the following error: cannot determine region size; use 4-item box The line in question is: canvas.paste(im=qrcode_img, box=(0,0)) -
Hey There ! , I am new to Django and i am very interested on it and i was just curious to know How do i implement Push Notification using Fire base
, I am new to Django and i am very interested on it and i was just curious to know How do i implement Push Notification using Fire base Cloud Messaging i am having trouble to implement it on my Django Project . Well i want to implement these features: TO send Notification from student to Teacher And Vice Versa . QN. = > How do i do it ? well i need help or some best YouTube Channels to help guide me as of my recent Searches in YT {YouTube} i have not Found the best Video that matches my Querry . -
Django generates complex SQL instead of simple OR condition
I'm encountering an issue where Django's ORM is generating an unexpectedly complex SQL query from a simple function. The function checks if there are any recent or upcoming matches by applying filters for team participation and public season checks on alive matches. Instead of a straightforward OR condition, the generated SQL includes a nested subquery: SELECT COUNT(*) FROM "scheduler_season" WHERE "scheduler_season"."id" IN ( SELECT U0."id" FROM "scheduler_season" U0 WHERE (U0."enddate" >= ?::date AND U0."schedule_is_public" = ?) ) OR "scheduler_season"."id" IN (?, ?, ..., ?) Expected query: SELECT COUNT(*) FROM "scheduler_season" WHERE ("enddate" >= ? AND "schedule_is_public" = ?) OR "id" IN (?, ?, ..., ?) Why does Django create this complex subquery, and how can I modify the Django query to generate the simpler expected SQL? -
Flatpicker on django template not working on mobile device
i have interesting problem. Have this template: {# date picker #} <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css"/> <script src="https://cdn.jsdelivr.net/npm/flatpickr"></script> <script src="https://cdn.jsdelivr.net/npm/flatpickr/dist/l10n/bg.js"></script> <link rel="stylesheet" type="text/css" href="{% static "custom/date_picker.css" %}"/> <script> document.addEventListener("DOMContentLoaded", function () { // Ensure Flatpickr's localization is loaded before modifying if (flatpickr.l10ns && flatpickr.l10ns.bg) { flatpickr.l10ns.bg.rangeSeparator = " до "; } else { console.warn("Bulgarian locale not found, continuing without modifying rangeSeparator."); } const dateTimePickers = ["#fromInput", "#toInput"]; dateTimePickers.forEach(selector => { flatpickr(selector, { enableTime: true, time_24hr: true, locale: "bg", dateFormat: "H:i ч. на d M Y г.", enableSeconds: false, // Ensure seconds are not required disableMobile: true // Forces Flatpickr UI on mobile }); }); </script> then i have this two inputs <div style="margin-top: 15px" id="fromDiv"> <label for="fromTime">От</label> <input type="text" id="fromInput" name="fromTime" placeholder="Избери дата и час" style="margin: auto"> </div> <div style="margin-top: 15px" id="toDiv"> <label for="dateTimeInput">До</label> <input type="text" id="toInput" name="toTime" placeholder="Избери дата и час" style="margin: auto"> </div> everything works perfectly on desktop browser, but when is used on mobile device, inputs change, want seconds, but in choice pop up its not possible to be selected seconds. Examples on desktop browser: how looks input and choice pop-up on desktop browser Examples on mobile: pop-up choice on mobile browser and date-time input on mobile browser.. how … -
Forbidden Error (403) in Django Test Cases on GitHub Actions
I have a Django REST framework API application hosted on AWS ECS, using RDS. I am working on implementing CI/CD using GitHub Actions, where we need to include a test suite. The corresponding CI/CD implementation is as follows: unit-tests: runs-on: ubuntu-latest environment: ${{ inputs.build_env }} env: ENVIRON: ${{ secrets.ENVIRON }} PG_DB_NAME: ${{ secrets.POSTGRES_DB }} PG_DB_USER: ${{ secrets.POSTGRES_USER }} PG_DB_PASSWORD: ${{ secrets.POSTGRES_PASSWORD }} PG_DB_HOST: ${{ secrets.POSTGRES_HOST }} PG_DB_PORT: ${{ secrets.POSTGRES_PORT }} SECRET_KEY: ${{ secrets.SECRET_KEY }} steps: - name: Checkout repo uses: actions/checkout@v3 - name: Setup Python uses: actions/setup-python@v2 with: python-version: ${{ env.PYTHON_VERSION }} - name: Install dependencies run: | python3 -m pip install --upgrade -r requirements.txt - name: Configure AWS credentials uses: aws-actions/configure-aws-credentials@v1 with: aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }} aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }} aws-region: ${{ secrets.AWS_REGION }} - name: Run tests run: | cd ./dbasebe python3 manage.py test cd .. And the unit test case is class TestFirstEndpoint(SimpleTestCase): def setUp(self): self.client = APIClient(enforce_csrf_checks=False) def test_endpoint_no_valid_user(self): url = reverse('myapp:firstendpoint') response = self.client.post(url, {'userid':'testuser'}, format='json') `self.assertEqual(response.status_code, 404) the corresponding endpoint view is @api_view(["POST"]) @authentication_classes( ([utils_security.CsrfExemptSessionAuthentication, BasicAuthentication]) def first_endpoint_view(request): userid = request.data.get("userid", 'USER1') user = Mymodel.objects.filter(userid=userid) if user.exists(): # do my job return Response({"message": "Work is done"}, status=status.HTTP_200_OK) else: return Response({"message": "User not found"}, status=status.HTTP_404_NOT_FOUND) … -
'<' not supported between instances of 'NoneType' and 'int' django views.py
templates/html {% if guess == rand_num %} <h1>{{message1}}</h1> {% elif guess > rand_num %} <h1>{{message3_a}}</h1> <h1>{{message3_b}}</h1> {% elif guess < rand_num %} <h1>{{message2_a}}</h1> <h1>{{message2_b}}</h1> {% endif %} views.py def easy(request, ): rand_num = random.choice(lst) print(rand_num) attempts = 11 for _ in range(0, 10): # print(f"You have {attempts} remaining to guess the number.") # guess = int(input("Make a guess: ")) guess = request.GET.get('guessed_number') if guess == rand_num: return render(request, 'easy.html', {'attempts': attempts, "message1": f"You got it! The anshwer was {rand_num}"}) break elif guess < rand_num: attempts -= 1 return render(request, 'easy.html', {'attempts': attempts, "message2_a": "Too Low", "message2_b": "Guess again"}) elif guess > rand_num: attempts -= 1 return render(request, 'easy.html', {'attempts': attempts, "message3_a": "Too High", "message2_b": "Guess again"}) attempts -= 1 return render(request, 'easy.html', {'attempts': attempts, 'guess': guess, 'rand_num': rand_num}) return render(request, 'easy.html') i Am triying to Run this Django code. but it is not running..