Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how can I modularize this code to reuse the AJAX in different HTML files without needing to rewrite it each time?
I separated my JavaScript code from the .html file and placed it in a static folder, then imported it. However, after this change, my AJAX stopped working. How can I make my ajax.js reusable across different pages without rewriting it? This was the working code that handled the editing of classes, receiving, and processing files. I should mention that I’m working on a Django project, and this is the first JS file I’m including in the project. The idea of separating it is so that the same AJAX functionality can be used for the adicionar_aula URL. Here is the code: ` Editar Aula Editar Aula {% csrf_token %} {{ form.as_p }} Arquivos já adicionados: {% for arquivo in arquivos_existentes %} {% if arquivo.arquivo %} {{ arquivo.arquivo.name }} {% else %} Arquivo não disponível {% endif %} Excluir {% empty %} Nenhum arquivo adicionado ainda. {% endfor %} Adicionar Arquivo Salvar Alterações $(document).ready(function() { // Enviar novos arquivos via AJAX $('#input-arquivo').on('change', function() { var formData = new FormData(); $.each($(this)[0].files, function(i, file) { formData.append('arquivo', file); }); formData.append('csrfmiddlewaretoken', '{{ csrf_token }}'); $.ajax({ url: '{% url "editar_aula" pk=plano.id %}', // URL para a view de edição type: 'POST', data: formData, processData: false, contentType: false, … -
Remove the mandatory field label 'This field is required.' and fix the bug with 'clean_email'
I use the built-in Django, 'UserCreationForm' to create a registration form, but there are unnecessary instructions 'This field is required.' that these fields are required, I want to remove them, please help, or at least translate into Russian, so that the inscription is in Russian, if you can, also help fix clean_email in forms, so that it does not always throw out this inscription after 1 test entry of an existing email here is a screenshot of the result RegisterUserForm views.py: class RegisterUser(CreateView): form_class = RegisterUserForm template_name = 'users/register.html' extra_context = {'title': 'Регистрация'} get_success_url = reverse_lazy('users:login') forms.py: class RegisterUserForm(UserCreationForm): username = forms.CharField(label="Логин:", widget=forms.TextInput(attrs={'class': "form-input"})) password1 = forms.CharField(label="Пароль:", widget=forms.PasswordInput(attrs={'class': "form-input"})) password2 = forms.CharField(label="Повтор пароля:", widget=forms.PasswordInput(attrs={'class': "form-input"})) class Meta: model = get_user_model() fields = {'username', 'email', 'first_name', 'last_name', 'password1', 'password2'} labels = { 'username': 'Логин:', 'email': 'E-mail:', 'first_name': 'Имя:', 'last_name': 'Фамилия:', 'password1': 'Пароль:', 'password2': 'Повторить пароль:', } widgets = { 'username': forms.TextInput(attrs={'class': "form-input"}), 'first_name': forms.TextInput(attrs={'class': "form-input"}), 'last_name': forms.TextInput(attrs={'class': "form-input"}), } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.order_fields(['username', 'email', 'first_name', 'last_name', 'password1', 'password2']) def clean_email(self): email = self.cleaned_data['email'] if get_user_model().objects.filter(email=email).exists(): raise forms.ValidationError(("E-mail должен быть уникальным!"), code="invalid") return email users/register.html: {% extends 'users/base.html' %} {% block title %}Регистрация{% endblock %} {% block content %} … -
Question about creating a CRUD API for a project
how’s it going? This isn’t a coding question, but if anyone can help, it would be great. I’m new to this and I want to create an API that does a CRUD as a project. I’ve seen it’s recommended to do this, but of course, creating a public API allows anyone to modify the database. My question is: when recommending to create an API as a project, are they referring to a FakeAPI? I mean, should actions like DELETE or PUT only be temporary while the session is active? I’ve been trying to understand this so I can get started on the project. Thanks for your attention. -
Cant show 5 by 5 with paginator of Django
I'm using paginator of Django 5.1, the paginator work well but cant show dat 4 by 4 I want to show data 4 by 4 views.py def tipomaterial(request): tipomaterial = TipoMaterial.objects.all().order_by('nombre') #paginador de 4 en 4 paginator = Paginator(tipomaterial, 4) page_number = request.GET.get('page', 1) pgtm = paginator.get_page(page_number) return render(request, 'tipomaterial.html', { 'tipomaterial': tipomaterial, 'pgtm': pgtm }) tipomaterial.html <main class="container py-5"> <br/><br/> <hr> <span class="step-links"> {% if pgtm.has_previous %} <a href="?page={{ pgtm.previous_page_number }}">Previous</a> {% endif %} <span class="current"> Page {{ pgtm.number }} of {{ pgtm.paginator.num_pages }}. </span> {% if pgtm.has_next %} <a href="?page={{ pgtm.next_page_number }}">Next</a> {% endif %} </span> image enter image description here Help please -
Error Deploying Python Backend to Railway.app: HDF5 Not Found During netCDF4 Installation
I'm normally deploying my Python Backend to Railway.app for easy hosting. Today I pushed som new features, but it did not finish because of an error. First look for me, it looks like there is something wrong with dockerfile. I hope there are somebody that knows how to fix it. #10 26.41 Downloading netCDF4-1.6.3.tar.gz (777 kB) #10 26.42 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 777.5/777.5 kB 480.2 MB/s eta 0:00:00 #10 26.46 Installing build dependencies: started #10 32.07 Installing build dependencies: finished with status 'done' #10 32.07 Getting requirements to build wheel: started #10 32.26 Getting requirements to build wheel: finished with status 'error' #10 32.27 error: subprocess-exited-with-error #10 32.27 #10 32.27 × Getting requirements to build wheel did not run successfully. #10 32.27 │ exit code: 1 #10 32.27 ╰─> [40 lines of output] #10 32.27 reading from setup.cfg... #10 32.27 Package hdf5 was not found in the pkg-config search path. #10 32.27 Perhaps you should add the directory containing `hdf5.pc' #10 32.27 to the PKG_CONFIG_PATH environment variable #10 32.27 No package 'hdf5' found #10 32.27 #10 32.27 HDF5_DIR environment variable not set, checking some standard locations .. #10 32.27 checking /root/include ... #10 32.27 hdf5 headers not found in /root/include #10 32.27 checking … -
Cpanel Django SMTP Problem: Mails Dont Show Up
Im sending mails in my Django project though my mail hosting with SSL settings. Eventhough I cant detect any problems with the SMTP code and mails are seem to sent in the cpanels tracking page, the mails dont show up in the inbox. I tried it for gmail and outlook it didnt work. Settings: EMAIL_HOST = '<server_name>' EMAIL_PORT = 465 EMAIL_HOST_USER = 'info@my_mail.com' EMAIL_HOST_PASSWORD = '********' View class SendMailTest(APIView): def post(self, request): recipient_email = 'recipient@mail.com' msg = MIMEMultipart() msg['From'] = settings.EMAIL_HOST_USER msg['To'] = recipient_email msg['Subject'] = 'SMTP Test Mail' html_content = "<h1>This is a test email</h1><p>Sent via Django.</p>" msg.attach(MIMEText(html_content, 'html')) context = ssl.create_default_context() with smtplib.SMTP_SSL(settings.EMAIL_HOST, settings.EMAIL_PORT, context=context) as server: server.set_debuglevel(1) server.login(settings.EMAIL_HOST_USER, settings.EMAIL_HOST_PASSWORD) server.sendmail(settings.EMAIL_HOST_USER, recipient_email, msg.as_string()) return Response({'status': 'success'}) Debug Log Summary: reply: b'235 Authentication succeeded\r\n' reply: retcode (235); Msg: b'Authentication succeeded' send: 'mail FROM:<info@my_mail.com> size=412\r\n' reply: b'250 OK\r\n' reply: retcode (250); Msg: b'OK' send: 'rcpt TO:<'recipient@mail.com'>\r\n' reply: b'250 Accepted\r\n' reply: retcode (250); Msg: b'Accepted' send: 'data\r\n' reply: b'354 Enter message, ending with "." on a line by itself\r\n' reply: retcode (354); Msg: b'Enter message, ending with "." on a line by itself' data: (354, b'Enter message, ending with "." on a line by itself') send: b'Content-Type: multipart/mixed;.... reply: b'250 OK … -
django json api ordering_fields not working on include resources
Hi I am working on ordering_fields on include resources using django_json_api. I have 2 models activities and activity_enrollments(activity is foreign_key). I am ordering on 2 fields one is related to activity.priority and next is activity_enrollment.is_targeted. is_targeted field order is working fine but activity__priority is not working I have tried multiple columns in activity_enrollment model these are i am able to sort it. but related fields are not working viewset from rest_framework_json_api import filters from rest_framework_json_api import django_filters from rest_framework.filters import SearchFilter from rest_framework import status, viewsets from .models import ActivityEnrollment, Activity from .serializers import ActivityEnrollmentSerializers class EnrollmentsViewSet(viewsets.ModelViewSet): """ A simple ViewSet for viewing and editing accounts. """ queryset = ActivityEnrollment.objects.all() serializer_class = ActivityEnrollmentSerializers filter_backends = (filters.QueryParameterValidationFilter, filters.OrderingFilter, django_filters.DjangoFilterBackend, SearchFilter) ordering_fields = ("activity__priority","is_targeted",) serializers from .models import ActivityEnrollment, Activity from rest_framework_json_api.serializers import ModelSerializer class ActivitySerializers(ModelSerializer): class Meta: model = Activity fields = ( 'id', 'name', 'priority', ) class ActivityEnrollmentSerializers(ModelSerializer): included_serializers = { "activity": ActivitySerializers } class Meta: model = ActivityEnrollment fields = ( "id", "is_targeted", "completed_at", "activity" ) class JSONAPIMeta: included_serializers = ['activity'] api: GET /api/activity-enrollment/?include=activity&sort=-activity__priority response { "links": { "first": "http://127.0.0.1:8908/api/activity-enrollment/?include=activity&page%5Bnumber%5D=1&sort=-activity__priority", "last": "http://127.0.0.1:8908/api/activity-enrollment/?include=activity&page%5Bnumber%5D=1&sort=-activity__priority", "next": null, "prev": null }, "data": [ { "type": "ActivityEnrollment", "id": "3", "attributes": { "is_targeted": false, "completed_at": … -
in static file in django the background_image not work
I tried using a code to change the background color and it worked fine. But when I used the background_image code, the code did not work and gave me (Failed to load resource: the server responded with a status of 404 (Not Found)) Although the path is correct This is the path to the image inside the app D:\Todos\Todosproject\static\images\svitlana-j7Ssk0Km8Jo-unsplash.jpg static/styles body { background-image: url('/Todos/Todosproject/static/images/svitlana-j7Ssk0Km8Jo-unsplash.jpg'); } base.html <!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <link rel="stylesheet" type="text/css" href="{% static 'css/styles.css' %}"/> <title> {% block title %} {% endblock title %} </title> </head> <body> {% block body %} {% endblock body %} </body> </html> settings.py in django STATIC_URL = 'static/' STATICFILES_DIRS = [BASE_DIR / "static"] -
How to save OneToMany in Django Admin
This is my models class Author(models.Model): full_name = models.CharField(max_length=100) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.full_name class Book(models.Model): title = models.CharField(max_length=100) author = models.ForeignKey(Author, on_delete=models.CASCADE, db_column='author_id',related_name='authors',null=True,blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.title My admin setup @admin.register(Author) class AuthorAdmin(admin.ModelAdmin): list_display = ('id', 'full_name', 'created_at', 'updated_at') search_fields = ['full_name'] ordering = ['-created_at'] @admin.register(Book) class BookAdmin(admin.ModelAdmin): list_display = ('id', 'title', 'author', 'created_at', 'updated_at') search_fields = ['title'] list_filter = ['author__full_name'] ordering = ['-created_at'] I want from create Author page. I can select multiple Book with author_id = Null. And when i save it, it will update author_id for all selected Book Please help me -
Resize Tables with css
3v and Django 5.1 for my Forms I created a file css but I don't know how to use it, my CSS is still empty. settings.py enter image description here tipomaterial.html {% extends 'base.html' %} {% block content %} <main class="container py-5"> <table class="table table-bordered"> <thead> <tr> <th style="text-align: center;"> <strong> <h2>Tipo de Material</h2> </strong> </th> <th> <a class="btn btn-success" role="button" href="{% url 'creartipomaterial' %}"> <i class="bi bi-plus-square-fill"> Agregar </i> </a> </th> </tr> <tr style="text-align: center;"> <th scope="col">Nombre del material</th> <th scope="col" colspan="2">Acciones</th> </tr> </thead> <tbody class="table-group-divider"> {% for datos in tipomaterial %} <tr> <td> <li class="list-group-item" href="{% url 'detalle_tipomaterial' datos.id %}"> <strong>{{datos.nombre}}</strong> </li> </td> <td> <a class="btn btn-primary" href="{% url 'detalle_tipomaterial' datos.id %}" role="button"> <i class="bi bi-pencil-fill"> Editar </i> </a> <a class="btn btn-danger" href="{% url 'eliminar_tipomaterial' datos.id %}" role="button"> <i class="bi bi-trash3-fill"> Eliminar </i> </a> </td> </tr> {% endfor%} </tbody> </table> </main> {% endblock %} design enter image description here I wish my table was smaller. Any idea please -
403 Forbidden POST Request when trying to log out using React front end with Axios and Django with rest-framework
I keep getting an 403 Forbidden error when trying to log out of the user account. I am able to log in fine, I see in the cookies that there is a sessionID and a csrf token. However every single time without fail I get a 403 forbidden error when trying to log out. I have withCredentials:true and include the csrf token in the header. I have my middleware in the right order, I have all the correct cors-headers configuration and allowed hosts. When inspecting the network details using F12 I can see that the sessionID cookie is not being sent along with the csrf token. Not sure why? I am at my wits end. Here is my code for the login and logout front end as well as relevant settings.py code and views.py for logout. Axios: import axios from "axios"; axios.defaults.xsrfCookieName = 'csrftoken'; axios.defaults.xsrfHeaderName = 'X-CSRFToken'; const client = axios.create({ baseURL: "http://127.0.0.1:8000", withCredentials: true, }); export default client; Login: function submitLogin(e) { e.preventDefault(); client.post("/api/login/", { username, password }, { withCredentials: true, }) .then(function(res) { if (res.data.redirect_url) { navigate(res.data.redirect_url); } else { console.error("No redirect URL provided."); } }) Logout: function logout(e) { e.preventDefault(); const csrftoken = document.cookie.split('; ').find(row => row.startsWith('csrftoken='))?.split('=')[1]; … -
How to handle prefixed UUIDs in Django Admin for querying and displaying objects?
I am working on a Django project with a custom UUIDField with a prefix (e.g., ft_) to represent IDs. The raw UUID is stored in the database, but I want the prefixed value (e.g., ft_) to be shown in API responses, admin interfaces, and elsewhere. However, this creates issues when querying objects in Django Admin because the URLs include the prefixed ID, and Django tries to query the database directly using this prefixed value. Here is my custom field implementation: import uuid from django.db import models class PrefixedUUIDField(models.UUIDField): def __init__(self, prefix, *args, **kwargs): self.prefix = prefix super().__init__(*args, **kwargs) def from_db_value(self, value, expression, connection): if value is None: return value return f"{self.prefix}_{value}" def get_prep_value(self, value): if isinstance(value, str) and value.startswith(f"{self.prefix}_"): value = value.split(f"{self.prefix}_")[1] return super().get_prep_value(value) def to_python(self, value): if isinstance(value, uuid.UUID): return f"{self.prefix}_{value.hex}" if isinstance(value, str) and not value.startswith(f"{self.prefix}_"): return f"{self.prefix}_{value}" return value The model: class FamilyTree(models.Model): id = PrefixedUUIDField(prefix="ft", primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=255) In Django Admin, the URL for editing an object looks like this: http://admin.localhost:8000/family_tree/familytree/ft_5F5479ca65374d401d9466d57fc95e4072/change/ However, this causes the following error: invalid input syntax for type uuid: "ft_5F5479ca65374d401d9466d57fc95e4072" I understand this happens because Django Admin tries to query the database using the prefixed id, but the database … -
Column 'tbl1.id' is not the same data type as referencing column 'tbl2.field_id' in foreign key 'tb1_field_id_tbl2_id'
I have a problem with migrations. I'm using database which was created with old Django version 1.4 in new application with Django version >5. The problem is that old Django is using different data type for primary key field (AutoField - int in database). So in database datatype of old django's primary key is "int" and in the new Django datatype is "bigint". I've created new model with Foreign Key to old model and now I'm facing an error: Column 'tbl1.id' is not the same data type as referencing column 'tbl2.field_id' in foreign key 'tb1_field_id_tbl2_id' How can I solve this problem? Only thing that help is to assign db_constraint=True in the models.ForeignKey field. But I don't want have this risk. -
Suggestion of Django "email queue" package for current versions?
I found the django-mail-queue and django-email-queue packages, which are several years old yet appear to be well-used. But, as recently discussed here moments ago, I ran into unexpected migration issues. (And, with help, I think solved them.) But I'd like to ask if anyone has a better suggestion – for current Django, current MySQL and so-on. "I just want: 'It Just Works.™'" No migration quibbles, and so on. I want to simply be able to queue email-only messages and then send them with a periodically-scheduled 'manage' subcommand. That's it, that's all. The above-cited packages will work for me, but the migration issue startled me. -
Why do I have to create a new thread for updating a database record? (Django Rest Framework)
I'm using Django Rest Framework for creating an API. The idea is that the user uploads some data using a POST request. This data is uploaded to a database. Once uploaded, a new Python thread is created, running some operations on said data. Then when operations have finished, the result is written to the original database record. Using this approach the API remains accessible, while also working on the operations in the background. The user can check the operations status using a GET request. For some reason, when trying to update the record with the operation results, I got the following error: SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async It was confusing, since the operation and updating function was already running using a thread. I would not get the error when substituting the operations with some simple mock-up test results (strings). Not even when using time.sleep() for a longer period than the actual operations would take. So I suspect the problem has something to do with the operations I'm running, even though they do not interact with Django whatsoever. I fixed the problem by creating new threads specifically for saving the updated … -
Django alterfield migration to textfield fails
The migration for Django package django-mail-queue contains the following in relevant part: migrations.AlterField( model_name='mailermessage', name='to_address', field=models.TextField(db_index=True, verbose_name='To'), ), But it fails on MySQL 9.0.1 (Django 5.1.5) with the following error: django.db.utils.OperationalError: (1170, "BLOB/TEXT column 'to_address' used in key specification without a key length") Any idea why? I found a closed bug-report for Django (from some years ago) in which this kind of AlterField request had problems, but it appears to be unrelated. -
django_apscheduler calls my job many times
I have a scheduler python package with this main file: from apscheduler.schedulers.background import BackgroundScheduler from django_apscheduler.jobstores import DjangoJobStore, register_events from django.utils import timezone from django_apscheduler.models import DjangoJobExecution import sys # This is the function you want to schedule - add as many as you want and then register them in the start() function below def scheduled_function(): print("my function is running as scheduled") def start(): scheduler = BackgroundScheduler() scheduler.add_jobstore(DjangoJobStore(), "default") scheduler.remove_all_jobs() scheduler.add_job(scheduled_function, 'interval', seconds=10, name='scheduled_function', jobstore='default') scheduler.start() scheduler.print_jobs() I call it from my apps.py like this: from django.apps import AppConfig import os class MyAppConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'my_server_app' def ready(self): if os.environ["RUN_MAIN"]: from my_app.scheduler import scheduler scheduler.start() Despite calling remove_all_jobs, my function is called many times. For example, the output of my print_jobs call looks like this after I've restarted django a few times: Jobstore default: scheduled_function (trigger: interval[0:00:10], next run at: 2025-01-16 11:43:56 UTC) scheduled_function (trigger: interval[0:00:10], next run at: 2025-01-16 11:43:56 UTC) scheduled_function (trigger: interval[0:00:10], next run at: 2025-01-16 11:43:56 UTC) scheduled_function (trigger: interval[0:00:10], next run at: 2025-01-16 11:44:01 UTC) scheduled_function (trigger: interval[0:00:10], next run at: 2025-01-16 11:44:02 UTC) scheduled_function (trigger: interval[0:00:10], next run at: 2025-01-16 11:44:03 UTC) scheduled_function (trigger: interval[0:00:10], next run at: 2025-01-16 11:44:04 UTC) … -
How do I hot reload a Django reusable app?
I am creating a Django reusable app. I can build the package using python -m pip install build which creates *.tar.gz file which i can install. But how do i make the main Django app auto reload on changes in the child app. I have wasted many hours looking for something to do this but couldn't find anything. -
Adding the user I created in Django to the server with ldap
I want to add the user created in Django to my server via LDAP. Even if I get the message that the connection is successful, it does not continue and gives this warning: LDAP connection successfully. Error occurred during LDAP connection: ('unable to open socket', [(LDAPSocketOpenError('socket connection error while opening: [WinError 10060] I can attract users to my database with the connection I made. def create_user_in_ldap(request, django_user): """ Adds the user created in Django to the LDAP server. """ try: ldap_config = get_object_or_404(LdapConfig,company=request.user.company) ldap_server = ldap_config.ldap_server ldap_username = ldap_config.bind_username ldap_password = ldap_config.bind_password ldap_domain = ldap_config.bind_dn server = Server(ldap_server, get_info=ALL) connection = Connection( server, user=f"{ldap_domain}\\{ldap_username}", password=ldap_password, authentication=NTLM, auto_bind=True ) if not connection.bind(): print(f"LDAP connection unsuccessful: {connection.result}") return False print("LDAP connection succesfully") user_dn = f"cn={django_user.username},ou=Users,dc=example,dc=com" attributes = { "objectClass": ["top", "person", "organizationalPerson", "user"], "cn": django_user.username, "sn": django_user.last_name or "NoLastName", "givenName": django_user.first_name or "NoFirstName", "displayName": f"{django_user.first_name} {django_user.last_name}", "mail": django_user.email, "userPassword": "default_password", } connection.add(user_dn, attributes=attributes) print("User add result:", connection.result) if connection.result["description"] == "success": print(f"User successfully added to LDAP server {django_user.username}") return True else: print(f"Error adding user: {connection.result['description']}") return False except Exception as e: print(f"Error occurred during LDAP connection: {str(e)}") return False -
Set-cookie isn't working with React and Django
I am trying to make a simple session-based authentication with Django and React, but the browser won't set cookies LoginView: class LoginView(APIView): def post(self, request): username = request.data.get("username") password = request.data.get("password") user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return Response( {"message": "Login successful", "username": user.username}, status=status.HTTP_200_OK, ) else: return Response( {"error": "Invalid credentials"}, status=status.HTTP_401_UNAUTHORIZED ) Front-end logic: const getData = () => { fetch("http://127.0.0.1:8000/me/").then( (res) => { return res.json() } ).then( (data) => { setUsername(data.username) } ) } const login = () => { fetch("http://127.0.0.1:8000/login", { method: "POST", body: JSON.stringify({ "username": "user", "password": "password" }), headers: { "Content-Type": "application/json", } }).then(function(response){ return response.json(); }).then((data) => console.log(data)); getData() } Note: Backend actually sends back Set-Cookie header: set-cookie: csrftoken=OHi2iTT8vDvnn7pAzbb705zrj3gFkFLK; expires=Thu, 15 Jan 2026 08:31:49 GMT; Max-Age=31449600; Path=/ set-cookie: sessionid=jna0kbgo4k8x8spoyzyyxch2d24bz2li; expires=Thu, 30 Jan 2025 08:31:49 GMT; HttpOnly; Max-Age=1209600; Path=/ -
Django DRF API endpoint can be called via Postman but gives back 404 not found in pytest
I'm currently rewriting our Django unit tests (written with django.unittest library) in pytest, and I'm encountering an issue. I use a separate conftest.py file where I store my pytest fixtures and also load my JSON fixtures to fill the database with test data. One of my pytest fixture methods creates a user, and another one creates an authorized client. The user fixture also takes db as an argument. That's basically the base setup. The test method calls an endpoint that includes the user_id in the URL. The call looks something like: response = authorized_client.get(path=f"/user/{user_id}", headers=header) Testing the endpoint manually in Postman gives back the user data and a 200 status code. However, pytest returns a 404 status code. User.objects.exists(id=user_id) This confirmed that the user exists in the database. I investigated further and called the endpoint that retrieves all users. The user_id I used in the call to the endpoint was not included in the response. I suppose that's why I get a 404 back. The Question Why do I get User.objects.exists(id=user_id) but the user with that ID is not actually there when I call the endpoint? Does pytest handle test database isolation differently than django.unittest so that the viewset can't … -
ModuleNotFoundError at /api/v1/account/users/1/
I have a django rest framework project with this kind of treeroot in the accounts model I have a User model like bellow : class User(AbstractUser): phone_number = models.CharField(max_length=11, unique=True) then I have a simple serializer and ModelViewSet for this model the apps.py in accounts is as bellow : from django.apps import AppConfig class AccountsConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'api.accounts' and in the api directory apps.py is like this : from django.apps import AppConfig class ApiConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'api' and at the end this is my settings.py """ Django settings for listings project. Generated by 'django-admin startproject' using Django 3.2.4. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ import environ import os from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ env = environ.Env() DEBUG = True BASE_URL_V1 = 'api/v1/' # reading the EVN file environ.Env.read_env(BASE_DIR.__str__() + '/../.env') # Raises django's ImproperlyConfigured exception if SECRET_KEY not in os.environ SECRET_KEY = env('SECRET_KEY') AUTH_USER_MODEL = "accounts.User" INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'drf_spectacular', … -
Issue with Django CheckConstraint
I'm trying to add some new fields to an existing model and also a constraint related to those new fields: class User(models.Model): username = models.CharField(max_length=32) # New fields ################################## has_garden = models.BooleanField(default=False) garden_description = models.CharField( max_length=32, null=True, blank=True, ) class Meta: constraints = [ models.CheckConstraint( check=Q(has_garden=models.Value(True)) & Q(garden_description__isnull=True), name="garden_description_if_has_garden", ) ] The problem is that when I run my migrations I get the following error: django.db.utils.IntegrityError: check constraint "garden_description_if_has_garden" is violated by some row But I don't understand how the constraint is being violated if no User has a has_garden, the field is just being created and also its default value is False 🤔. I'm using django 3.2 with postgresql. What is the proper way to add this constraint? If it's of any use here's the autogenerated migration: # Generated by Django 3.2.25 on 2025-01-15 23:52 import django.db.models.expressions from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("some_app", "0066_gardenuser"), ] operations = [ migrations.AddField( model_name="user", name="garden_description", field=models.CharField(blank=True, max_length=32, null=True), ), migrations.AddField( model_name="user", name="has_garden", field=models.BooleanField(default=False), ), migrations.AddConstraint( model_name="user", constraint=models.CheckConstraint( check=models.Q( ("has_garden", django.db.models.expressions.Value(True)), ("garden_description__isnull", True), ), name="garden_description_if_has_garden", ), ), ] -
How to display multiple self-related foreign key data in Django/HTML?
I am trying to create a django web app for displaying various data (a question and some additional data).My data consists of a question body and industry guidance, which contains several bullet points. Each bullet point may contain additional sub options itself as well, etc. Example data: Question body: Was everyone familiar with the location, purpose, testing and oepration of fire doors? Industry Guidance: Operational readiness Maintenance and testing Regular inspections Regular maintenance Weekly Monthly ... Below are my models: class BaseGuidance(models.model): text = models.CharField(max_length=2000) parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name="sub_options") class Meta: abstract = True def __str__(self): return self.text class IndustryGuidance(BaseGuidance): pass class Question(models.model): body = models.CharField(max_length=400) industry_guidance = models.ForeignKey(IndustryGuidance, on_delete=models.CASCADE, null=True, blank=True) Here is my view, which is rendering the HTML: def index(request): questions = Question.objects.all() industry_guidance = IndustryGuidance.objects.prefetch_related( 'sub_options', ).all() return render(request, "sire/index.html",{ "questions": questions, "industry_guidance": industry_guidance }) Below is my HTML: <td scope="col"> <ul class="list-group"> {% for guidance in industry_guidance %} <li>{{ guidance.text }} </li> <ul> {% for sub_option in guidance.sub_options.all %} <li>{{ sub_option.text }}</li> {% endfor %} </ul> {% endfor %} </ul> </td> I am really confused on to how exactly I should approach this problem in order to fetch all data and display … -
Cant upload media from Django app to R2 Cloudflare or Digital Ocean Spaces
im having some issues uploading media to R2 Cloudflare or Digital Ocean Spaces , the app is hosted in Digital Ocean, i guess something is blocking the app, and I dont know where start looking. Django + Nginx + Gunicorn. Local server is doing well. Any ideas? Thank you!