Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can i edit external link format converter rule in wagtail cms draftail editor
When someone adds an external link in Wagtail CMS, they should have the option to choose whether to make the link 'nofollow' or 'noreferrer.' To achieve this, I have inherited the existing link form, and the code is provided here class CustomExternalLinkChooserForm(ExternalLinkChooserForm): rel = forms.ChoiceField( choices=[ ("noreferrer", "Noreferrer"), ("nofollow", "Nofollow"), ], required=False, label=_("Rel Attribute"), ) i have also inherited view class CustomExternalLinkView(ExternalLinkView): form_class = CustomExternalLinkChooserForm i registered this in wagtail hooks so admin take this override core view @hooks.register("register_admin_urls") def register_custom_external_link_view(): return [ path( "admin/choose-external-link/", CustomExternalLinkView.as_view(), name="wagtailadmin_choose_page_external_link", ) ] By using the above, it gives me an output like this, but the main issue is that when the Draftail rich text editor saves the link in the database, it does not add the rel attribute in href url. How can I solve this issue? -
Issue with Loading Static Files and Images from Amazon S3 in Django
# Amazon S3 Configuration AWS_ACCESS_KEY_ID = "<your-access-key-id>" AWS_SECRET_ACCESS_KEY = "<your-secret-access-key>" AWS_STORAGE_BUCKET_NAME = "<your-bucket-name>" AWS_S3_REGION_NAME = "us-east-2" AWS_S3_CUSTOM_DOMAIN = f"https://{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com" AWS_S3_OBJECT_PARAMETERS = {"CacheControl": "max-age=86400"} AWS_S3_QUERYSTRING_AUTH = False # STORAGES Configuration STORAGES = { "default": { "BACKEND": "storages.backends.s3boto3.S3Boto3Storage", "OPTIONS": { "location": "media", # Directory for media files "file_overwrite": False, # Prevent overwriting files }, }, "staticfiles": { "BACKEND": "storages.backends.s3boto3.S3StaticStorage", "OPTIONS": { "location": "static", # Directory for static files }, }, } # Configuration during development STATIC_URL = "/static/" # URL for static files STATICFILES_DIRS = [BASE_DIR / "config" / "static"] # Directories for static files STATIC_ROOT = BASE_DIR / "staticfiles" # Root directory for collected static files MEDIA_URL = "/media/" # URL for media files MEDIA_ROOT = os.path.join(BASE_DIR, "media") # Root directory for media files # S3 Configuration for production if not DEBUG: STATIC_URL = f"{AWS_S3_CUSTOM_DOMAIN}/static/" MEDIA_URL = f"{AWS_S3_CUSTOM_DOMAIN}/media/" The documentation used was from https://django-storages.readthedocs.io/en/latest/backends/amazon-S3.html. I am using Django version 5.1.4. Although the static files (CSS, JS, assets) are being collected correctly, when accessing the application, the layout is broken, with no styles applied or images loaded from the static/assets folder. Could anyone help me resolve this issue and ensure that the static files are loaded correctly in the production environment? The … -
Update datetime field in bulk save json object Python Django
i am very bad in django fw. I make simple django resp api. I want to save multiple json object to db. If one of objects is already exist in db(has the same uniq fields) i need just to update filed with datetime. My Model Like: class CheckPort(models.Model): created = models.DateTimeField(auto_now_add=True) ip = models.CharField(max_length=15, blank= False) port = models.PositiveIntegerField(default=0) type = models.CharField(max_length=5 ,default='tcp') class Meta: ordering = ['created'] unique_together = ('ip', 'port','type') My view: @api_view(['GET', 'POST']) def port_list(request): if request.method == 'GET': offers = CheckPort.objects.all() serializer = OfferSerializer(offers, many=True) return Response(serializer.data) elif request.method == 'POST': serializer = OfferSerializer(data=request.data,many=isinstance(request.data, list)) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) So how to validate this? -
Problema no Carregamento de Arquivos Estáticos e Imagens com Amazon S3 em Django [closed]
# Configuração do Amazon S3 AWS_ACCESS_KEY_ID = "<your-access-key-id>" AWS_SECRET_ACCESS_KEY = "<your-secret-access-key>" AWS_STORAGE_BUCKET_NAME = "<your-bucket-name>" AWS_S3_REGION_NAME = "us-east-2" AWS_S3_CUSTOM_DOMAIN = f"https://{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com" AWS_S3_OBJECT_PARAMETERS = {"CacheControl": "max-age=86400"} AWS_S3_QUERYSTRING_AUTH = False # Configuração de STORAGES STORAGES = { "default": { "BACKEND": "storages.backends.s3boto3.S3Boto3Storage", "OPTIONS": { "location": "media", "file_overwrite": False, }, }, "staticfiles": { "BACKEND": "storages.backends.s3boto3.S3StaticStorage", "OPTIONS": { "location": "static", }, }, } # Configuração durante o desenvolvimento STATIC_URL = "/static/" STATICFILES_DIRS = [BASE_DIR / "config" / "static"] STATIC_ROOT = BASE_DIR / "staticfiles" MEDIA_URL = "/media/" MEDIA_ROOT = os.path.join(BASE_DIR, "media") # Configuração S3 para produção if not DEBUG: STATIC_URL = f"{AWS_S3_CUSTOM_DOMAIN}/static/" MEDIA_URL = f"{AWS_S3_CUSTOM_DOMAIN}/media/" A documentação utilizada foi a do https://django-storages.readthedocs.io/en/latest/backends/amazon-S3.html Embora os arquivos estáticos (CSS, JS, assets) sejam coletados corretamente, ao acessar a aplicação, o layout está quebrado, sem a aplicação dos estilos ou o carregamento das imagens da pasta static/assets. Alguém poderia me ajudar a resolver esse problema e garantir que os arquivos estáticos sejam carregados corretamente no ambiente de produção? -
Django Datetime TypeError: fromisoformat: argument must be str
I am having this error while using django. I try to get the date that one transaction happened but i get this error: File "/usr/local/lib/python3.11/site-packages/django/utils/dateparse.py", line 114, in parse_datetime return datetime.datetime.fromisoformat(value) TypeError: fromisoformat: argument must be str code error code snippet ` next_due_date = models.DateField(blank=True, null=True) # The next date when this transaction will be added transaction_date = models.DateTimeField(default=timezone.now) def __str__(self): # Check if transaction_date is set and valid before formatting if self.transaction_date: return f"{self.transaction_type} of {self.amount} on {self.transaction_date}" else: return f"{self.transaction_type} of {self.amount}"` Here is also my already made transactions.: [{"id":1,"user":1,"transaction_type":"expense","amount":"33.00","description":"Cosmote","category":null,"recurrence":null,"next_due_date":null,"transaction_date":"2025-03-26T14:03:02.430961Z"},{"id":2,"user":1,"transaction_type":"income","amount":"1000.00","description":".","category":"Salary","recurrence":"monthly","next_due_date":"2025-03-03","transaction_date":"2025-03-26T14:03:02.430961Z"},{"id":3,"user":1,"transaction_type":"income","amount":"1000.00","description":".","category":"Salary","recurrence":"monthly","next_due_date":"2025-03-03","transaction_date":"2025-03-26T14:03:02.430961Z"},{"id":4,"user":1,"transaction_type":"income","amount":"450.00","description":"Rent","category":"Rent","recurrence":"biweekly","next_due_date":"2025-03-01","transaction_date":"2025-03-26T14:03:02.430961Z"}] i can't understand the reason why is this happening i tried using directly timezone.now(): transaction_date = timezone.now() instead of transaction_date = models.DateTimeField(default=timezone.now) but it got the same error, also tries using if else statement to check in the str function but nothing last i tried using this format in str return f"{self.transaction_type} of {self.amount} on {self.transaction_date}" return f"{self.transaction_type} of {self.amount} on {self.transaction_date.strftime('%B %d, %Y')}" any idea why may this is happening? -
Labels in the form is not showing
This is my model.py file code: class Review(models.Model): VOTE_TYPE = ( ('up','Up Vote'), ('down','Down Vote'), ) owner = models.ForeignKey(Profile, on_delete=models.CASCADE, null = True) project = models.ForeignKey(Project, on_delete=models.CASCADE) # when the model is deleted, all the reviews should also be deleted. body = models.TextField(null = True, blank=True) value = models.CharField(max_length=200, choices = VOTE_TYPE) created = models.DateTimeField(auto_now_add=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) This is my forms.py code: class ReviewForm(ModelForm): class Meta: model = Review fields = ['value', 'body'] labels = { 'value': 'Place your vote', 'body': 'Add a comment with your code' } def __init__(self,*args,**kwargs): super(ReviewForm, self).__init__(*args, **kwargs) for name,field in self.fields.items(): field.widget.attrs.update({'class':'input'}) This my html file code <form class="form" action="{% url 'project' project.id %}" method="POST"> {% for field in form %} <!-- 'form' IS THE WORLD WE PUT IN CONTEXT DICT IN PROJECTS VIEW. --> <div class="form__field"> <label for="formInput#textarea">{{ field.label }}</label> {{ field }} </div> {% endfor %} <input class="btn btn--sub btn--lg" type="submit" value="Add Review" /> </form> The label's CSS is here: .comments { margin-top: 4rem; padding-top: 3rem; border-top: 2px solid var(--color-light); } .comments .form label { position: absolute; margin: -9999px; } .commentList { margin: 3rem 0; } .comment { display: flex; gap: 2rem; } the problem is that Labels … -
Tailwind CSS does not generate CSS for all classes
I'm new to Tailwind CSS and I'm looking to include it in my Django/FastAPI project. I'm using Tailwind version 4.0.17. The problem I'm having is that Tailwind doesn't recognize the HTML tags I have in my template files... I run the following command : npx tailwindcss -i ./static/css/input.css -o ./static/css/output.css This generates a CSS file for me, but it doesn't have all the classes in it... On the other hand, when I test with this command : npx tailwindcss --content ./templates/test_endpoint.html --dry-run > output.css This time, all the CSS classes of the HTML template are present in the output file, but not the others (those of the other HTML templates). Here is the code for the tailwind.config.js file: /** @type {import('tailwindcss').Config} */ module.exports = { content: [ "./templates/**/*.html", "./templates/*.html", "templates/main/index.html", "templates/base.html", "./**/templates/**/*.html", "./static/**/*.css", "./fastapi_app/**/*.html", "./main/**/*.html" ], theme: { extend: {}, }, plugins: [], } I've tried reinstalling Tailwind several times, changing the paths, trying other commands, and the result is always the same. If you have any ideas on how to solve this problem, that would be great! Thanks -
Most efficient way to write a "Many to Occasional" field in Django
So I read that ManytoMany fields in Django were slower than ForeignKey lookups (as they make use of a helper table). I am creating an application that allows performers to catalog their acts. Each act they have in their catalog can have multiple images. However, I also want to specify one "Hero Image" of the Act which will be used for preview when they search through their catalog. each act can have many images, but only one of those could be a header image. I came up with three options but I want to hear what the hive has to think. ManytoManyField from django.db import models from django.contrib.auth.models import User # Create your models here. class Act(models.Model): title = models.CharField(max_length=200) user = models.ForeignKey(User, on_delete=models.CASCADE) description = models.TextField() hero_image = models.ForeignKey('Image', on_delete=models.SET_NULL, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Image(models.Model): act = models.ManyToManyField(Act) image = models.ImageField(upload_to='images/') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) Two Foreign Keys from django.db import models from django.contrib.auth.models import User # Create your models here. class Act(models.Model): title = models.CharField(max_length=200) user = models.ForeignKey(User, on_delete=models.CASCADE) description = models.TextField() hero_image = models.ForeignKey('Image', on_delete=models.SET_NULL, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Image(models.Model): act = models.ForeignKey(Act, on_delete=models.CASCADE) image = models.ImageField(upload_to='images/') … -
not able to connect to postgresql server
So I'm having trouble connecting my postgresql db server. I'm relatively new to Ubuntu, this is a brand new computer. My db name, username and password are all correct as per my Django settings. I hope I don't have to edit my pg_hba.conf file. I had similar issues regarding this with Fedora, but I didn't think I would have this problem with Ubuntu. I did in fact create a new database via the linux terminal. I'm also in my virtual environment. I even tried opening the psql shell and got more warnings. Here is the complete trackeback error after running python manage.py makemigrations and psql. FYI the name for my Ubuntu system is corey-james show_sunset_warning() /home/corey-james/Arborhub/arborhubenv/lib/python3.12/site-packages/django/core/management/commands/makemigrations.py:160: RuntimeWarning: Got an error checking a consistent migration history performed for database connection 'default': connection to server at "localhost" (127.0.0.1), port 5432 failed: FATAL: password authentication failed for user "cortec" connection to server at "localhost" (127.0.0.1), port 5432 failed: FATAL: password authentication failed for user "cortec" warnings.warn( No changes detected (arborhubenv) corey-james@corey-james-HP-Laptop-14-dq0xxx:~/Arborhub/MyProject$ psql psql: error: connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed: FATAL: role "corey-james" does not exist (arborhubenv) corey-james@corey-james-HP-Laptop-14-dq0xxx:~/Arborhub/MyProject$ -
Django + HTMX: how to have a CreateView that looks up information via HTMX and updates the form dynamically?
I'm a python and Django newbie. Also a newbie in StackOverflow... I'm trying to build a CreateView with a form that contains a button to lookup information via a GET request using HTMX. A user would encounter the form completely blank at first. Once they input a specific field (in this case a serial number), they can click the button that initiates the lookup/GET request. After the information is retrieved via the GET, I would like to update specific fields in the form with some of the information from the GET (essentially like an auto-complete). So far I have been able to build the initial CreateView (which is straightforward) and have been able to setup the button that does the HTMX GET request; I have also been able to retrieve the information needed but where I'm stuck is on being able to update/inject the values retrieved into specific fields from the form after the GET request. What are the steps I should take to handle that specific part? I have tried adding the form into the view that manages the HTMX get request and assigning some of the "initial" values, later having the form with the values defined as "initial" … -
How to propagate error on create method in DRF serializer?
I'm trying to raise some error based on some business logic as in below class ConsultationViewset(BaseModelViewset, ListModelViewsetMixin, RetrieveModelViewsetMixin, CreateModelViewsetMixin, UpdateModelViewsetMixin): serializer_class = ConsultationSerializer .... class ConsultationSerializer(serializers.ModelSerializer): def create(self, validated_data): consultation = ConsultationService.create_consultation(validated_data.pop('customer', None), validated_data) return consultation def create_consultation(customer: CustomerFactory.Models.CUSTOMER, validated_data): if ticket is None: raise exceptions.PermissionDenied("No active ticket found for this customer, request is forbidden") My aim is to send the raised message in create_consultation in the response. Yet I keep getting AssertionError: create() did not return an object instance.instead. I could send a custom message if I re-raise the error in the viewset like below, but it felt wrong as the error is AssertionError. class ConsultationViewset(...): def perform_create(self, serializer): try: serializer.save() except AssertionError as e: raise exceptions.PermissionDenied('custom message') How to properly raise a PermissionDenied error? -
How to send CSRF token using Django API and a Flutter-web frontend ? HeaderDisallowedByPreflightResponse
I have a python/django web API with a single endpoint, let's call it /api/v1/form. That API is called from a Flutter-web frontend application. I currently use the following configuration that disables CSRF token verification, and it works : requirements.txt Django==5.1.7 django-cors-headers==4.7.0 webserver/settings.py ... ALLOWED_HOSTS = ["localhost"] CORS_ALLOWED_ORIGINS = ["http://localhost:8001"] # flutter dev port INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', 'webserver', ] ... MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ... webserver/urls.py from django.urls import path import webserver.views urlpatterns = [ path('api/v1/form', webserver.views.api_v1_form, name="api_v1_form"), ] ... webserver/views.py from django.http import HttpResponse, HttpResponseBadRequest def api_v1_form(request): if request.method == "POST": process_request(request.body) return HttpResponse("request successfully processed.") return HttpResponseBadRequest("Expected a POST request") flutter/lib/page_form.dart Future<int> sendForm(MyData data) async { final response = await http.post( Uri.parse("http://localhost:8000/api/v1/form"), body: data.toString(), ); return response.statusCode; } Here is what I don't understand : if I disable to the CORS package in order to simply use a vanilla Django server, then I find myself capable of sending requests to the API but unable to receive an answer. Why is that the case ? The following is the configuration used to get the CSRF token and use it in the requests. settings.py ALLOWED_HOSTS = ["localhost"] … -
Django with chartjs > 2.9.3
I'm using version Django==5.0.6 and attempting in integrate charts using chartjs and plugin datalabels. When I use the charts render without issue, but I'm not able to see any datalabels. If I try to add Chart.register(ChartDataLabels); the graph no longer renders. I've also tried Chart.plugins.register(ChartDataLabels); I'd like to be able to use the most updated version of chartjs but when I change the chart version to anything other than 2.9.3, the graphs don't render. base.html <!DOCTYPE html> <html> {% load static %} {% load django_bootstrap5 %} {% bootstrap_css %} {% bootstrap_javascript %} <head> <title>{{ template_data.title }}</title> <link rel= "stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css"> <link href= "https://fonts.googleapis.com/ css2?family=Poppins:wght@300;400;500;600;700&display= swap" rel="stylesheet"> <link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}"> <meta name="viewport" content="width=device-width, initial-scale=1" /> <script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.3"></script> <script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@2.0.0-rc"></script> </head> ... data.html {% extends "base.html" %} {% load django_tables2 %} {% block head %} <p><h3>Job data</h3>{{year}}</p> {% endblock head %} {% block content %} <canvas id="chart" style="position: relative; height:100vh; width:100vw"></canvas> <script> let ctx = document.getElementById("chart").getContext('2d'); /* Chart.register(ChartDataLabels); Chart.plugins.register(ChartDataLabels); */ let chart = new Chart(ctx, { type: "horizontalBar", data: { labels: [{% for data in labels %} '{{data}}', {% endfor %}], datasets: [ { label: "Job Week 13", backgroundColor: "#2d9f42", borderColor: "#030202", data: [{% for data in week13_count … -
Which is better: using Django Constraints or raising a ValueError in the save method?
I’ve come across two ways to enforce a condition in Django models: Using the save method with a ValueError: class MyModel(models.Model): field_name = models.CharField(max_length=100) def save(self, *args, **kwargs): if not self.field_name: # Example condition raise ValueError("Field name cannot be empty.") super().save(*args, **kwargs) Using Django's Constraints (like CheckConstraint): from django.db import models from django.db.models import Q class MyModel(models.Model): field_name = models.CharField(max_length=100) class Meta: constraints = [ models.CheckConstraint( check=~Q(field_name=""), # Example condition name="field_name_not_empty", ) ] I know both approaches can enforce conditions, but I’m wondering: Which approach is more efficient? Which one is generally better to use in real-world scenarios? -
Calling a Django Management Command from a Celery Task and Redirecting Logs
I'm trying to call a Management Command with call_command within a Celery task. The management command writes logs in different ways: through print statements, self.stdout.write, or using the logger defined at the script's module level. I want to capture all these log messages in the Celery logger to make them visible in Datadog. Is this possible? I tried the worker_redirect_stdouts_level option, but it impacts the global Celery logging configuration. -
Django formset with nested single inline form of each formset object(form)
I'm trying to figure out the logic of building such structure: class Order(models.Model): id = ... class OrderItem(models.Model): order = FK(Order) quantity = CharField() category = CharField(choices=..) class OrderItemSchema(models.Model): class Meta: abstract = True order_item = OneToOneField(OrderItem) brand = CharField() model = CharField() class SomeProduct1Schema(OrderItemSchema): size = PositivieIntegerField() class SomeProduct2Schema(OrderItemSchema): weight = CharField() type = CharField() Let's assume some customer has created new Order which "Company" has to produce. There are different types of products (not much: 2-10) which may not have even single common parameter/field but still be placed withing one Order. The question is: How to manage FormSet (or there is another way?) of OrderItem elements where each element may has different fields? Example: OrderItem: [SomeProduct1Schema] \ category \ quantity \ brand \ model \ size OrderItem: [SomeProduct2Schema] \ category \ quantity \ brand \ model \ weight \ type So far I've added OrderItem inline formset to Order and both SomeProduct1Schema \ SomeProduct2Schema inline formsets attached to OrderItemFormSet as nested form. But it's works well with single nested formset class and becoming mess when need to handle multiple dynamically. Now I'm thinking to make SomeProduct1Schema classes to inherit from OrderItem directly using multi-table inheritance. Performance is not … -
Django decorator import issue: 'cannot import name' when used in views.py
when trying to start the server it cannot find the decorator from django.contrib.auth.decorators import login_required, user_passes_test, staff_member_required ... @staff_member_required def delete_service_view(request, service_id): service = get_object_or_404(Service, pk=service_id) service.delete() return redirect('index') @staff_member_required def toggle_trusted_from_service_view(request, user_id): if request.method == 'POST': try: user = User.objects.get(pk=user_id) user.isTrusted = not user.isTrusted user.save() return redirect('service_detail', service_id=request.POST.get('service_id')) except User.DoesNotExist: return HttpResponseForbidden("User not found.") else: return HttpResponseForbidden("Invalid enquiry method.") When i try python manage.py runserver File "C:\Users\alexe\djangoshop\dshop\main\views.py", line 3, in <module> from django.contrib.auth.decorators import login_required, user_passes_test, staff_member_required ImportError: cannot import name 'staff_member_required' from 'django.contrib.auth.decorators' (C:\Users\alexe\djangoshop\dshop\dshop_new_env\Lib\site-packages\django\contrib\auth\decorators.py) I've already recreated the environment and reinstalled all dependencies -
Apps aren't loaded yet
I'm using Visual Studio 2022 as the IDE. It has 2 projects: CLI - A Python Application Common - A Blank Django Project The classes are created in Common > app > models.py. app is a Django app CLI is the startup project, and cli.py is its startup file. Common project is referenced in CLI. When I Start the CLI app in debug mode, there is an error for the Question class. -
Django-Simple-History: Avoid Redundant History Records & Track Generic Relations
We are using django-simple-history to track changes in our models, including many-to-many (m2m) relationships and generic relationships. Model: class BandProfile(BaseModel): class Meta: db_table = "band_profiles" name = models.CharField(max_length=255) types = models.ManyToManyField( Choices, related_name="types", limit_choices_to={"category": "type"}, blank=True, ) description = models.TextField(null=True, blank=True) history = HistoricalRecords( table_name="history_band_profiles", history_user_setter=set_historical_user_from_request, history_user_getter=get_historical_user_from_request, history_user_id_field=models.CharField(max_length=36, null=True), m2m_fields=[types], # Many-to-many tracking ) def __str__(self): return f"Band Profile for {self.name}" Serializer: def create(self, validated_data): """ Create method for BandProfile with handling for related fields. """ types = validated_data.pop("type_ids", []) band_profile = BandProfile.objects.create(**validated_data) band_profile.types.set(types) Issues: When creating or updating resources, django-simple-history is generating multiple redundant history entries, which results in incorrect historical tracking. Below shows the redundant records. See the redundant records Expected Response Format: We need a structured response that includes the historical records of the resource, its many-to-many relations, and generic relations, like this (Field names are examples): [ { "id": 101, "name": "Resource A", "history_date": "2025-03-20T10:00:00Z", "change_type": "update", "types": [ { "id": 201, "name": "Sector X", "history_date": "2025-03-19T15:00:00Z", "change_type": "create" }, { "id": 202, "name": "Sector Y", "history_date": "2025-03-20T16:00:00Z", "change_type": "update" } ], "generic_relation": [ { "id": 301, "type": "Document", "title": "Policy Document A", "history_date": "2025-03-18T11:00:00Z", "change_type": "create" }, { "id": 302, "type": "Document", "title": "Policy Document … -
Django + python --> problem with polish characters like "ą" "ę" "ł"
Ciao! I am a beginner in Django & Python. I want to create a simple blog. I followed a step-by-step tutorial from this video → [YouTube link]https://www.youtube.com/watch?v=2MkULPXXXLk&t=865s and I have issue. When I create a category with Polish characters like "ą", "ę", it works. However, when I try to assign a post to this category, it doesn’t work. I spent some time trying to fix it but had no success. If I understand correctly, Python compares the category name "Łódź" with "Łódź" after URL transformation or something like that. For example: Łódź == odz → False Because of this, I can't see posts in the "Łódź" category. Here is my GitHub repo: [GitHub link] https://github.com/marekpno/problem MD -
Specifying get methods for nested serializers
In the case of nested serializers, is there a way to specify a method that will get the data? class AuthorSerializer(ModelSerializer): .... class BookSerializer(ModelSerializer): authors = AuthorSerializer(many=True) .... In this example, I would like to intercept and modify how BookSerializer gets the authors. How do I accomplish this? -
Django error with SSL and Azure Flexible MySQL
I'm doing a MySQL migration to an Azure MySQL Server. Which I don't have the control on the configuration. I managed to connect to it with a simple python script, but faking the TLS flag with pymysql. from azure.identity import ManagedIdentityCredential import pymysql # Get Managed Identity Token credential = ManagedIdentityCredential() token_msi = credential.get_token( "https://ossrdbms-aad.database.windows.net/.default" ).token deploy_env = "dev" application_name = "my_app" # Define connection parameters connection = pymysql.connect( host="xxxxxxxxxxxxxxxxxxxx.mysql.database.azure.com", user=f"{application_name}_{deploy_env}", password=token_msi, db=f"{application_name}_{deploy_env}", ssl={"fake_flag_to_enable_tls": True} ) # Execute a query query = "SHOW DATABASES" with connection.cursor() as cursor: cursor.execute(query) print(cursor.fetchall()) So this works. I managed to dump my old database and import it to the new one using the mysql cli. But now I'm trying to make my Django app connect to it. In my Django settings.py: deploy_env = "dev" application_name = "my_app" DATABASES = { "default": { "ENGINE": "django.db.backends.mysql", "NAME": f"{application_name}_{deploy_env}", "USER": f"{application_name}_{deploy_env}", "PASSWORD": None, # Token will be assigned dynamically "HOST": f"xxxxxxxxxxxxx.mysql.database.azure.com", "PORT": 3306, } } get_db_token() Here is the get_db_token function: import os import django.conf as conf from azure.identity import ManagedIdentityCredential def get_db_token(): azure_credential = ManagedIdentityCredential() token = azure_credential.get_token( "https://ossrdbms-aad.database.windows.net" ).token conf.settings.DATABASES["default"]["PASSWORD"] = token When making a test with python manage.py dbshell I can see all my … -
Using pghistory with custom event table names
I'm currently testing pghistory for our Django project. I set up a few models to be tracked. As a convention our model names are different from the actual table names - these are defined in the Meta class like so: class Delivery(models.Model): created = models.DateTimeField(auto_now_add=True, editable=False) creator = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='deliveries', on_delete=models.PROTECT, editable=False) ... class Meta: db_table = 'ep_delivery' When I decorate the model with @pghistory.track() the resulting event table is called as the model, which is DeliveryEvent in this example. But I would rather have it being named ep_delivery_event to be in accordance with our conventions. How can I achieve this? -
How to use multiple database connections in Django TestCase
I'm writing a testcase to reproduce deadlock in my service. After I use multiprocessing to create a two thread, I found they use the same database connection. So I can't reproduce the deadlock scenario in testcase. How do i resolve this issue? My code is as belows: @transaction.atomic() def process_1(): change = Change.objects.select_for_update().get(id="1") time.sleep(5) change = Change.objects.select_for_update().get(id="2") @transaction.atomic() def process_2(): change = Change.objects.select_for_update().get(id="2") time.sleep(5) change = Change.objects.select_for_update().get(id="1") p1 = Process(target=process_1) p2 = Process(target=process_2) p1.start() p2.start() p1.join() p2.join() self.assertEqual(p1.exitcode, 0) self.assertEqual(p2.exitcode, 0) -
Unable to Import 'celery' When Running pylint, but Django Runs Fine
I am working on a Django project and using uv as the package manager. My dependencies are managed in pyproject.toml, and I have the following setup: pyproject.toml (Relevant Parts) [project] name = "port-backend" version = "0.1.0" description = "Backend service for port.az" readme = "README.md" requires-python = ">=3.12" dependencies = [ "celery>=5.4.0", "django==4.2", "djangorestframework>=3.15.2", "djangorestframework-simplejwt>=5.5.0", "drf-spectacular>=0.28.0", ] [dependency-groups] dev = [ "pylint>=2.0.0", ] [tool.pylint.MASTER] ignore-paths = ['.venv/'] disable = [ 'C0415', # Import outside toplevel 'E0401', # Import error ] Steps Taken I ran uv sync, which created a new .venv and installed dependencies. VS Code detected the new environment and asked if I wanted to use it. I selected "Yes" and ensured the virtual environment was activated. Running uv run manage.py runserver works without issues, meaning Django and Celery are installed correctly. However, running uv run pylint . gives these errors: ************* Module manage manage.py:12:8: C0415: Import outside toplevel (django.core.management.execute_from_command_line) (import-outside-toplevel) ************* Module config.celery_app config/celery_app.py:3:0: E0401: Unable to import 'celery' (import-error) What I Have Tried Verified that Celery is installed in the .venv by running uv pip list, and celery is present. Checked that the .venv is activated in VS Code (terminal shows (port-backend) ➜ port_backend). Tried running uv …