Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cronjob in Docker container uses outdated settings in Django, despite environment variables in Docker Compose
I'm facing a persistent issue with a Django app using Django REST Framework. The application has several models, including one called Project with a created_at timestamp. There’s a management command in manage.py that archives a project if a user hasn't taken action on it within 72 hours of its creation. This command is executed by a cronjob in production, and the entire setup runs within a Docker container. Initial Setup In the past, I separated the back-end environment into two Docker containers: One container ran the Django application and served the API. The other container was dedicated solely to running the cronjob that executed these management commands. Reason for Combining Containers This setup had the same issue with outdated settings, and managing both containers separately added significant overhead, as I needed to clear both containers’ caches and rebuild them frequently. To simplify, I combined the API and cronjob into a single container and used Supervisor to manage the cronjob within this container. Note that Supervisor is functioning correctly, as the cronjob itself runs on schedule (logs confirm this), but it’s only an environment variable issue within the cronjob. The Problem The cronjob uses outdated settings—specifically an old DB_HOST that points … -
Updating User Profile Logs Out User in Django and Does Not Save Changes
I am working on a Django app with two apps: user for profile management and blog for posts. When a logged-in user tries to update their profile, they are unexpectedly logged out, and the changes are not saved. But it is working when it is done from the admin page. I've included the relevant views, models, forms, and settings below. I am new to django and this is my first project in the same. views.py from django.shortcuts import render, redirect from .forms import UserRegisterForm, UserUpdateForm, ProfileUpdateForm from django.contrib import messages from django.contrib.auth.decorators import login_required def profile(request): if request.method == 'POST': u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, 'Your profile has been updated!') return redirect('profile') else: u_form = UserUpdateForm(instance=request.user) p_form = ProfileUpdateForm(instance=request.user.profile) context = {'u_form': u_form, 'p_form': p_form} return render(request, 'user/profile.html', context) models.py from django.db import models from django.contrib.auth.models import User from PIL import Image class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .models import Profile class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = Userfields = ['username', 'email', 'password1', 'password2'] … -
How to cache django forms?
I use Redis for caching data. But I display forms with dropdown list (ForeignKey objects). That's why i have 2 more sql requests for Book model (where i have author and genre as ForeignKeys) and OrderItem model (where i have bill and book as ForeignKeys). I wanna cache them too for increasing app's speed. I have this mixin: class ModelFormMixin: def post(self, request, *args, **kwargs): self.object_list = self.get_queryset() form = self.get_form() if form.is_valid(): form.save() queryset_cache_key = f'{self.model.__name__}_queryset' cache.delete(queryset_cache_key) return self.form_valid(form) else: return self.form_invalid(form) And these forms: from typing import Type from django import forms from django.forms import ModelForm from .models import Book, Author, Genre, OrderItem, Bill class DynamicModelForm(ModelForm): class Meta: model = None fields = '__all__' @classmethod def create(cls, _model: Type): class Meta(cls.Meta): model = _model form_class = type(f"{_model.__name__}Form", (cls,), {'Meta': Meta}) return form_class class OrderItemForm(DynamicModelForm.create(OrderItem)): price = forms.DecimalField( max_digits=5, decimal_places=2, label='Ціна', # price required=False, disabled=True ) def clean(self): cleaned_data = super().clean() quantity = cleaned_data.get('quantity') book = cleaned_data.get('book') if book and quantity: cleaned_data['price'] = book.price * quantity else: cleaned_data['price'] = 0 return cleaned_data Here's example of my view: class BookView(ModelContextMixin, ModelFormMixin, ModelSuccessUrlMixin, generic.edit.FormMixin, generic.ListView):x model = Book template_name = 'base/books.html' form_class = DynamicModelForm.create(Book) extra_context = {'add_button_name': 'Додати нову книгу'} # … -
Getting integer value from models.PositiveIntegerField() (Django)
I making my first big project(before i was just learning and making simple tasks) so I have some issues, but thats great! But only when there are answers in web - but now I couldn't find them.. I need to do some math with PositiveIntegerField's value as python integer, but I can't find any ways to do it. Here i have some class(not all code and changed names): class SomeClass(models.Model): par = models.PositiveIntegerField() #Making field thar I will compile below class SomeAnotherClass(models.Model): q = models.PositiveIntegerField() w = models.PositiveIntegerField() e = models.PositiveIntegerField() r = models.PositiveIntegerField() t = models.PositiveIntegerField()# Some things i need all = [q,w,e,r,t] counter = 0 if q!=0: counter+=1 if w!=0: counter+=1 if e!=0: counter+=1 if r!=0: counter+=1 if t!=0: counter+=1 #IDK how to make it more elegant..(helping with that is appreciated) if SomeClass.par*counter<=sum(all_rounds[:counter]):# And here are 2 errors, out of <TypeError: unsupported operand type(s) for *: 'DeferredAttribute' and 'int'> and <TypeError: unsupported operand type(s) for +: 'int' and 'IntegerField'> to_par=f'+{sum(all_rounds[:counter])-SomeClass.par*counter}'#Same here if SomeClass.par*counter>sum(all_rounds[:counter]):#Here to_par=f'-{SomeClass.par*counter-sum(all_rounds[:counter])}'#And here So my only reason of errors is that I can't convert from IntegerField to simple python integer... (I tried some ways my self and from web, but now I'm here) Here are 2 … -
requests on django api by javascript with CORS error
I have a web application for many years that uses Django and Django Rest Framework. The API is used by a python application and it works correctly: import requests response = requests.options(http://example.com/api/albums/) 200 {'name': 'Album List List', 'description': '', 'renders': ['application/json', 'text/html'], 'parses': ['application/json', 'application/x-www-form-urlencoded', 'multipart/form-data'], 'actions': {'POST': .... I discovered Svelte and I wanted to work with this API but impossible: let api_ = "http://example.com/api/albums/" const getAlbums = async () => { var response = await fetch(api, { mode: 'cors', method: 'GET', headers: { 'Content-Type': 'application/json'}}); var result = await response.json(); return result.results; Cross-Origin Request Blocked: The “Same Origin” policy does not allow viewing the remote resource located at http://example.com/api/albums/. Reason: The “Access-Control-Allow-Origin” CORS header is missing. Status Code: 200. I read that you need to install django-cors-headers. but now I have this error: Exception in thread django-main-thread: Traceback (most recent call last): File "/home/vianney/Documents/.blog/lib/python3.10/site-packages/django/template/utils.py", line 69, in __getitem__ return self._engines[alias] KeyError: 'django' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/vianney/Documents/.blog/lib/python3.10/site-packages/django/template/backends/django.py", line 174, in get_package_libraries module = import_module(entry[1]) File "/usr/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in … -
Django: Mailgun is stripping out a tags in my email
I have this email template <p>If you have any questions or would like feedback on your profile, please do not hesitate to contact us. To make the changes, you can go <a href="https://languageloom.academy/teacher/edit-profile/">here</a> to view and manage your account.</p> but when I send the email like this @shared_task def send_email_task( subject: str, message: str, from_email: str, recipient_list: list[str], html_message: str = None, ): """ A Celery task to send an email. :param subject: Subject of the email. :param message: Body of the email (plain text). :param from_email: Sender's email address. :param recipient_list: A list of recipient email addresses. :param html_message: HTML content of the email (optional). :return: True if the email is sent successfully, False otherwise. """ try: msg = EmailMultiAlternatives(subject, message, from_email, recipient_list) # Attach HTML content if provided if html_message: msg.attach_alternative(html_message, "text/html") msg.send() return True except smtplib.SMTPException as e: logger.error(f"Email sending failed: {e}") return False it sends the email successfully but the a tag has its href stripped out In my mailgun settings I dont have any tracking enabled. -
Django Migration file not being created despite showing its name and changes
It started seemingly out of nowhere, I'm unable to trace the origins of this issue but yesterday I made migrations just fine and I'm the only working on the project as of now, when I run python manage.py makemigrations it shows: Migrations for 'app_name': app_name/migrations/0XXX_Do_stuff.py - Add field - Remove field - Alter field - Create model - Add field x to model` When running migrations this shows up: Operations to perform: Apply all migrations: things, things Running migrations: No migrations to apply. Your models in app(s): 'app_name', 'app_name_too' have changes that are not yet reflected in a migration, and so won't be applied. Run 'manage.py makemigrations' to make new migrations, and then re-run 'manage.py migrate' to apply them. I can provide any code needed but I honestly don't even know where to start, Any help would be appreciated. I use MySQL. -
Django model filter for string
I have table which has string such as id | url 1 | /myapi/1241/ 2 | /myapi/ 3 | /myapi/1423/ 4 | /myapi/ Now I want to filter them like this below myModel.Objects.filter(url="/myapi/****/") Is it possible , or is there any method to do this? -
How to change the color of a shapefile layer in Django Admin's Leaflet map based on a field's value?
I'm working on a GeoDjango project where I'm displaying a shapefile layer in a Leaflet map embedded in the Django Admin interface. I need to dynamically color the geometry (geom field) in the map based on the value of another field in the model called mean_ctrl. Django Admin with Geom Field Here’s the color scheme I want to implement: def get_color(mean_ctrl): if mean_ctrl < 60: return "#38A800" elif 60.1 <= mean_ctrl <= 120: return "#55FF00" elif 120.1 <= mean_ctrl <= 170: return "#FFFF00" elif 170.1 <= mean_ctrl <= 220: return "#FFAA00" elif 220.1 <= mean_ctrl <= 270: return "#FF0000" else: return "#C500FF" I am looking for guidance on how to apply this color scheme to the Geom field on the Leaflet map in Django admin. Any guidance would be very helpful! Thank you. -
How to get all fields with choices in a Django model?
I have a Django model with dozen fields with Choice options and I want to serialize their values to write an CSV file. How can I traverse the fields to find the ones with Choices options? Something like that: for field in MyModel._meta.fields: if field.has_choices_on_it(): print(f.name) -
Optimize request to db Django
which way is better? and why? queryset = Tariff.objects.filter(user=user).order_by('-created_at').first() or queryset = Tariff.objects.filter(user=user).order_by('created_at').last() You need to get the newest record from the database, which way is better and faster? -
I am unable to add my django project to a github repository due to a loop of errors
I am trying to connect my Django project to a Git repository but whenever I try to stage, commit, then push I get an error when I push about how "The branch "main" has no remote branch. Would you like to publish this branch?" I click okay then it says "Can't push refs to remote, Try running "Pull" first to integrate your changes." but when I pull I get the following error "Git: There is no tracking information for the current branch" so I am completely lost and I am unsure as to what else to provide for this problem to be fixed since this is also my first time doing a solo coding project. I have tried looking up what to do but whenever I do its nothing that helps with the current situation because its a whole loop of me not knowing what the cause is and where to start looking. -
Deploying Django REST API backend on AZURE
I have tried to solve how to deploy Django project on Azure, been following many tutorials but in this point i cant point whats the issue. Deploying from GitHub, deployment have been success whew times but i cant to access to my application, i get mostly 404 or application error when run trough browser. I have postgre locally migrated but i want to use Azure postgre DB. Been pandering with ENV variables, i cant to connect to SHH to apply migrations, CONN CLOSE..etc So i have no idea where to start now actually? I have tried Microsoft guides, guides from internet, asking help from ChatGPT. I want to deploy my Django app on Azure but have no idea now , 'how to' . -
How to create a dropdown Django admin filter with select2?
I am working on a Django admin customization where I need to create dropdown filters with select2. I am using the django-admin-autocomplete-filter package, which works fine for foreign keys but it seems regular fields are not supported. For example, my Collection model has an IntegerField (months). I added list_filter = [AutocompleteFactory(‘Months’, ‘months’] inside the CollectionAdmin and I get this error: DeferredAttribute object had now attributed ‘get_queryset’ -
How can i resolve this issue on REnder
ERROR: Ignored the following versions that require a different python version: 1.21.2 Requires-Python >=3.7,<3.11; 1.21.3 Requires-Python >=3.7,<3.11; 1.21.4 Requires-Python >=3.7,<3.11; 1.21.5 Requires-Python >=3.7,<3.11; 1.21.6 Requires-Python >=3.7,<3.11 ERROR: Could not find a version that satisfies the requirement pkg_resources==0.0.0 (from versions: none) ERROR: No matching distribution found for pkg_resources==0.0.0 What I've Tried: Upgrading pip with pip install --upgrade pip. Upgrading setuptools with pip install --upgrade setuptools. Attempted to create a virtual environment. Any advice on how to resolve these errors would be greatly appreciated! -
Anotation after filter (freeze queryset) Django
In the process of model annotation there is a need to filter the finished list. But the value of the annotation "rank" after the filter() becomes "1" because it has only one element. Without filtering the queryset everything works fine request_user = ( MainUser.objects.select_related("balance_account") .annotate(coin_balance=F("balance_account__coin_balance")) .annotate(rank=Window(expression=RowNumber(), order_by="-coin_balance")) .filter(id=data.get("user_id")) .first() ) Is there a way to avoid the race or freeze the filtered queryset? -
nh3 and mark_safe usage in django markdown
I am using the nh3 library with my Django project to sanitize my HTML of my rendered markdown. I also have fenced code blocks and code block highlighting implemented. If I do not use mark_safe on my nh3 cleaned markdown, all my rich text markdown becomes html code. If I use mark_safe in my Post model after cleaning the markdown, it no longer appears as html code. This is what I have in my Post model's get_message_as_markdown function responsible for generating markdown: from markdown import markdown import nh3 def get_message_as_markdown(self): clean_content = nh3.clean(self.message) rendered_content = markdown(clean_content, extensions=['fenced_code', 'codehilite']) return mark_safe(rendered_content) Is this "safe" to do? Thanks in advance! -
How can I dynamically instantiate multiple apps through django plotly dash?
I am using https://django-plotly-dash.readthedocs.io/en/latest/index.html to build a dash app. I want to dynamically create a new app when the symbol is different. I think this will create a new entry in django_plotly_dash_statelessapp table. How can I achieve this? Example: @app.callback( Output("example-graph", "figure"), [Input("input-element-id", "value")] ) def update_figure(input_value, session_state=None, **kwargs): symbol = session_state["symbol"] # Each unique symbol creates a different app instance new_figure = { "data": [ {"x": [1, 2, 3], "y": [input_value, input_value + 1, input_value + 2], "type": "bar"} ], "layout": {"title": f"Updated Chart for {symbol}"} } return new_figure Call in my view: class SomeDetailView(DetailView): model = SomeModel context_object_name = "detail" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) # Access the current session and add `symbol` to it session = self.request.session django_plotly_dash_objs = session.get("django_plotly_dash", {}) django_plotly_dash_objs["symbol"] = context["detail"].symbol session["django_plotly_dash"] = django_plotly_dash_objs return context -
Django background task not runnng
I am trying to send an email with a django background task. But the problem is that when I run python manage.py process_tasks nothing happens. I am just stuck in part where it looks like it is running but nothing is returned to the terminal logger = logging.getLogger(__name__) @background(schedule=1) def notify_user(): logger.info("Task started") smtp_server = "smtp.gmail.com" port = 465 sender = "email" password = "password" context = ssl.create_default_context() with smtplib.SMTP_SSL(smtp_server, port, context=context) as server: server.login(sender,password) print("Yes") user = get_user_model() I have tried changing the intervals in between runs to 60(seconds) but it wasn't working so I changed it to 1(second) to see if it would work. But alas it doesnt -
Different behaviour when redirecting on local vs production Astro + Django + Nginx
I have deployed an webapp using Astro, Django and Nginx. I am testing the integration with Stripe using Stripe Checkout. So I set up a html form: <form method="post" action=`${baseDomain}users/signup`> ... </form> where baseDomain = http://localhost:8000/api/ if in dev mode and baseDomain = https://example.com/api/ in production. The /users/signup endpoint is handled by a view that ends up calling a function for the redirection to stripe similar to the example in Stripe Checkout. When testing it in my local environment it works great, I am able to access the test checkout form, pay for the product and I am redirected to my custom success page. Here's a screenshot of the Network tab in my browser DevTools: However in production I get the following error: Even though the status is OK for the Stripe Checkout page the browser issues a GET request back to form endpoint, resulting of course in a method not allowed error. What I can notice is that the type of request has changed from document to fetch and the initiator chain is not exactly the same. This is the initiator chain in my local environment This is the initiator chain in prod: I've tried redirecting to just "https://google.com" … -
Django template rendering order... - problem with include and partial and blocks
I've got: ViewChild.html: {% extends 'app1/parent.html' %} {%block title%} my title {%endblock title%} Then I've got Parent.html: {%include 'html_parts/modal_part.html' %} That uses partial view: {%block title%} {%endblock title%} Unfortunately, the view is not rendered correctly ie. 'my title' is not displayed. (it is all ok with application, paths, etc. All files are placed in coorect folders). It is only something with the logic of rendering. Possibly, I can't use in parent view a partial, that defines block, that is going to be filled by child view? Any advices? -
EndpointConnectionError using Localstack with Django
I'm working on setting up Localstack in my Django app so we don't need to connect to S3 for local development. This is the relevant part of my docker-compose: app: build: context: . dockerfile: docker/app.Dockerfile command: > bash -c "poetry run python manage.py runserver_plus 0.0.0.0:8000 --reloader-type watchdog" ports: - 8000:8000 - 5678:5678 volumes: - .:/app - venv:/app/.venv depends_on: - db - celery - elasticsearch - localstack stdin_open: true tty: true networks: - proxynet localstack: container_name: localstack image: localstack/localstack ports: - '4566:4566' volumes: - ./localstack-data:/var/lib/localstack - /var/run/docker.sock:/var/run/docker.sock And I have these settings in my settings.py file: MEDIA_URL = "/media/" MEDIA_ROOT = BASE_DIR("media") DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' AWS_DEFAULT_ACL = "private" AWS_S3_ACCESS_KEY_ID = "local" AWS_S3_SECRET_ACCESS_KEY = "local" AWS_S3_ENDPOINT_URL = "http://localhost:4566" AWS_STORAGE_BUCKET_NAME = "mybucket" But no matter what I try, when I try to upload a file in my application, I get a botocore.exceptions.EndpointConnectionError: Could not connect to the endpoint URL: "http://localhost:4566/mybucket". This only happens when the request to S3 is made through the Django request/response cycle, because I have a few scripts I wrote that are working fine with localstack. For example: #!/bin/bash export AWS_ACCESS_KEY_ID=local export AWS_SECRET_ACCESS_KEY=local export AWS_DEFAULT_REGION=us-east-1 aws s3api create-bucket --bucket "$1" --endpoint-url http://localhost:4566 # Check if the bucket creation was successful … -
How to get the log and result of websocket async_to_sync calling
I have websocket and simply send the mesasges to channel_layer from channels.layers import get_channel_layer channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)( '{}'.format(mychannelname), { "type": "chat_message", "message": "send you" } ) It seems works well and messages goes to client browser, however I want to know if it works well or not from server. Is it possible or can I get the number of clients connected to channel? My consumers.py makes channels import json from channels.db import database_sync_to_async from channels.generic.websocket import AsyncWebsocketConsumer class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_group_name = self.scope["url_route"]["kwargs"]["room_name"] await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() await self.send(text_data=json.dumps({ 'channel_name': self.channel_name })) async def disconnect(self, close_code): print("some disconnect") await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) async def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] print("receive data",text_data_json) print("channel_name:",self.channel_name) print("group_name:",self.room_group_name) if text_data_json['type'] == "register": self.user_id = text_data_json['message'] print("user_id is:",self.user_name) #res = await self.save_message_to_db(message) await self.channel_layer.group_send( self.room_group_name, { 'type': 'chat_message', 'message': "nicelydone", } ) async def chat_message(self, event): print("someone call chat_message") message = event['message'] await self.send(text_data=json.dumps({ 'message': message })) -
When I deployed Django in gunicorn and nginx, the admin login cannot login. But in development mode, it worked fine. Any advice?
When I input the correct admin login, the page just refreshed and came back to the same page. how should i troubleshoot? i have also done collectstatic and update my nginx configuration to the same static directory. Anyone can advise how to troubleshoot or debug? -
Upload multiple file objects to API as 2d array of files
I am trying to build an API using django which support file uploads as an array of array. An example of what I am trying to achieve is, [ { "string": "Some string", "files": [ "<uploaded file object 1>", "<uploaded file object 2>" ] }, { "string": "Some string", "files": [ "<uploaded file object 3>" ] }, { "string": "Some string", "files": [] } ] I dont want to use base64 encoded files for this since the files can be sometimes large, so I dont want to increase the overheads using base64. **how can I achieve this API call in the most efficient way and what would be most appropriate structure to call this API and help with some javascript frontend code do it. ** I tried to move this to a FormData where I can acheive the a above upload like below but I am not able to call the API from the frontend, it doesnt work probably because I am writing wrong code. strings: ["Some string", "Some string", "Some string"] files: [["<uploaded file object 1>", "<uploaded file object 2>"], ["<uploaded file object 3>"]] For my backend I am using django(rest framework), here is the relevant part of the …