Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to localize Django duplicate key value violates unique constraint error message?
Problem description I would want to provide clear localized error messages to client using Django. I have the following unique field: class Foo(models.Model) email = models.EmailField(max_length=255, unique=True, default=None, blank=True, null=True, verbose_name=gettext_lazy('email address'), error_messages={'unique': gettext_lazy("Email address is already registered to another user.")}) When I try to save duplicate email address, I still get an error psycopg2.errors.UniqueViolation: duplicate key value violates unique constraint "foo_email_key" Question Why is my error message not localized? How can be the desired behaviour obtained? -
AsyncIO: Program still runs in a synchronous manner despite using AsyncIO in Django
I have created an API named APIDummyWait5. Now I want to test the following - I want the API to return the result in few milliseconds. - While the function that is being called inside the API should run in an asynchronous manner. The API - APIDummyWait5 randomly generates a number in between 1 - 25 and then sends that as an argument to a function named get_country_details along with another parameter named country that I will be fetching from API url params. Here is the API class APIDummyWait5(APIView): def get(self, request): print("Coming Here") worker = os.getpid() thread = threading.get_ident() country = request.GET.get('country') print(f"API wait 5 - for worker - {worker} at Thread {thread} starting at: {datetime.datetime.now()}") wait_time = rd.randint(1, 25) response = {'wait_time': wait_time, 'country': country} asyncio.run(main(wait_time=wait_time, country=country)) print(f"API Wait 5 - for worker - {worker} at Thread {thread} ending at: {datetime.datetime.now()}") return Response({ "data": response }) async def main(wait_time, country): result = await get_country_details(wait_time, country) I am creating a helper function named main to call the get_country_details function. The function - get_country_details actually sleeps for the wait time and then calls a third party API to fetch the name and capital of a country and store it in … -
Django different models' m2m relations fields comparsion related to same m2m model
I'm following this question to filter on M2M field: Django filter queryset __in for *every* item in list I'm using .annotation approach. My models: class Options(models.Model): name = models.CharField(max_length=50) class Product(models.Model): options = models.ManyToMany(Category) class Item(models.Model): options = models.ManyToMany(Category) I'm trying to filter Product instance to contain all categories as Item instance has: items = Item.objects.all() for item in items: item_options = [option.name for option in item.options.all()] queryset=models.Product.objects.filter( status=Status.COMPLETED, )\ .filter(options__name__in=item_options)\ .annotate(num_options=Count("options"))\ .filter(num_options=len(item_options)) It works in most cases except when Item doesn't contains any options. In this case I woul d like to match Product instance which also haven't any options but it fails returning no objects. -
How should I store google login info sent from frontend in backend Django? [closed]
In my Django application, I want to implement Google and Apple login. For Google login, the frontend (using Firebase Authentication) sends me the following details: Google ID, display name, email, and photo URL. How should I store this data in the backend so that users can log in again in the future? Should I use the django-allauth package (which requires setting up social providers with client ID and secret), or should I manually store the data in the default users table? Could you suggest the best approach? Thanks! -
How can we activate the dropdown menu items on the Wagtail Bakerydemo website?
I encountered an issue with the bakerydemo an Wagtail demo site. When clicking on "bread" menu item or its dropdown label, the submenu items did not display, despite marking the "Show in menus" checkbox for the child pages. Your prompt attention to this matter would be greatly appreciated.d up for child pages. -
Django OAuth2 Authentication Failing in Unit Tests - 401 'invalid_client' Error
I've been stuck on this issue for 3 days now, and I'm hoping someone can help me out. I'm trying to implement OAuth2 authentication for my Django backend with a REST interface. However, my unit tests for authentication are failing, and I'm getting a 401 error with the message 'invalid_client' instead of the expected 200 status code. My user model is configured to use email as the user ID. Here's the relevant part of my user model: class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) date_joined = models.DateTimeField(auto_now_add=True) roles = models.ManyToManyField(UserRole, related_name="roles") objects = CustomUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] def __str__(self): return self.email class CustomUserManager(BaseUserManager): def create_user(self, email, password=None, **extra_fields): if not email: raise ValueError('The Email field must be set') email = self.normalize_email(email) user = self.model( email=email, **extra_fields) if password: user.set_password(password) else: user.set_unusable_password() user.save(using=self._db) return user def create_superuser(self, email, password=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self.create_user(email, password, **extra_fields)` My Django settings from .settings import * # Use an in-memory SQLite database for testing DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', } … -
Adding CSS styles to dynamically created HTML elements in JavaScript
I'm working on a Django project and I have an index.html file where I've connected a JavaScript file using the following script tag: <script src="{% static 'assets/js/bubble.js' %}"></script> In my JavaScript file, I have the following code: console.log("Bubble"); // Get the speech bubble container const speechBubbleContainer = document.querySelector('.speech-bubble-container'); // Function to create a speech bubble function createSpeechBubble(message) { const speechBubble = document.createElement('div'); speechBubble.style = ` background-color: #fff; border-radius: 10px; padding: 10px; font-size: 16px; font-weight: bold; color: #333; box-shadow: 0 0 10px rgba(0, 0, 0, 0.2); opacity: 1; transition: opacity 2s; `; speechBubble.textContent = message; speechBubbleContainer.appendChild(speechBubble); // Remove the speech bubble after 2 seconds setTimeout(() => { speechBubble.style.opacity = 0; setTimeout(() => { speechBubble.remove(); }, 2000); }, 2000); } // Create a speech bubble every 30 seconds setInterval(() => { createSpeechBubble('Hi'); }, 3000); And here's my HTML code: <div class="floating-button" style="..."> <!-- button styles --> <img src="..." alt="Button Image" style="..."> <!-- image styles --> <div class="speech-bubble-container" style="..."></div> </div> I want to add CSS styles to the dynamically created speech-bubble elements, but I'm not sure how to do it. I've tried adding the styles directly to the HTML elements, but it's not working as expected. Can someone help me figure out how … -
django import_export lib buttons not showing in admin site
from django.contrib import admin from import_export.admin import ImportExportModelAdmin from .models import members @admin.register(members) class MembersAdmin(ImportExportModelAdmin): pass this is my code in admin.py .actually i am trying to use import-export lib for my project while running in server it show the models i have created but its not showing the button where we can import export.(btw i am a noob in this field) i need answer for my queries related to the python django library -
Empty Dynamic Nested Serializer for Generic Django Model
I have this generic Model called Thumbs with two fields which can describe another model. The two fields are: 'entity_type', a CharField values can be a family or product, both corresponding to Family and Product models, respectively Then there's 'entity_id', a IntegerField this is the PrimaryKey for the previous entity in another table. So, I want to create a serializer for this Thumbs model which implements a nested serializer for the specified 'entity_type'. For example, if the 'entity_type' is family, the serializer used a FamilySerializer so the serialized Thumbs object has the entity's data. This is how I implemented that behavior, but it is returning an empty family object. from rest_framework import serializers from app.models import Thumbs, Family from app.serializers.user_role_product_tool import FamilySerializer, ProductSerializer class ThumbSerializer(serializers.ModelSerializer): entity = serializers.SerializerMethodField() class Meta: model = Thumbs fields = '__all__' def get_entity(self, obj): if obj.entity_type == "family": return FamilySerializer(source=obj.entity_id, read_only=True).data else: return None Example output showing the Family serializer is being used when expected, but it's empty although the Family table has an entry with PrimaryKey of 107: { "id": 182, "entity": { "family_name": "", "status": "", "created_by": "", "last_updated_by": "" }, "entity_id": "107", "entity_type": "family", "thumbs_decision": "PENDING", "entity_parent_id": "181", "created_date": "2024-09-03T14:21:17.403159-07:00", "last_updated_by": "", … -
Problem creating a user with Social Django
In my settings.py I have - INSTALLED_APPS = [ *** 'social_django', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'social_django.middleware.SocialAuthExceptionMiddleware', ] # Authentication backends AUTHENTICATION_BACKENDS = ( 'cloud.social_auth_backends.CustomGoogleOAuth2', 'django.contrib.auth.backends.ModelBackend', ) # Google OAuth2 credentials SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = os.getenv('SOCIAL_AUTH_GOOGLE_OAUTH2_KEY') SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = os.getenv('SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET') # Login and logout redirection LOGIN_REDIRECT_URL = '/' LOGOUT_REDIRECT_URL = '/' In my project's urls.py I have - from django.contrib import admin from django.urls import path, include from django.conf.urls.static import static from django.conf import settings urlpatterns = [ path('admin/', admin.site.urls), path('', include('cloud.urls')), path('ckeditor/', include('ckeditor_uploader.urls')), path('auth/', include('social_django.urls', namespace='social')), ] urlpatterns += [ path("ckeditor5/", include('django_ckeditor_5.urls'), name="ck_editor_5_upload_file"), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) in my social_auth_backends.py I have - from django.contrib.auth import get_user_model from social_core.backends.google import GoogleOAuth2 class CustomGoogleOAuth2(GoogleOAuth2): def user_data(self, access_token, *args, **kwargs): print(f"Fetching user data with access token: {access_token}") data = super().user_data(access_token, *args, **kwargs) print(f"User data fetched: {data}") return data def new_user(self, user, *args, **kwargs): email = user.email print(f"Creating a new user with email: {email}") if not email: raise ValueError("Email is required to create a user.") User = get_user_model() username = email.split('@')[0] print(f"Attempting to get or create user with email: {email} and username: {username}") user, created = User.objects.get_or_create( email=email, defaults={'username': username} ) if created: print(f"User created with email: {email}") user.set_unusable_password() … -
(unicode error) 'utf-8' codec can't decode byte 0xf3
I'm using django 5.0.8 and python 3.11, so in my view i use this: context = RequestContext(request, { 'title':'sómething', 'formLogin': formLogin }) As you can see i pass string with 'ó' value, when i try to run my project gives me the error '(unicode error) 'utf-8' codec can't decode byte 0xf3' this happen with any special characters for what i know using '# -- coding: utf-8 --' at first in my view solve this, but not now, what can i do? -
How to reload the current page with a different html template after a Task completes in Django?
I'm working on a Django project where I need to handle a task that runs in the background. Once the task is completed, I want to reload the current page, but I also need it to load a specific HTML template on that same URL. Currently, I'm using AJAX to poll the status of the task, and once it’s completed, I receive a JSON response from the server indicating the task's completion. My goal is to reload the current page when the task is done, so the user can see the updated content. I want that if the user visits the page later or deletes or reloads the tab the new template is what is loaded and not the old one. Here's my django view: @csrf_protect def initiate_transcription(request, session_id): file_name = request.session.get('uploaded_file_name') file_path = request.session.get('uploaded_file_path') try: transcribed_doc = TranscribedDocument.objects.get(id=session_id) except TranscribedDocument.DoesNotExist: return JsonResponse({'status': 'error', 'message': 'Document not found'}, status=404) if request.method == 'GET': if not file_name or not file_path: return redirect(reverse('transcribeSubmit')) if request.method == 'POST': if not file_name or not file_path: return redirect(reverse('transcribeSubmit')) else: try: if transcribed_doc.state == 'not_started': transcribed_doc.state = 'in_progress' transcribed_doc.save() audio_language = request.POST.get('audio_language') output_file_type = request.POST.get('output_file_type') task = transcribe_file_task.delay(file_path, audio_language, output_file_type, 'ai_transcribe_output', session_id) return JsonResponse({'status': 'success', 'task_id': … -
Best practices for enum with django models and migrations
I have a django model with a field that uses a enum for it's choices tuple like this: VERSION_CHOICES = tuple( (v.value, v.value) for v in ForwardsUpdateEventSensitivityVersion ) version = models.CharField( max_length=max(len(s[0]) for s in VERSION_CHOICES), choices=VERSION_CHOICES, ) What is the best practice for writing the accompanying migration? Using the enum directly like this: models.CharField( choices=[ tuple( (v.value, v.value) for v in ForwardsUpdateEventSensitivityVersion ) ], ) Or hardcoding the values like this: models.CharField( choices=[("V1", "V1"), ("V2", "V2")], ) -
Somebody know how to add the anchor plugin on CKEDITOR5?
I am trying to add anchors on CKEDITOR5, but the editor automaticaly removes de 'id' atributte when i exit the text source mode, i tried to find a anchor plugin for ckeditor5, but i don find nothing that works on django. <p> <a href="#bottom">go bottom</a> </p> <p> &nbsp; </p> <p> &nbsp; </p> <p id="bottom"> bottom </p> -
raise self.model.DoesNotExist( django.contrib.sites.models.Site.DoesNotExist: Site matching query does not exist
I am implementing google authentication in my website but whenever I run my code I got this error. Internal Server Error: / Traceback (most recent call last): File "C:\Users\rahul\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\rahul\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\rahul\Documents\tournament-web\Xoriva\loginpage\views.py", line 6, in home return render(request, "home.html") ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\rahul\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\shortcuts.py", line 25, in render content = loader.render_to_string(template_name, context, request, using=using) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\rahul\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\template\loader.py", line 62, in render_to_string return template.render(context, request) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\rahul\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\template\backends\django.py", line 107, in render return self.template.render(context) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\rahul\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\template\base.py", line 171, in render return self._render(context) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\rahul\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\template\base.py", line 163, in _render return self.nodelist.render(context) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\rahul\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\template\base.py", line 1008, in render return SafeString("".join([node.render_annotated(context) for node in self])) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\rahul\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\template\base.py", line 969, in render_annotated return self.render(context) ^^^^^^^^^^^^^^^^^^^^ File "C:\Users\rahul\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\template\library.py", line 237, in render output = self.func(*resolved_args, **resolved_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\rahul\AppData\Local\Programs\Python\Python312\Lib\site-packages\allauth\socialaccount\templatetags\socialaccount.py", line 21, in provider_login_url provider = adapter.get_provider(request, provider) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\rahul\AppData\Local\Programs\Python\Python312\Lib\site-packages\allauth\socialaccount\adapter.py", line 214, in get_provider app = self.get_app(request, provider=provider, client_id=client_id) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\rahul\AppData\Local\Programs\Python\Python312\Lib\site-packages\allauth\socialaccount\adapter.py", line 297, in get_app apps = self.list_apps(request, provider=provider, client_id=client_id) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\rahul\AppData\Local\Programs\Python\Python312\Lib\site-packages\allauth\socialaccount\adapter.py", line 242, in list_apps db_apps = SocialApp.objects.on_site(request) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\rahul\AppData\Local\Programs\Python\Python312\Lib\site-packages\allauth\socialaccount\models.py", line 34, in on_site site = get_current_site(request) ^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\rahul\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\contrib\sites\shortcuts.py", line … -
Issue with Django translation not reflecting in the admin interface
I'm working on enabling Swedish translations in a Django project using the standard i18n/l10n setup, but I can't get the translated strings to appear in the admin interface. I've set up the LOCALE_PATHS, created .po and compiled .mo files, and added 'sv' to LANGUAGES in settings.py, but the admin is still showing English strings. What am I missing? I've already run python manage.py compilemessages, ensured that the .mo files exist, and tried clearing the cache, but the admin interface still defaults to English. Has anyone encountered this before? Is there something I might be missing in the configuration or setup? -
Django migrations operations inside RunPython code
I'm working with data migrations in django, and at some point, I'll have to run migrations.RunPython. The point is that I wish I could execute migrations operations(AddField, AlterField) under certain conditions. For example: def forward_migration(apps, schema_editor): if some_condition: migrations.AddField(...) class Migration(migrations.Migration): dependencies = [ ('some_app', '0002_auto_...'), ] operations = [ migrations.RunPython(forward_migration) Thanks in advance. -
Sending Apple Push Notifications to Wallet Passes for different PassTypeID
i have a webapp that is able to create apple wallet passes for iOS. Process more or less looks like this: User provides his Apple Pass ID and certificate from apple developer, based on that cert i am creating wallet passes that i can send to devices, then devices register to my webServiceURL. Now i have tested this app while creating the passes from my Apple Pass ID and while using my APNs key from the same developer account and everything works great. What im looking for now is how to send push notifications to devices that have passes with different Apple Pass ID (so from user apple pass ID) with my APNs key. Apps like PassKit etc. can send those notifications while not requesting user to provide his APNs key, maybe there is something i fundamentally dont understand about this process? Im using aioapns library for python and when i try to push notify pass made with PassTypeID from different apple developer account, if i use that PassTypeID as topic with keys from my developer accound i get TopicDissalowed, and when i use my PassTypeID as topic, device is not notified. -
My css styles don't connect to my django-written website
Some styles were connected without any problems, but I managed to make only one section, as they stopped connecting and my entire site began to look like a document in word I have already searched for similar problems here, tried the solutions given; I also searched for how to connect styles, etc. Unfortunately, I did not find a solution to my problem, so I am writing here Base.html {% load static %} <!DOCTYPE html> <html lang="ru"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>{% block title %}{% endblock %}</title> {% block css %} <link rel="stylesheet" href="{% static 'css/_normalize.css' %}"> <link rel="stylesheet" href="{% static 'css/main.css' %}"> {% endblock %} </head> index.html {% extends './base.html' %} {% load static %} {% block css %} <link rel="stylesheet" href="{% static 'css/main.css' %}"> {% endblock %} {% block title %} Главная {% endblock %} {% block content %} <section class="hero"> <div class="container hero__container"> <div class="hero__content"> <div class="hero__text"> <h1 class="title hero__title"> Центр подбора лечения от&nbsp;алкоголизма, наркомании и&nbsp;других зависимостей </h1> <h4 class="title hero__subtitle"> Мы&nbsp;приходим на&nbsp;помощь в&nbsp;самых нелегких ситуациях и&nbsp;точно знаем как можем помочь и&nbsp;пациенту, и&nbsp;его близкому окружению. </h4> </div> <button class="btn btn-reset hero__btn"> <a href="#" class="link-reset hero__link">Бесплатная консультация</a> </button> </div> <div class="hero__image"> <img src="{% static 'images/hero/hero-img.png' %}" … -
Can't send files to ChatConsumer in Django Channels
I'm having an issue with sending files to a handler in ChatConsumer using Django Channels. I have two consumers, ChatConsumer and GroupChatConsumer, for handling direct messages and group messages. I want to send files to ChatConsumer or GroupChatConsumer based on whether a group exists or not. If the group doesn't exist then file should go to ChatConsumer I'm sending the files using channel_layer.group_send through views. Keep in mind I have the same handler name in ChatConsumer and GroupConsumer but despite changing those the issue persists What i have tried: Added print statements right after group_send to confirm if they execute without any error and they do! I also added logging inside ChatConsumer to see if any file or message is recived but there isn't! Ensured if the websocket connections are active and they are! So how can I verify if a message is successfully sent to ChatConsumer? Why is the consumer not receiving any messages? My code: https://github.com/Kioshi5581/djchat -
Django Debug Toolbar is not showing
After setting all the configuration i still cant see the toolbar. P.S. some of ther other not related to the problem code were removed to save space What I Did python -m pip install django-debug-toolb settings.py Also tried adding fix for set content type of js files in Django import mimetypes mimetypes.add_type("application/javascript", ".js", True) from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.messages', 'django.contrib.staticfiles', 'playground', "debug_toolbar", ] MIDDLEWARE = [ "debug_toolbar.middleware.DebugToolbarMiddleware", 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'storefront.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'storefront.wsgi.application' STATIC_URL = 'static/' DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' INTERNAL_IPS = [ "127.0.0.1", ] urls.py from django.conf import settings from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('playground/', include('playground.urls')), ] if settings.DEBUG: import debug_toolbar urlpatterns += path('__debug__/', include(debug_toolbar.urls)), after all these changes i just ran python manage.py runserver or F5 And after all these steps i still dont see the toolbar -
Django: Html select with onchange action (without using form) and pure Javascript: redirect with code 200 but page not loaded
I have a select box in my template that reacts on changes with the onchange function that sends the selected value to the Django view. The view gets the required data from the database and should display them. main.html {% block content %} <select class="form-select form-select-lg mb-3 categorySelect select" name="categorySelect" aria-label="Select category" onchange="getSelectedId(value)"> <option value="None">Select category</option> <option value="all">All</option> <option value="cat1">Category 1</option> <option value="cat2">Category 2</option> </select> {% endblock %} select.js function getSelectedId(selectedValue) { const value = selectedValue; const endpoint = "/all/select"; fetch(endpoint + "?select_id=" + value) .then() .then(response => { }) } views.py def select(request): select_id = request.GET.get("select_id", "None") print(select_id) if select_id.__contains__('None'): return render(request, "home/main.html" ) elif select_id.__contains__('all'): return redirect(reverse('all:probe_list')) elif select_id.__contains__('cat1'): selected = "Category 1" config = RequestConfig(request) resultTable = AllProbesTable(Probe.objects.filter(category = "cat1")) config.configure(resultTable) return render(request, 'all/selectResults.html', {'table':resultTable, 'selected': selected}) I get the correct select_id in the view and the I get a 200 from the redeirect but the page is not changing (similar to This question). I understand that I need to add a reload such as "location.reload()". I added this to the template I am redirecting to but this did not work. Is there any way to trigger a reload or is there another way to implement a … -
Is Enumerating Through Multiple Categories in API Tests a Good Practice? Alternatives for View Testing?
I'm currently writing tests for my Django application using pytest and pytest-django. One of my tests involves creating multiple category instances and verifying that they are correctly listed in the API response. Here’s a snippet of the test: @pytest.mark.django_db def test_auth_user_can_list_categories(auth_client, category_factory): categories = category_factory.create_batch(5) url = reverse("category-list") response = auth_client.get(url) assert response.status_code == 200 for i, category in enumerate(categories): assert response.data[i]["id"] == category.id assert response.data[i]["name"] == category.name In this test, I’m creating 5 distinct categories and then using enumerate to loop through them to verify that each category is correctly listed in the API response. I’m wondering if this approach of enumerating through the categories to match them with the API response is considered a good practice. Are there any better or more efficient ways to test this scenario? Specifically, are there alternative strategies for view testing that could offer more robust or scalable solutions? I’d appreciate any advice or best practices on how to improve this test or alternative methods to achieve the same results. -
Background-image in CSS url blocked by Opaque Response Blocking
I use a background-image like this: <style> .bg-image { background-image: url("{{ instance.background.url }}"); } </style> but the request gets blocked A resource is blocked by OpaqueResponseBlocking. Displaying the image the 'normal' way with <img src="..."> works perfectly. I tried setting a header in CORS-Configuration like: Content-Type: text/css but that did not change anything. I did specify the origin domain and allowed GET, PUT, DELETE, POST and HEAD. -
Django Session variables not visible after login
I am developing a hospital site. patients are allowed to login and book appointment. When a patient logs in, a sessions is initiated and saved. Again, I debugged, by adding a print statement after saving the sessions in the login view and its good, but when i try to book an appointment, then i print the session variables, they are empty. Could anyone please help me on this.... I would really appreciate. Note: My frontend is built with Next.js and am adding credentials='include' on my request. Also the cookies are set well in my browser with the key: sessionid and its value. const response = await fetch( "http://127.0.0.1:8000/bookings/book-appointment/", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify(appointmentData), credentials: "include" } ); @csrf_exempt def login_view(request): if request.method == 'POST': try: data = json.loads(request.body) email = data.get('email') password = data.get('password') # Fetch the user from the database user = Patient.objects.filter(email=email).first() # Check if user exists and password is correct if user and user.check_password(password): # Handle 2FA if enabled if user.enable_2fa: generate_and_send_2fa_code(user) return JsonResponse({ 'success': True, 'message': '2FA code sent', 'user_id': user.id, 'email': user.email, 'requires_2fa': True }) # Set session expiry time request.session.set_expiry(2 * 60 * 60) # 2 hours # Log …