Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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> -
Migration in different schemas of database in Python Django 5
I have a problem to make migrations in PostgreSQL database with 2 schemas: public and users. I have models for users and their profiles. It requires to put them on schema with name "users" and then create superuser and some basic users. But every time when I do migrations, Django creates tables in default schema "public" or I have different mistakes. Many attempts to fix this didn't get me a result, so I need help. My models: class MyUser(AbstractUser): class Meta: managed = True db_table = 'users\".\"user' # gives a problem email = models.EmailField(_("email address"), unique=True) USERNAME_FIELD = "email" REQUIRED_FIELDS = ["username"] objects = MyUserManager() class MyProfile(models.Model): class Meta: managed = True db_table = 'users\".\"profile' # gives a problem user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) name = models.CharField(max_length=200, default="Name") surname = models.CharField(max_length=200, default="Surname") My Manager: class MyUserManager(BaseUserManager): def create_user(self, email, password, **extra_fields): if not email: raise ValueError(_("Email required")) email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() return user def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault("is_staff", True) extra_fields.setdefault("is_superuser", True) extra_fields.setdefault("is_active", True) if extra_fields.get("is_staff") is not True: raise ValueError(_("is_staff=True required")) if extra_fields.get("is_superuser") is not True: raise ValueError(_("is_superuser=True required")) return self.create_user(email, password, **extra_fields) My DB: 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': "djangotest", 'USER': "postgres", 'PASSWORD': "********", … -
Issue with Testing UpdateView in Django
I have an UpdateView that allows editing objects of the Scooter model. After successfully processing the form (via a POST request), the view is supposed to redirect the user to the detail page of the edited scooter (with a 302 status code). However, in my test, I see that the response after the POST request returns a 200 status code, and response.context contains the object data, as if the form was re-rendered instead of a redirect occurring. Why does the UpdateView return a 200 status code after the POST request, even though the get_success_url method is correctly configured? Is using response.context after POST appropriate in such a test? Should I instead use refresh_from_db for the object in the database? Is there a better way to test UpdateView behavior in Django to avoid potential inconsistencies with the view's behavior after a POST request? (these are in different files ofc, i just needed to paste it here) @pytest.mark.django_db def test_scooter_detail_edit_data(client, superuser_user, available_scooter): url = reverse('scooter-update', kwargs={'scooter_id': available_scooter.id}) client.force_login(superuser_user) response = client.get(url) assert response.status_code == 200 assert response.context['scooter'].available == True assert response.context['scooter'].daily_price == 100 response = client.post(url, data={ 'available': False, 'daily_price': 200, }) assert response.status_code == 200 assert response.context['scooter'].available == False assert response.context['scooter'].daily_price … -
How to highlight all the streets within a range of coordinates of a specific city (eg. Milan) using polyline (Leaflet)?
I want to use overpass API (OpenStreetMapAPI) to fetch the coordinates(longitude and latitude: start, midpoint, end) of all the streets(with specific addresses) within the coordinate range of a specific city(eg. Milan). Can you recommend any documentation or tutorials for this? -
Using AG-grid community addition in offline mode
I am adding Ag-grid community addition (plain java script version) into my django/python app. i was able to make inline editing and other cool free features work by inserting into my base.html. Now, i was asked to copy that js into the repository so that it will work when/if we don't have internet. I copied the content of "https://cdn.jsdelivr.net/npm/ag-grid-community/dist/ag-grid-community.min.js" into my static/js folder and called it ad-grid-community.min.js, so now my base.html file has this link instead: However, now a lot of inline-editing features in my ag-grid table stopped working. I am guessing i need to install additional modules, but how do i do that? Thanks a lot in advance! -
Why does Django show 'using password: NO' error despite correct database credentials?
I'm experiencing an issue with my Django project where logging in produces the following error: Error: (1045, "Access denied for user 'jdcbde5_vawcdb'@'localhost' (using password: NO)") Error: Details: Deployed Project: https://jdcbdev.website/ at inmotionhosting The database credentials in my Django settings (settings.py) are correct. Here's a snippet: I confirmed that NAME and USER are the same with correct password. With correct grants: I wrote a standalone Python script using mysqlclient to connect to the database, and it works without any issues: What could cause Django to fail with this error despite the credentials being correct? Is there something specific about Django's handling of database connections that I might be missing? Thanks in advance for your help! -
Paste object data into admin form
Need help. I have an object that I add using the standard administration form by link /admin/tasklist/task/add/ model.py class Task(models.Model): name = models.CharField("Name", max_length=100) discr = models.CharField("Discription", max_length=255) date = models.DateField("Date") status = models.IntegerField("Status", default=2) def __str__(self): return self.name def natural_key(self): return (self.name) class Meta: db_table = 'tasks' verbose_name = 'Task' verbose_name_plural = 'Tasks' I want to be able to copy an object after making edits from the same admin form. I need that when clicking on the link /admin/tasklist/task/1/copy, the form for adding an object opens, and data from object 1 is inserted into the status and date fields. Maybe I need to create one Custom Admin Actions for this? -
How Do I Set Up WebSockets for a Real-Time Chat App Using Django Channels and React?
I’m working on a real-time chat application with Django Channels on the backend and React on the frontend. My goal is to enable users to exchange messages in real time, but I’m having trouble connecting everything properly. Here’s a rundown of what I’ve done so far: Backend (Django) I’ve set up Django Channels with WebSocket support. This is what my asgi.py file looks like: import os from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter, URLRouter from channels.security.websocket import AllowedHostsOriginValidator from channels.auth import AuthMiddlewareStack import chat.routing os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backend.settings') django_asgi_app = get_asgi_application() application = ProtocolTypeRouter({ "http": django_asgi_app, "websocket": AllowedHostsOriginValidator( AuthMiddlewareStack( URLRouter( chat.routing.websocket_urlpatterns ) ) ), }) Here’s my WebSocket routing setup in routing.py: from django.urls import path from . import consumers websocket_urlpatterns = [ path('ws/chat/<str:chatgroup_name>', consumers.ChatConsumer.as_asgi(),), ] The consumer (ChatConsumer) handles WebSocket connections and message broadcasts. Here’s a simplified version of it: class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.chatgroup_name = self.scope['url_route']['kwargs']['chatgroup_name'] self.user = self.scope['user'] await self.channel_layer.group_add(self.chatgroup_name, self.channel_name) await self.accept() async def disconnect(self, close_code): await self.channel_layer.group_discard(self.chatgroup_name, self.channel_name) async def receive(self, text_data): message = json.loads(text_data)['body'] await self.channel_layer.group_send( self.chatgroup_name, { 'type': 'chat_message', 'message': message, } ) async def chat_message(self, event): await self.send(text_data=json.dumps(event)) and this is the messages page in the react app: import { useState, useEffect, … -
How to mock a function in a django custom command?
How can I mock foo in order to have it NOT called? Here's my latest attempt: #~/django/myapp/management/commands/acme.py def foo(): pass class Command(BaseCommand): def handle(self, *args, **options): foo() #~/django/myapp/tests/test.py from django.core.management import call_command @mock.patch('myapp.management.commands.acme.foo') def test_command_output(self,mock_foo): call_command('acme') assert not mock_foo.called -
Pre-fetching huge querysets in django
TLDR: how can I prevent very large IN sets in the SQL query generated? When I pre-fetch a ManyToMany field pointing to model Tag from a model Object: obj_qs = models.Object.objects.filter(created_time__gt = 2024) obj_qs.prefetch_related('tags') I get a pre-fetching SQL query of the following form: SELECT (`main_object_tag`.`object_id`) AS `_prefetch_related_val_object_id`, `main_tag`.`id`, `main_tag`.`name` FROM `main_tag` INNER JOIN `main_object_tag` ON (`main_tag`.`id` = `main_object_tag`.`tag_id`) WHERE `main_object_tag`.`object_id` IN (1, 2, 3, 4, 5); args=(1, 2, 3, 4, 5) The problem is, the IN clause could be huge this way - hundreds of thousands of objects in my case. Could I work around this somehow - using a query instead of the "IN" specification? Extra: why? We would serialize the objects in the following way subsequently: return JsonResponse([ { 'name': obj.name, 'tags': [tag.name for tag in obj.tags.all()] } for obj in obj_qs ]) -
Django MySQL and CONVERT_TZ
I need to know the duration of some events in my MySQL database. Around DST the duration in UTC is different then in local time and I need to know them in local time. I have found a way to do this, but I was wondering if this function can be improved. from django.db.models import ExpressionWrapper, F, fields from django.db.models.functions import Cast from django.db.models.expressions import RawSQL duree = ExpressionWrapper(F('_dtend') - F('_dtstart'), output_field=fields.DurationField()) event_dur = Event.objects.annotate( _dtstart=Cast( RawSQL("CONVERT_TZ(dtstart, 'UTC', timezone)", ()), fields.DateTimeField() ), _dtend=Cast(RawSQL("CONVERT_TZ(dtend, 'UTC',timezone)", ()), fields.DateTimeField()), ).annotate( dur=duree ) Without the convert_tz I find 8000 events, with only 1000. There are probably 7000 events around DST last October. So the duration works fine. Great. Problem solved. However, if I do: event_dur.first()._dtstart, event_dur.first().dtstart I get back: datetime.datetime(2024, 11, 22, 0, 0, tzinfo=datetime.timezone.utc), datetime.datetime(2024, 11, 21, 23, 0, tzinfo=datetime.timezone.utc) As you can see the _dtstart (which uses Europe/Amsterdam btw) has the correct time, but the tzinfo is wrong (should be 'Europe/Amsterdam'). While for the duration this is no big problem I was wondering if there is a way to also include the correct timezone information directly out of the database? -
How to annotate type of Manager().from_queryset()?
In Django I have custom QuerySet and Manager: from django.db import models class CustomQuerySet(models.QuerySet): def live(self): return self.filter(is_draft=False) class CustomManager(models.Manager): def publish(self, instance: "MyModel"): instance.is_draft = False instance.save() In my model I want to use both, so I use from_queryset method: class MyModel(models.Model): objects: CustomManager = CustomManager().from_queryset(CustomQuerySet)() is_draft = models.BooleanField(blank=True, default=True) Since I annotated objects as CustomManager, Pylance (via vscode) logically yells at me that MyModel.objects.live() is wrong, due to Cannot access attribute "live" for class "CustomManager" Attribute "live" is unknown. Removing type annotation leads to similiar complaint: Cannot access attribute "live" for class "BaseManager[MyModel]" Attribute "live" is unknown. How to annotate objects in MyModel so Pylance will be aware that objects also has CustomQuerySet methods available, not only CustomManager methods? -
How to make group by in djano ORM
I've an Order model as below: class Order(models.Model): bill = models.ForeignKey(Bill, on_delete=models.PROTECT, null=True, blank=True) address_from = models.ForeignKey(Address, on_delete=models.PROTECT) address_to = models.ForeignKey(Address, on_delete=models.PROTECT) How can I group a queryset from it and iterate in each group like the following: bill = models.Bill.objects.create() groups = Order.objects.all().group_by('address_from', 'address_to') for group in groups: group.update(bill = bill) The goal is to set a bill for each group of the orders that have the same address from and address to. -
How to read headers from axios post in django?
I am sending an axios post to my django backend app: async function sendBookingRequest() { // console.log(date,bookedHours,cancha,cellphone) try { axios.post("https://danilo2588.pythonanywhere.com/book", { headers: {'Authorization':"1234567890123456789012345678901234567890"}, params:{ 'requested_date':date, 'hours':bookedHours, 'business':cancha, 'phone':cellphone, } }) .then( function(response){ setConfirmation(response.data) setStepper(7) }) .finally( setIsLoading(false) ) } catch(error){ console.log(error) }; } In my views I have: def booking(request): auth_key = request.headers.get('Authorization') if auth_key: generic_user = Token.objects.get(key=auth_key).user if request.method == "POST" and generic_user: #do whatever needed... However the views is not reading the headers and throws an error. I could simply remove the Authentication/token line and voila! but the thing is that I want to keep the code as secure as possible. What is wrong with my code? -
How to add event liteners in Django?
I have the following code in html with a js script, but i want to add it to my django forms but i don't know how or where to start. What it does is that it automatically multiplies two numbers as the user types and shows the predict in a different part of the table. {% extends "blog/base.html" %} {% block content %} <h1>About Page</h1> <div class="container"> <h2>Basic Table</h2> <form> <table class="table"> <thead> <tr> <th>Value</th> <th>Amount</th> <th>Total</th> </tr> </thead> <tbody> <tr> <td>10</td> <td> <div class="form-group"> <label for="usr"></label> <input type="text" class="form-control" id="num1" /> </div> </td> <td> <div id="total"></div> </td> </tr> <tr> <td>20</td> <td> <div class="form-group"> <label for="tt"></label> <input type="text" class="form-control" id="num2" /> </div> </td> <td> <div id="total 2"></div> </td> </tr> <tr> <td>30</td> <td><div class="form-group"> <label for="ttt"></label> <input type="text" class="form-control" id="num3" /> </div></td> <td><div id="total 3"></div></td> </tr> </tbody> </table> </form> </div> <script> function multiply(a, b, outputId) { var total = a * b; document.getElementById(outputId).innerHTML = total; } const num1 = document.getElementById('num1'); const num2 = document.getElementById('num2'); const num3 = document.getElementById('num3'); num1.addEventListener('input', (event) => { console.log(event); multiply(10, Number(event.target.value), 'total'); }); num2.addEventListener('input', (event) => { multiply(20, Number(event.target.value), 'total 2'); }); num3.addEventListener('input', (event) => { multiply(30, Number(event.target.value), 'total 3'); }); </script> {% endblock content %} I … -
Populating CheckboxSelectMultiple widget using my own model in Wagtail admin
Context I've created a model, corresponding field model, and intend to reuse the built-in CheckboxSelectMultiple widget for use within the Wagtail admin. The concept is a multiple-select permission field that is saved as a bit-field: # Model class class Perm(IntFlag): Empty = 0 Read = 1 Write = 2 I used Django's model field's documentation to create a field model that can translate my Perm type to and from my database (saved as an integer field that bitwise OR's the respective permission bits): # Model field class class PermField(models.Field): description = "Permission field" def __init__(self, value=Perm.Empty.value, *args, **kwargs): self.value = value kwargs["default"] = Perm.Empty.value super().__init__(*args, **kwargs) def deconstruct(self): name, path, args, kwargs = super().deconstruct() args += [self.value] return name, path, args, kwargs def db_type(self, connection): return "bigint" # PostgresSQL def from_db_value(self, value, expression, connection): if value is None: return Perm.Empty return Perm(value) def to_python(self, value): if isinstance(value, Perm): return value if isinstance(value, str): return self.parse(value) if value is None: return value return Perm(value) def parse(self, value): v = Perm.Empty if not isinstance(ast.literal_eval(value), list): raise ValueError("%s cannot be converted to %s", value, type(Perm)) for n in ast.literal_eval(value): v = v | Perm(int(n)) return v Then, I also created a Wagtail snippet … -
How to implement multi-step product creation with related models (Tax, Currency, Delivery Area, Category) in Django Rest Framework?
I am working on a product creation process using Django Rest Framework (DRF), and I have models for Tax, Currency, DeliveryArea, Category, and Product. The creation process is divided into multiple steps, with each step capturing different parts of the product's information. Here's what I am trying to achieve: Models: Product: The main model that represents the product. Category: The category to which the product belongs. Currency: The currency for the product's price. DeliveryArea: The delivery area for the product. Tax: The tax details for the product. Steps in the Process: Step 1: Product name, description, and category. Step 2: Price, currency, and delivery area. Step 3: Tax information. What I Need: Data Persistence: I need to save the data progressively as the user completes each step of the form. Step-by-step editing: Users should be able to return to any previous step and update their inputs without losing the progress in the steps they've already completed. Related Models: I need to handle the relationships between the Product model and the other models (Category, Currency, DeliveryArea, and Tax). Approach I've Considered: I plan to use DRF serializers for each step, with the relevant fields for that step. I want to use … -
Django: from user's language to the locale string - how to?
In our Django/Python/Linux stack we want to determine the correct locale from the user's language. The language might be 'de' and the locale could be something like de_DE or de_AT or even de_CH.UTF-8 - depending on what locale -a returns. In case of ambiguity we would just use the first valid entry for the respective language. This locale string shall than be used to determine the correct number format for instance like so: locale.setlocale(locale.LC_ALL, user.language) formattedValue = locale.format_string(f'%.{decimals}f', val=gram, grouping=True) We don't want to create a relation between language code and locale string in our application - so defining a dictionary containing languages and locale strings is not something we have in mind. The information should be retrieved generically. Any ideas how to do it in a proper way? -
"Why is the object passed through Link state in React undefined when accessed via useLocation on the next page?"
I'm having trouble passing an object through the Link state in React Router, and it's coming up as undefined when I try to access it on the next page using useLocation. Here’s a breakdown of my setup and the issues I'm encountering. Staff Component (Staff.js) I'm fetching staff data from an API and rendering it with React Router's Link: import React, { useEffect, useState } from 'react'; import { Link } from 'react-router-dom'; const Staff = () => { const [staffMembers, setStaffMembers] = useState([]); useEffect(() => { // Fetch staff data from API fetch('https://api.example.com/staff') .then(response => response.json()) .then(data => setStaffMembers(data)) .catch(error => console.error('Error fetching staff:', error)); }, []); return ( <div className="hidden p-5 md:grid md:grid-cols-4 gap-6"> {staffMembers.map((staff) => ( <Link key={staff.id} to={{ pathname: `/staff/${staff.title.replace(/\s+/g, '-')}`, state: { staff } // Pass the entire staff object here }} className="image-div shadow hover:shadow-lg text-center rounded flex flex-col items-center border-l-8 border-yellow-200 p-3" > {staff.title_logo ? ( <img src={staff.title_logo} alt={staff.title} className="w-16 h-16" /> ) : ( <div className="w-16 h-16 bg-gray-300 flex items-center justify-center"> <span>No Logo Available</span> </div> )} <span className='mb-2 font-semibold text-lg'>{staff.title}</span> </Link> ))} </div> ); }; export default Staff; Staff Detail Component (StaffDetail.js) I’m trying to access the passed staff object using useLocation: import … -
Should the csrf template tag be used in a Search form?
I have a django view that allows a user to search and get data from a database. No changes are made to the database. I also realized that the csrf token shows up in the url. I searched online and read that this shouldn't be the case and that when making GET requests I should not include the csrf token but I am still not sure. Here is my code: view: class SearchResultsListView(ListView): model = Processor template_name = 'finder/search_results.html' paginate_by = 10 # Number of results per page def get_queryset(self): query = self.request.GET.get("q") return Processor.objects.filter( Q(name__icontains=query) | Q(standard_transaction_fee__icontains=query) | Q(accepted_payment_methods__icontains=query) | Q(available_merchant_countries__icontains=query) | Q(supported_business_types__icontains=query) | Q(basic_info__icontains=query) | Q(restricted_prohibited_business__icontains=query) ) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['query'] = self.request.GET.get('q', '') return context html: <div class="search-container-container"> <div class="search-results-container"> <!-- Top search bar --> <div class="search-header"> <form action="{% url 'search_results' %}" method="GET" class="search-search-form"> {%csrf_token%} <input type="text" name="q" class="search-input" placeholder="Search processors..." value="{{ request.GET.q }}" aria-label="Search" > <button type="submit" class="search-button"> Search </button> </form> </div> -
Query N rows around the row id with complex ordering in Django ORM
According to the reference id, I want to query N rows, so that the row with the reference id would be in the middle. I know how to do it when the QuerySet is simply ordered by id column, but my solution falls apart when I want to order the results by a column other than id (as ids are not sequential anymore) or by multiple columns (e.g. (title, created_at)). For example, if I had 5 items in the table below, and wanted to query 3 items with a reference id of 3, it would select rows with id 2, 3 and 4: Id Title 1 One 2 (Selected) Two 3 (Selected) Three 4 (Selected) Four 5 Five I tried using Window() function with RowNumber() expression to assign row numbers to a sorted list of items, and then query items before and after the reference id row number, which, unsurprisingly, did not work as row numbers are recomputed on each query. -
I want to construct a value dynamically with variable number of parents python django
I am working on a django project. I have my Providable model and a foreign key: category (providable_categtory). each category can have multiple sub-categories and a providable will finally be assigned to a leaf node. here is how the category code for each providable is created: @property def get_code(self): return f"{self.category.get_code}-{self.code}" the get_code method in providable_category: @property def get_code(self): if not self.parent: return self.code else: return f"{self.parent.get_code}-{self.code or self.pk_code}" as you can see when i display a providable code in the django admin it's something like: a-b-c-6 where a,b and c are categories and 6 is the providable's own code. so now I want to be able to search for a providable in django admin using it's full code but since the full providable code is not a field of providable it can't be done directly by adding the get_code method to search field. what I did was, I implemented an override of the get-search_results method in my ProvidableAdmin class as below: def get_search_results(self, request, queryset, search_term): # annotation for the service_code. queryset = queryset.annotate( service_code=Concat( "category__parent__parent__code", Value("-"), "category__parent__code", Value("-"), "category__code", Value("-"), "code" ) ) queryset, may_have_duplicates = super().get_search_results(request, queryset, search_term) return queryset, may_have_duplicates and added service_code to search_fields. this … -
Connecting to mariaDB in Github action
I know there are multiple related questions but I can't get this to work. I'm working on a Github action to test my Django app using MariaDB and Selenium before deploying. I have simplified it to just running the tests for now. I have reviewed my secrets and know they are correct. I have tried running services on both localhost and in a container, but neither can seem to resolve the database address. I have tried it like this: name: Deploy on: push: jobs: django-tests: runs-on: ubuntu-latest services: db: env: MYSQL_ROOT_PASSWORD: ${{ secrets.MYSQL_ROOT_PASSWORD }} MYSQL_DATABASE: ${{ secrets.MYSQL_DATABASE }} MYSQL_USER: ${{ secrets.MYSQL_USER }} MYSQL_PASSWORD: ${{ secrets.MYSQL_PASSWORD }} image: mariadb:11.5 options: > --health-cmd="healthcheck.sh --connect --innodb_initialized" ports: - 3306:3306 selenium: image: selenium/standalone-chrome ports: - 4444:4444 steps: - name: Check out code uses: actions/checkout@v3 - name: Debug Hostname Resolution run: | ping -c 4 localhost:3306 || echo "Failed to resolve 'db'" - name: Set up Python uses: actions/setup-python@v4 with: python-version: 3.12 - name: Install dependencies run: | python -m pip install --upgrade pip pip install -r requirements.txt - name: Run Django Selenium Tests env: SECRET_KEY: ${{ secrets.DJANGO_SECRET }} MYSQL_ROOT_PASSWORD: ${{ secrets.MYSQL_ROOT_PASSWORD }} MYSQL_DATABASE: ${{ secrets.MYSQL_DATABASE }} MYSQL_USER: ${{ secrets.MYSQL_USER }} MYSQL_PASSWORD: ${{ secrets.MYSQL_PASSWORD }} … -
HX-Trigger to issue a request using arguments
I want to create a request after a trigger using htmx after a button was clicked with django: def SomeView(request, var1, var2): trigger_data = json.dumps({"dlstart": {"pid": pid, "var1": var1}}) return HttpResponse("", headers={"HX-Trigger": trigger_data}) I can see in the Network Tab the GET request is working. But now I want to add the two arguments from trigger_data to my hx-get dynamically. I did not find a way in htmx alone to achieve this, so I did a JS workaround (which I would gladly drop in favor of a htmx only solution): document.body.addEventListener("dlstart", function() { const url = `/someURL/${event.detail.pid}/${event.detail.var1}`; const filename = "test.png"; fetch(url) .then(response => { if (!response.ok) { throw new Error('was not ok'); } return response.blob(); }) .then(blob => { const link = document.createElement('a'); link.href = window.URL.createObjectURL(blob); link.download = filename; document.body.appendChild(link); link.click(); // feels so ugly document.body.removeChild(link); }) }); I imagine some combination of hx-get and dynamically add the arguments must work too? -
Docker Compose - The ImageField field in Django cannot upload images when I migrate the database from sqlite3 to MySQL in Docker Compose
I have the Article model in Django blog app File /backend/blog/models.py class Article(models.Model): class Status(models.TextChoices): DRAFT = 'DF', 'Draft' PUBLISHED = 'PB', 'Published' title = models.CharField(max_length=255) slug = models.SlugField(max_length=100, blank=True, unique=True) content = MDTextField(null=True, blank=True) author = models.ForeignKey(User, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) comments = models.IntegerField(default=0) reactions = models.IntegerField(default=0) updated = models.DateTimeField(auto_now=True) category = models.ForeignKey(Category, related_name='articles', on_delete=models.SET_NULL, null=True) tags = models.ManyToManyField(Tag) image_background = models.ImageField(upload_to='articles_images/', blank=True, null=True) image_url = models.URLField(max_length=500, blank=True, null=True) # Updated field to store image URL from Firebase intro = models.TextField() estimate_time = models.CharField(max_length=50) type = models.ForeignKey(Type, on_delete=models.SET_NULL, null=True) publish = models.DateTimeField(default=timezone.now) status = models.CharField(max_length=2, choices=Status.choices, default=Status.DRAFT) Next, I porting the default database SQLITE3 to MYSQL for Django project File /backend/settings.py # ! Config database for mysql DATABASES = { "default": { "ENGINE": os.environ.get("SQL_ENGINE", "django.db.backends.sqlite3"), "NAME": os.environ.get("SQL_DATABASE", os.path.join(BASE_DIR, 'db.sqlite3')), "USER": os.environ.get("SQL_USER", "myuser"), "PASSWORD": os.environ.get("SQL_PASSWORD", "myuserpassword"), "HOST": os.environ.get("SQL_HOST", "localhost"), "PORT": os.environ.get("SQL_PORT", "3306"), 'OPTIONS': { 'charset': 'utf8mb4', } } } I also config the path media to upload image /backend/settings.py STATIC_URL = 'static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATICFILES_DIRS = (os.path.join(BASE_DIR,"static"), ) I used the docker-compose.yml to build image and run container for backend (django), frontend (nextjs) and database (mysql) to develop my project version: '3.8' services: database: image: …