Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django migrations: SeparateDatabaseAndState vs --fake
Let's say I have a model: class MyModel(models.Model): ... field_no_need_anymore = Charfield(...) I want to remove field_no_need_anymore, but I don't want to apply changes to the database immediately - I will drop this column manually later (next day or day after). In Django for this case I have two options: python manage.py migrate --fake or add this to the migration: operations = [ migrations.SeparateDatabaseAndState( state_operations=[ migrations.RemoveField( model_name='mymodel', name='field_no_need_anymore', ) ], database_operations=[] ) ] In both cases there will be a new record in django_migrations table, while no changes to the target table will be applied. So, when you use --fake and when SeparateDatabaseAndState? -
Django add numbers from database and displaying on screen
I have a model that takes values from each day. I would like to add the sum of those numbers and display them below the columns every time they are added to. For instance: Some days we have a lift_frame in service and some days we don't. At the end of the month I want to display the total number of days we had a lift_frame in service. Can someone help me sort this out, or point me to the documentation that explains adding and displaying sums in Django? This is my current code: model.py class Day(models.Model): day = models.DateField(auto_now=False) well_name = models.ForeignKey("Well", on_delete=models.SET_NULL, null=True) lift_frame = models.IntegerField(default=0) mpd_manifold_building = models.IntegerField(default=0) rcd_housing = models.IntegerField(default=0) pipework = models.IntegerField(default=0) mpd_supervisor = models.IntegerField(default=2) mpd_operator = models.IntegerField(default=2) def __str__(self): return self.day.strftime("%d %B") views.py class Dayboard(LoginRequiredMixin, View): def get(self, request): days = Day.objects.all().order_by('day') return render(request, 'days/dayboard.html', {'days': days}) dayboard.html {% extends 'base/base.html' %} {% block content %} <div class="container"> <div class="d-flex justify-content-end m-4"> {% if user.is_superuser %} <a href="{% url 'add-day' %}" class="btn btn-outline-info rounded">+</a> {% endif %} </div> <table class="table table-hover"> <thead> <tr> <th scope="col">Date</th> <th scope="col">Well</th> <th scope="col">MPD</th> <th scope="col">RCD</th> <th scope="col">Pipe</th> <th scope="col">LF</th> <th scope="col">Sup</th> <th scope="col">Op</th> <th scope="col"></th> </tr> </thead> <tbody> … -
Django: how to reset page URL in a post response?
Context Page displays a list of records (from a DB) where some columns are editable. One "cell" is supposed to contain a sum. Layout is something like this: +----+-------+--------+--------+--------+---------------+ | id | name | Price |Packing |Shipping| Total fees | +----+-------+--------+--------+--------+---------------+ | 32 | Name1 | 150.25 | (0.00) | (1.00) | <Update> 0.00 | <Save> | 47 | Name2 | 57.16 | (0.50) | (1.00) | <Update> 0.00 | <Save> +----+-------+--------+--------+--------+---------------+ <Cancel> <Approve> where (…) denotes an input field and <…> a button. The goal is to be able to manually override what comes from the DB and, in case the row is not "approved" for the next step in the workflow, to save the overrides in the DB for later check. <Update> button computes the sum of the fees. This should probably be handled by JavaScript, locally in the client. <Save> requires a POST transaction. The button has a formaction= to return the row id for identification of which order to process. This means the URL is http://host/app/save/<rowid> while the page is initially queried by http://host/app. It is "easy" to handle it in urls.py: urlpatterns=[ path('app', MyView.as_view(), name='current_list'), path('app/save/<id>', MyView.as_view(), name='patch_entry'), ] When <Save> is pressed, post() receives … -
How to make django automatically fill in a form field with information from another model that is in the database
`Good morning, I am building a system to manage the company I work for, however, I am facing a problem, as I need a certain field in the contract form to be already filled in with the process number to which it belongs, in this case, when I am going to register this contract, this registration is done by the process, by a button that sends to the contract template, which is more precise than the process number (it would be something like the name of the process, different from the primary key) at this moment I need the form is already loaded with the process number, and the user just enters the rest of the information, and saves. Below are my models, views, forms and templates. models i am using cbv to make this sistem -
Django Models - Table and Table status - how to model?
I need some advice... In my django app, I've got models: Order and Order status: class OrderStatus(models.Model): status = models.CharField(max_length=20, verbose_name="Status") class Order(models.Model): orderNo = models.CharField(max_length=20, verbose_name="Order", unique=True) orderStatus = models.ForeignKey(OrderStatus, on_delete=models.PROTECT, verbose_name="Status" ) There are 3 statuses..: New, In progress, Finished... In my views, I frequently use a code like: (for example to create Order) orderx = Order() orderStatus1 = OrderStatus.objects.get(pk=1) # <- the problem is here... orderx.orderStatus=orderStatus1 orderx.orderNo=i orderx.save() The problem, I've got is the one: I should't get Status object by char content (eg. "New" - because it can change, be in different language etc, so I should't filter it like: orderStatus1 = OrderStatus.objects.get(status="New") I also shouldn't get it by id like now: orderStatus1 = OrderStatus.objects.get(pk=1) because there is no warranty, that it will be the same ID while placing in other database, etc.. So how should it be modelled, so I can take STATUS_NEW somehow? -
Django mssql-django is error in MacOS but it is working on Windows
I have already installed pip install mssql-django on MacOS. It was working fine for a while after that stop executing the program ( python3 manage.py runserver) and display message error below: django.db.utils.Error: ('01000', "[01000] [unixODBC][Driver Manager]Can't open lib 'ODBC Driver 17 for SQL Server' : file not found (0) (SQLDriverConnect)") DB setting: 'default':{ 'ENGINE': 'mssql', 'NAME': 'dbname', 'HOST': 'x.x.x.x', 'PORT': '1433', 'USER': 'sa', 'PASSWORD': 'xxxx', 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server', } It is working fine on Windows but not working on MacOS why ? -
Duplicate rows in aggregation over values() with many-to-many relation
I'm trying to calculate a lookup for items sharing a common related object + a common value. It seems like it should be pretty straightforward, but I keep getting incorrect results no matter what I try. I can't get the grouping to be what I want it. Here's a simple example: I have Persons assigned to Teams; I have ExpenseReports signed by (multiple) Persons on particular dates. I want a query that finds, for each pair of Team and date, the total expense signed for by that team on that date. Here's my models: class MyTeam(models.Model): name = models.CharField() class MyPerson(models.Model): name = models.CharField() team = models.ForeignKey(MyTeam, on_delete=models.CASCADE) class ExpenseReport(models.Model): expense_paid = models.FloatField() expense_date = models.DateField() persons = models.ManyToManyField(MyPerson) And here's some simple data -- expense reports on two dates. Appa and Alex on Team A ; Barbara and Bob are on Team B: [2024-11-01] 1.0 paid by [<MyPerson: Person <Alex>>, <MyPerson: Person <Appa>>] <-- Team A [2024-11-01] 10.0 paid by [<MyPerson: Person <Barbara>>, <MyPerson: Person <Bob>>] <-- Team B [2024-11-05] 100.0 paid by [<MyPerson: Person <Barbara>>] <-- Team B [2024-11-05] 1000.0 paid by [<MyPerson: Person <Alex>>, <MyPerson: Person <Bob>>] <-- Teams A and B What I've Tried There's the … -
MSAL for React frontend & Django backend - Anything helps
Is there a standard practice for MSAL auth when using a separate frontend/backend lagnuage? Should I have both a Public and ConfidentialClient, or just one? I'm confusing myself after reading the docs thoroughly for a couple weeks... My primary goal is for users to obtain an access token with my client ID as the audience claim so that the django api can validate it (middleware), and then secure an additional set of tokens with MS Graph's default scope so that my backend can make calls to MS Graph (such as sending emails via the mail endpoint). It seems redundant for react to use msal.js library and the django backend to also use msal since it'll result in two separate token caches... Should I only implement msal into one of them? If so, should I prefer one over the other? I could use a little guidance in terms of how to structure my msal authentication in my project... Any help would be appreciated, no matter how small/quick it is... -
How to add the OneToOneField in to the BD in Admin site that was created using setattr function
I have some classes in models.py, and after adding one more I need to add one more attribute in to the already created class, I found in internet that the best way to do this is to use setattr() function, so I made all and.. It seems work, no bugs, it is showing in the Admin site as <django.db.models.fields.related.OneToOneField> , but there are no way to chose it when I trying to create or change this field, there aren't , is it a bug or I doing smth wrong? Here is my code: class PlayerInstance(models.Model): #... class Competition(models.Model): #... setattr(PlayerInstance, 'choice_to_competition', models.OneToOneField( Competition, default = 'for_nothoing', on_delete=models.RESTRICT, help_text='which competition is it taking part?', )) And no, I didn't forget to add 'choice_to_competition' in to the list_display. Here 2 photos of Admin site: I made them, but I can't add them here, can't understand reason, but it is not really necessary. -
Django Stat Reloader not working in Dev Container
I have a vs-code dev container in which Django is running. This container is also accessible, but I have two problems: a) The statreloader does not work b) In general, changes are saved within the container, but ignored (even after a restart). # .devcontainer/devcontainer.json { "name": "Existing Docker Compose (Extend)", "dockerComposeFile": [ "../docker-compose.yml", "docker-compose.yml" ], "service": "django", "workspaceFolder": "/workspace", "customizations": { "vscode": { "settings": {}, "extensions": [ "ms-python.python", "eamodio.gitlens", "editorconfig.editorconfig" ] } } } # .devcontainer/docker-compose.yml services: django: volumes: - .:/workspace:cached # ./docker-compose.yml name: experiments-graphql services: django: image: backend build: context: ./backend dockerfile: ./Dockerfile ports: - 8000:8000 # ./backend/Dockerfile FROM python:3.12 EXPOSE 8000 ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 RUN pip install uv COPY pyproject.toml uv.lock ./ RUN uv sync && uv lock WORKDIR /app COPY . /app RUN adduser -u 5678 --disabled-password --gecos "" appuser && chown -R appuser /app USER appuser CMD [ "uv", "run", "python", "manage.py", "runserver", "0.0.0.0:8000" ] -
Django jwt token error with react. "Given token not valid for any token type, token_not_valid"
I am using Django Rest Framework for authentication and Axios in the frontend(reactjs). Everything was working fine while development and then tested on a test server at my company and jwt was working fine, when deployed to the production server I randomly get the following error : { "detail": "Given token not valid for any token type", "code": "token_not_valid", "messages": [ { "token_class": "AccessToken", "token_type": "access", "message": "Token is invalid or expired" } ] } Sometimes I get this error in the first API call after login, some other time I get it after sending multiple requests after login, also I never get it through postman I am will list my nginx conf and my react config nginx: upstream api { server ${DJANGO_API}; } server { listen 80 default_server; server_name xx; server_tokens off; add_header X-Frame-Options "DENY"; proxy_cookie_flags one samesite=strict; client_max_body_size 10M; location /api/ { proxy_pass http://api$request_uri; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /admin/ { proxy_pass http://api$request_uri; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /swagger/ { proxy_pass http://api$request_uri; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /redoc/ { proxy_pass http://api$request_uri; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /staticfiles/ { … -
cannot install latest mysqlclient on ubuntu
I have read pip install mysql-python fails with EnvironmentError: mysql_config not found and mysql_config not found when installing mysqldb python interface and I am sure it is not a duplicate question. I had run sudo apt-get install python3-dev default-libmysqlclient-dev build-essential pkg-config and I have those build tools. I have mariadb installed. I also tried a different pypi mirror and the issue presists. Now I tried pip install mysqlclient and I got this. It seemed that pip is trying through versions. Finally I installed version 2.1.1 Collecting mysqlclient Using cached https://mirrors.tuna.tsinghua.edu.cn/pypi/web/packages/7d/62/51fbcd851834c830c940ded80280f593bd031137603329dd89479c68c5be/mysqlclient-2.2.6.tar.gz (91 kB) Installing build dependencies ... done Getting requirements to build wheel ... done Installing backend dependencies ... done Preparing metadata (pyproject.toml) ... done WARNING: Generating metadata for package mysqlclient produced metadata for project name unknown. Fix your #egg=mysqlclient fragments. Discarding https://mirrors.tuna.tsinghua.edu.cn/pypi/web/packages/7d/62/51fbcd851834c830c940ded80280f593bd031137603329dd89479c68c5be/mysqlclient-2.2.6.tar.gz#sha256=c0b46d9b78b461dbb62482089ca8040fa916595b1b30f831ebbd1b0a82b43d53 (from https://mirrors.tuna.tsinghua.edu.cn/pypi/web/simple/mysqlclient/) (requires-python:>=3.8): Requested unknown from https://mirrors.tuna.tsinghua.edu.cn/pypi/web/packages/7d/62/51fbcd851834c830c940ded80280f593bd031137603329dd89479c68c5be/mysqlclient-2.2.6.tar.gz#sha256=c0b46d9b78b461dbb62482089ca8040fa916595b1b30f831ebbd1b0a82b43d53 has inconsistent name: filename has 'mysqlclient', but metadata has 'unknown' Using cached https://mirrors.tuna.tsinghua.edu.cn/pypi/web/packages/be/95/1af2ee813d4f0b607082c18bb82aa05c98a95a402a1d2d5808999317cb16/mysqlclient-2.2.5.tar.gz (90 kB) Installing build dependencies ... done Getting requirements to build wheel ... done Installing backend dependencies ... done Preparing metadata (pyproject.toml) ... done WARNING: Generating metadata for package mysqlclient produced metadata for project name unknown. Fix your #egg=mysqlclient fragments. Discarding https://mirrors.tuna.tsinghua.edu.cn/pypi/web/packages/be/95/1af2ee813d4f0b607082c18bb82aa05c98a95a402a1d2d5808999317cb16/mysqlclient-2.2.5.tar.gz#sha256=add8643c32f738014d252d2bdebb478623b04802e8396d5903905db36474d3ff (from https://mirrors.tuna.tsinghua.edu.cn/pypi/web/simple/mysqlclient/) (requires-python:>=3.8): Requested unknown from … -
Django Unknown fields FieldError in forms.py with nested User model
Okay so this is a Django project I'm starting, and I have a User model in models.py. It has nested models, the 'contact' model and the 'personal' model. I want to create a form in Django. models.py class User(models.Model): """ Model representing a User with field groups """ class ContactInfo(models.Model): email = models.EmailField( max_length=120, validators=[EmailValidator()], unique=True, verbose_name="Contact Email" ) phone = models.CharField( max_length=10, blank=True, null=True, verbose_name="Phone Number" ) address = models.CharField( max_length=100, validators=[MinLengthValidator(5)], verbose_name="Address" ) suite = models.CharField( max_length=20, validators=[MinLengthValidator(0)], verbose_name="Suite" ) city = models.CharField( max_length=50, validators=[MinLengthValidator(3)], verbose_name="City" ) state = models.CharField( max_length=2, validators=[MinLengthValidator(2)], verbose_name="State" ) zip_code = models.CharField( max_length=5, validators=[MinLengthValidator(5)], verbose_name="Zip Code" ) class PersonalInfo(models.Model): first_name = models.CharField( max_length=40, validators=[MinLengthValidator(2)], verbose_name="First Name" ) last_name = models.CharField( max_length=40, validators=[MinLengthValidator(2)], verbose_name="Last Name" ) company = models.CharField( max_length=100, validators=[MinLengthValidator(5)], verbose_name="Company Name" ) contact = models.OneToOneField( ContactInfo, on_delete=models.CASCADE, related_name='user_contact' ) personal = models.OneToOneField( PersonalInfo, on_delete=models.CASCADE, related_name='user_personal' ) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return f"{self.personal.first_name} {self.personal.last_name}" forms.py from django import forms from .models import User, Request class UserForm(forms.ModelForm): """ Form for users """ class Meta: model = User fields = ( 'personal.first_name', 'personal.last_name', 'personal.company', 'contact.email', 'contact.phone', 'contact.address', 'contact.suite', 'contact.city', 'contact.state', 'contact.zip_code', ) def save(self, commit=True): user = super().save(commit=False) contact_info, _ = … -
Python unittest.mock patch fail with F() expressions can only be used to update, not to insert
A minimal working example is available at https://github.com/rgaiacs/django-mwe-magicmock. When using Django, I use Model.clean() to validate the form submitted by the user. During the validation, some fields might be updated based on the response of a HTTP request. I want to test the Model.clean() using Python's unittest and mocking the HTTP request. My app/models.py is import logging from django.core.exceptions import ValidationError from django.db import models from .aid import GitHosting logger = logging.getLogger(__name__) class Resource(models.Model): code_repository = models.URLField( help_text="Link to the repository where the un-compiled, human readable code and related code is located." ) version = models.CharField( blank=True, # Git hash contains 40 characters max_length=50, default="HEAD", help_text="The version of the resource in the format of a Git commit ID or Git tag.", ) def clean(self): git_host = GitHosting() self.version = git_host.get_version() and my app/tests.py is import logging from unittest.mock import patch from django.test import TestCase from django.urls import reverse from .models import Resource logger = logging.getLogger(__name__) @patch("app.models.GitHosting.get_version") class ResourceViewTestCase(TestCase): def test_add_resource(self, mock_get_version): mock_get_version = "5678" logger.error("Submitting form ...") response = self.client.post(reverse("app:index"), { "code_repository": "http://mygit.com/foo/bar" }) resource = Resource.objects.get(id=1) self.assertEqual(resource.version, "5678") When I run python manage.py test, the test fail with ValueError: Failed to insert expression "<MagicMock name='get_version().resolve_expression()' id='139668720464128'>" on app.Resource.version. F() … -
automatically backing up the last entry to a field in django admin
I have a model that serves as a price database for a part: class Part(models.Model): name = models.CharField("name", max_length=128) class Price(models.Model): value = models.DecimalField(max_digits=10, decimal_places=2) part = models.ForeignKey(Part, on_delete=models.CASCADE) is_active = models.BooleanField(default=True) in the admin I want to have a field that can change the price, but also a list where the old prices are visible. I kind of solved it with Django built in methods, but it seems rather complicated for such a simple request: class FakePlainTextWidget(forms.Widget): """ this widget masks an input field for prices so they are only being listed and not really editable or look that way """ def __init__(self, attrs=None): super().__init__(attrs) def render(self, name, value, attrs, renderer=None): s = f"""border: none; background-color: transparent; pointer-events: none; -webkit-appearance: none; -moz-appearance: textfield;""" return format_html(f"""<input type="number" name="{attrs["id"][3:]}" value="{value}" id="{attrs["id"]}" style="{s}"> €""") class PriceInlineForm(forms.ModelForm): class Meta: model = Price fields = "__all__" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if self.instance and not self.instance.is_active: # make fields read-only if price is_active=False for field in self.fields: self.fields[field].widget = FakePlainTextWidget() def save(self, commit=False): instance = super().save(commit=False) instance.is_active = False instance.save(update_fields=["is_active"]) Price.objects.create(value=self.cleaned_data["value"], part=instance.part) return instance class PriceInline(admin.TabularInline): model = Price can_delete = False exclude = ["is_active",] extra = 0 # No extra empty forms … -
My Django project settings seem to form an error
Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/Billing/ Using the URLconf defined in eCommerce.urls, Django tried these URL patterns, in this order: admin/ The current path, Billing/, didn’t match any of these. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. This is shown when I tried to create an app using django Here is the code for the program main.urls from django.contrib import admin from django.urls import path, include from BillingST.eCommerce.Billing import views urlpatterns = [ path("admin/", admin.site.urls), path("Billing/", include('Billing.urls')), path('', views.access, name='access') ] billing.urls from django.contrib import admin from django.urls import path, include urlpatterns = [ path('Billing/', include('Billing.urls')), path('admin/', admin.site.urls), ] I was trying to run the code for billing page, but it says to navigate to admin -
Partially initialized module 'pyairtable'
Basically I am bulding a sort of database manager on DJango for the place I work for. I am trying to use airtable as the database (Instead of a JSON or other methods) because we have all the information there. But everytime I try to run the script, it gives me this error AttributeError: partially initialized module 'pyairtable' from 'C:\Users\PC\AppData\Local\Programs\Python\Python313\Lib\site-packages\pyairtable\__init__.py' has no attribute 'api' (most likely due to a circular import). I have the propper packages installed, and I tried looking for a file with the same name that could cause this error, but I found nothing. To test it I even did this script for python and it still does not work from pyairtable import Table from dotenv import load_dotenv, find_dotenv AT = os.getenv(AIRTABLE_TOKEN) BI = os.getenv(BASE_ID) RC_table = Table(AT, BI, 'RC') LB_table = Table(AT, BI, 'L&B') PM_table = Table(AT, BI, 'PM') print("Table imported and initialized successfully!") And it still gives me the same error, I have tried to get the token by pasting it directly on the app and then using the os.getenv() (the token has access to do everything on the airtable tables). I don't know what to do to make it work. -
Best practices for API update and deployment in an existing Django project
Our existing Django project with a couple of apps has new API requirement. I'm thinking of the possibility to deploy the new restful API in a separate wsgi server so the API service will be independent from the orignal Django project. I can see two options: Create new API project which will inherit models and auth. This allows semi-independent update and deployment on the production. Or just create new app in the same project, but use another wsgi server with separate settings. While I'm writing this down I'm already having other insights (magic of writing thoughts), but the objective is to have the API updated and deployed without penalize the availabilty of the existing apps. -
How to integrate the Clover payment gateway using Python?
I’m currently working on integrating the Clover payment gateway in a Python application, but I’m facing some challenges. I’ve reviewed the Clover API documentation and attempted to set up the necessary authentication and API calls, but I’m not sure if I’m following the best practices or missing any key steps. Could anyone with experience in integrating Clover provide guidance, examples, or point me to relevant resources? Here’s what I’ve tried so far: Configured OAuth authentication and fetched some details including Merchant Id, Employee Id, Access Token. We are trying to integrate the payment gateway when a user submits a form. Is there any sample code or any tutorials related to this? Any details would be helpful. -
Selenium doesn't use testing database during Django functional tests in Docker or cannot access container because of port issues
Issue My Selenium Chrome Browser cannot access my Django web application when it uses Djangos test database: host_ip = socket.gethostbyname(socket.gethostname()) host_port = urlparse(self.live_server_url).port self.live_server_url = f"http://{host_ip}:{host_port}" # results in # selenium.common.exceptions.WebDriverException: Message: unknown error: net::ERR_CONNECTION_REFUSED Djangos StaticLiveServerTestCase creates random ports when creating test databases. With docker I can only expose hard coded ports. I can set one fixed port on my tests. But then they complain, that the port is already taken. class FunctionalTest(StaticLiveServerTestCase): """Functional Testing base class.""" port = 50500 # resulsts in: # OSError: [Errno 98] Address in use The other option I thought of was to set the URL for Selenium to my running web application, but than the test database created by StaticLiveServerTestCase won't be used. Instead it uses the postgres container, where objects created in the setup phase cannot be found. In my example test the user cannot login, because the Selenium access a version of the application serving the postgres db instead of the testing db. self.live_server_url = "http://web:8000" # results in # AssertionError: 'Profile' not found in 'Sign In' # the surrounding code is setup correctly, so this normally results in success. Setup I try to create a pipeline for my test driven … -
Django model has ManyToMany field, how to get all IDs without fetching the objects?
I have a data structure like this: class Pizza(models.Model): name = models.CharField(max_length=100) toppings = models.ManyToManyField(Topping, related_name="pizzas") class Topping(models.Model): name = models.CharField(max_length=100) And to get all topping IDs related to a pizza I can do this: list(map(lambda t: t.id, pizza.toppings.all())) But this fetches all toppings completely from the database, even thought I only need the IDs. Is there a way to get the IDs without fetching the complete objects (for performance reasons)? -
How to use Django {% querystring %} with GET form?
In Django 5.1 {% querystring %} was added. Is there some way to use it with GET form? For example, let's say we have template with: <span>Paginate by:</span> <a href="{% querystring paginate_by=50 %}">50</a> {# ... #} <form method="GET"> <input name="query" value="{{ request.GET.query }}"> <button type="submit">Search</button> </form> Assuming that we are currently on localhost:8000/?paginate_by=50, how to change form so clicking Search won't delete paginate_by query parameter - so what I want is for example localhost:8000/?paginate_by=50&query=abc and not localhost:8000/?query=abc? Before 5.1 I handled that via providing form with hidden fields based on GET parameters, but I am hoping that now more elegant solution is possible. -
VS Code does not forward ports (Dev Containers)
I'm currently trying to put my Django application into a dev container. And in itself it does work, but however, I cannot access the page in my browser. I'm using this Tutorial. ./backend/Dockerfile FROM python:3.12 EXPOSE 8000 ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 RUN pip install uv COPY pyproject.toml uv.lock ./ RUN uv sync && uv lock WORKDIR /app COPY . /app RUN adduser -u 5678 --disabled-password --gecos "" appuser && chown -R appuser /app USER appuser CMD [ "uv", "run", "python", "manage.py", "runserver", "0.0.0.0:8000" ] ./docker-compose.yml name: experiments-graphql services: django: image: backend build: context: ./backend dockerfile: ./Dockerfile ports: - 8000:8000 ./.devcontainer/devcontainer.json { "name": "Existing Docker Compose (Extend)", "dockerComposeFile": [ "../docker-compose.yml", "docker-compose.yml" ], "service": "django", "workspaceFolder": "/workspace", "customizations": { "vscode": { "settings": {}, "extensions": [ "ms-python.python", "eamodio.gitlens", "editorconfig.editorconfig" ] } } } ./.devcontainer/docker-compose.yml services: django: volumes: - .:/workspace:cached command: /bin/sh -c "while sleep 1000; do :; done" -
Why is my WebSocket connection being rejected with "Unauthenticated user" in Django Channels even with a valid JWT token?
I am working on a real-time chat application using Django Channels and WebSockets. I have implemented a custom user authentication system using JWT tokens and attached the token-based authentication to the WebSocket connection using Django Channels middleware. However, my WebSocket connection is always being rejected with the message: "Unauthenticated user attempted to connect.", despite sending a valid JWT token in the Authorization header. Here is the relevant code and setup for my project: Project Setup: Django Version: 4.1.4 Django Channels Version: 4.0.0 ASGI Server: Daphne Custom User Model: BasicUserProfile (which stores the JWT token in the auth_token field) Code: 1. CustomAuthMiddleware - Middleware for JWT Authentication: import jwt from datetime import datetime from channels.middleware.base import BaseMiddleware from authentication.models import BasicUserProfile from django.contrib.auth.models import AnonymousUser from django.conf import settings from channels.db import database_sync_to_async class CustomAuthMiddleware(BaseMiddleware): async def populate_scope(self, scope): user = scope.get('user', None) if user is None: token = self.get_token_from_headers(scope) if token: user = await self.get_user_by_token(token) else: user = AnonymousUser() scope['user'] = user def get_token_from_headers(self, scope): headers = dict(scope.get('headers', [])) token = headers.get(b'authorization', None) if token: token_str = token.decode() if token_str.startswith("Bearer "): return token_str[len("Bearer "):] return None @database_sync_to_async def get_user_by_token(self, token): try: decoded_token = jwt.decode(token, settings.SECRET_KEY, algorithms=["HS256"]) if decoded_token.get('exp') and decoded_token['exp'] … -
Django/html mp3 autoplay
I've got django application, and one view, that checks some data, and passess "play" variable to the template. If play is true - short mp3 "bing" should be played, else, it is not played. The page reloads every 10 seconds, to call view, checks if 'play' changed, and make sound possibly. The problem is, that just after first page load, nothing is autoplayed. I need to click play button on html player one time, and after that, everything works perfectly. But without this first "manual play", it is not working. Any ideas? The django template code is as follows. <html> <head> <script> window.onload = function() { var context = new AudioContext(); } function autoRefresh() { window.location = window.location.href; } setInterval('autoRefresh()', 10000); </script> </head> <body> {%if play%} <audio autoplay controls id="music" > <source src="{%static 'app1/stat1/d.mp3'%}" type="audio/mpeg"> </audio> {%endif%} </body> </html>