Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Template Table custom cells?
I am playing around with django a bit and wanted to create a table which I'm filling with some whatever. I am very new to programming with django and html. I have 4 for loops (sounds like a lot) {% for row in rows %} <tr> {% for column in columns %} {% for item1 in items1 %} {% if item1.attribute == column.attribute and something %} <td>{{item1.name}}</td> {% endif %} {% endfor %} {% for item2 in items2 %} {% if something %} <td>{{item2.name}}</td> {% endif %} {% endfor %} {% endfor %} </tr> {% endfor %} So as you can see, only if one of the if conditions is true a cell is created. This is obviously not what I want and I know by doing <td> {% for column in columns %} <td> {% for item1 in items1 %} . . . {% endif %} {% endfor %} </td> there would be a cell for every row and column tuple. However I want to individualy add a different background to each of the item types (item.type exists) like <td bgcolor= "color_name | hex_number | rgb_number"> </td>. I first tried a variable {% with emptycell="yes" %} that I change … -
Import Errors for Custom Django Apps in XBlock Development on OpenEdX Palm Version
I’m having trouble importing custom Django apps in an Open edX XBlock. Even though the Django application is installed in the Open edX environment, I'm encountering errors. The video_rating custom Django application is installed and working perfectly in this environment. onlineoffline is my XBlock. 2024-07-22 10:43:36,866 WARNING 32 [xblock.plugin] [user None] [ip None] plugin.py:144 - Unable to load XBlock ‘onlineoffline’ Traceback (most recent call last): File “/openedx/venv/lib/python3.8/site-packages/xblock/plugin.py”, line 141, in load_classes yield (class_.name, cls.load_class_entry_point(class)) File “/openedx/venv/lib/python3.8/site-packages/xblock/plugin.py”, line 70, in load_class_entry_point class = entry_point.load() File “/openedx/venv/lib/python3.8/site-packages/pkg_resources/init.py”, line 2517, in load return self.resolve() File “/openedx/venv/lib/python3.8/site-packages/pkg_resources/init.py”, line 2523, in resolve module = import(self.module_name, fromlist=[‘name’], level=0) File “/openedx/venv/lib/python3.8/site-packages/onlineoffline/init.py”, line 1, in from .onlineoffline import OnlineOfflineClassXBlock File “/openedx/venv/lib/python3.8/site-packages/onlineoffline/onlineoffline.py”, line 4, in from openedx.features.video_rating.models import UserFeedbackSave,Questions,Type,Ratings ModuleNotFoundError: No module named ‘openedx.features.video_rating’ -
Use Custom Manager to Filter on a Reverse Relation
I have a set of users and a set of assignments each user submits. class User(models.Model): name = models.CharField() class Assignment(models.Model): user = models.ForeignKey( "User", related_name="assignments" ) status = models.CharField() approved = AssignmentActiveManager() rejected = AssignmentRejectedManager() ... I created custom managers to determine different states of assignments, as it's complex and should be internal to the model. For example: class AssignmentActiveManager() def get_queryset(self): return Assignment.objects.filter(status__in=["Approved", "Accepted"]) Now I want to get all users with an approved assignment, using the Assignment.approved manager, because I don't want to duplicate the filtering code. I can do Users.objects.filter(assignments__in=Assignments.approved.all()).all() However, this query involves a WHERE status IN (SELECT ...) subquery. This is going to be less efficient than the query generated if I had written the filtering explicitly: Users.objects.filter(assignments__status__in=["Approved", "Accepted"]).all() Which would do an INNER JOIN and WHERE status IN (Approved, Accepted). So my question is. Is there a way to select users by filtering on assignments using the Assignment custom managers efficiently? -
Django project on CS50dev IDE
I am currently working on the CS50 Web course and am focusing on Project 1. For my development environment, I decided to use the online CS50dev IDE because I cannot install Django on my PC due to administrative restrictions. One of the first tasks in the project is to set up routing for files. For example, if you type server_address/wiki/css, you should be able to view the css page (if it exists); otherwise, an error page should be rendered. However, when I run the server and try to view pages, the error page is always displayed instead of the css page (or any other existing page). I suspect the problem might be related to the storage configuration. When I use the debugger to test my get_entry function, I encounter the following error: django.core.exceptions.ImproperlyConfigured: Requested setting STORAGES, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. Could you please help me figure out this bug? I’ve spent hours researching it, but nothing seems to be working. I tried to configure the storages but that didn't help. -
Django: How to solve multi-dev issue for database that should be populated
I'm working on a project with some people and we've been adding images and some text to the database (Postgres) through the django admin, they get added to the database but when someone commits to the GitHub repository and someone else pulls and runs he doesn't see any of the things added to the database. It looks like django doesn't leave instructions of what to populate to the database in the code itself so how can we get around this issue? Is there a standard method people already use? -
Modify available choices for a multiple Django from based on current selection
I have a form that works with these base choices: class ShockForm(forms.Form): sector = forms.ChoiceField(choices=[ ('c1', 'Choice 1'), ('c2', 'Choice 2'), ('c3', 'Choice 3'), ]) amount = forms.FloatField() the form is rendered a number of times depending on the user's previous selection, it displays n forms if n was inputed by the user on the previous screen. I want to make the forms dynamic, ie, if an user selects one choice in the first form that choice is not available on the other form and so on, so there cannot be duplicated choices. I belive JS is the solution for this as I am not saving every form one by one but all in one go (see views below). However I have very little knowledge of JS and all I tried did not work. Any guidance? Here is the template relevant content: <form method="post"> {% csrf_token %} {% for form in shocks_forms %} <h4>Sector {{ forloop.counter }}</h4> {{ form.as_p }} {% endfor %} <button type="submit">Submit</button> </form> And here the back end view: def simulation_shocks_view(request, pk): simulation = get_object_or_404(Simulation, pk=pk) number_of_sectors_to_shock = simulation.number_of_sectors_to_shock if request.method == 'POST': form_list = [ShockForm(request.POST, prefix=str(i+1), impact_area=simulation.impact_area) for i in range(number_of_sectors_to_shock)] if all(form.is_valid() for form in … -
I cannot figure out why I am still having pathing issues in Django for the Admin Panel as it is having trouble finding the static file
I have changed my Django folder structure quite late in the project, I am new to Django, so I did not prepare the folders at the beginning of the project which is my fault. I have been having issues with the static files, I managed to fix the static files for the project, but my Django Admin panel seems to have issues finding the static files for the admin panel. These are the types of errors that I am getting: WARNING 2024-08-14 09:27:03,080 log 10464 13992 Not Found: /static/admin/css/responsive.css WARNING 2024-08-14 09:27:03,080 log 10464 12416 Not Found: /static/admin/css/nav_sidebar.css WARNING 2024-08-14 09:27:03,080 basehttp 10464 13992 "GET /static/admin/css/responsive.css HTTP/1.1" 404 179 WARNING 2024-08-14 09:27:03,080 basehttp 10464 12416 "GET /static/admin/css/nav_sidebar.css HTTP/1.1" 404 179 The admin panel does load it's just the aesthetic aspects of it not loading, such as the css. This is the folder structure: ├───api │ ├───migrations │ ├───utils ├───assets │ ├───css │ └───images ├───config │ ├───django (This is where the base.py, prod.py, test.py, dev.py files) │ │ └── base.py │ │ └── test.py │ │ └── dev.py │ │ └── prod.py │ ├───settings (This is for storing files such as celery.py) │ ├───env.py │ ├───urls.py ├───templates │ └───includes └───.env └───manage.py … -
Custom Permission Mixin Django Rest Framework
I am trying to create a custom mixim that handles additional permission checks in my views. This is what I have tried: class ProfilePermissionsRequiredMixin: required_permissions = [] def get_required_permissions(self): return self.required_permissions def dispatch(self, request, *args, **kwargs): # Check if the user is authenticated if not request.user.is_authenticated: raise PermissionDenied("You must be logged in to access this resource.") # Get the user's profile profile = request.user.profile # Check if the profile has all the required permissions if all(profile.has_perm(perm) for perm in self.get_required_permissions()): return super().dispatch(request, *args, **kwargs) # Return 403 Forbidden if any permission check fails raise PermissionDenied("You do not have permission to access this resource.") The issue here is that the request that I get is not authenticated. I use a custom authentication class and it is apparently not applied in the despatch. What can I do to fix this? -
Is there a way to fix AuthCanceled error in the google-sign in in Django?
I was just developing my website, adding CustomUsers, managing profiles, etc., and everything went well, but when I tried to add Google Sign In, I kept getting errors in mid-authentication, like: !error image(https://i.sstatic.net/JqgI0S2C.png) or a text description of it: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/accounts/complete/google-oauth2/?state=Ykq4uYjlm2UMCICLCaKNQtDFmb6hEeQf&code=4%2F0AcvDMrA19DF4z27cVgLBo0ZMua4bL0njYqz-XKFiX9cjZ4k_xf9qAAAD_thq74_ghMhRUw&scope=email+profile+openid+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email&authuser=0&prompt=consent Django Version: 4.2.14 Python Version: 3.10.5 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'main.apps.MainConfig', 'social_django'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'social_django.middleware.SocialAuthExceptionMiddleware', 'django_user_agents.middleware.UserAgentMiddleware'] Traceback (most recent call last): File "C:\Users\norou\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\norou\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\norou\AppData\Local\Programs\Python\Python310\lib\site-packages\django\views\decorators\cache.py", line 62, in _wrapper_view_func response = view_func(request, *args, **kwargs) File "C:\Users\norou\AppData\Local\Programs\Python\Python310\lib\site-packages\django\views\decorators\csrf.py", line 56, in wrapper_view return view_func(*args, **kwargs) File "C:\Users\norou\AppData\Local\Programs\Python\Python310\lib\site-packages\social_django\utils.py", line 49, in wrapper return func(request, backend, *args, **kwargs) File "C:\Users\norou\AppData\Local\Programs\Python\Python310\lib\site-packages\social_django\views.py", line 31, in complete return do_complete( File "C:\Users\norou\AppData\Local\Programs\Python\Python310\lib\site-packages\social_core\actions.py", line 49, in do_complete user = backend.complete(user=user, redirect_name=redirect_name, *args, **kwargs) File "C:\Users\norou\AppData\Local\Programs\Python\Python310\lib\site-packages\social_core\backends\base.py", line 39, in complete return self.auth_complete(*args, **kwargs) File "C:\Users\norou\AppData\Local\Programs\Python\Python310\lib\site-packages\social_core\utils.py", line 256, in wrapper return func(*args, **kwargs) File "C:\Users\norou\AppData\Local\Programs\Python\Python310\lib\site-packages\social_core\backends\oauth.py", line 411, in auth_complete state = self.validate_state() File "C:\Users\norou\AppData\Local\Programs\Python\Python310\lib\site-packages\social_core\backends\oauth.py", line 101, in validate_state raise AuthStateMissing(self, "state") Exception Type: AuthStateMissing at /accounts/complete/google-oauth2/ Exception Value: Session value state missing. Please note that I … -
In Django, I would like to narrow a choice using a form to another form
I am trying to use the result of a selection as input to another selection. I have been working on this for three weeks, and I cannot find a simple answer. Here are my models: from django.db import models # Create your models here. class School(models.Model): id = models.CharField(primary_key=True, max_length=10) school_name = models.CharField(max_length=80) def __str__(self): return(f"{self.id} {self.school_name}") return self.id class Meta: ordering = ['id'] indexes = [ models.Index(fields=['id', 'school_name']), ] class Courses(models.Model): id = models.CharField(primary_key=True, max_length=12) created_at = models.DateTimeField(auto_now_add=True) school = models.ForeignKey(School, on_delete=models.PROTECT, related_name='school') name = models.CharField(max_length=150, null=True, blank=True) cost = models.CharField(max_length=75, null=True, blank=True) class Meta: ordering = ['id'] indexes = [ models.Index(fields=['school']), models.Index(fields=['name', 'id'])] def __str__(self): return(f"{self.school} {self.name}") return self.name class Student(models.Model): course = models.ForeignKey(Courses, on_delete=models.PROTECT) created_at = models.DateTimeField(auto_now_add=True) student_id = models.CharField(max_length=20, null=True, blank=True) class Meta: ordering = ['course'] indexes = [ models.Index(fields=['course']), ] And my views: def choose_school3(request): if request.user.is_authenticated: aschool = Courses.objects.all() form=SelectSchoolForm(request.POST) if request.method == "POST": if form.is_valid(): data = form.cleaned_data choice = data['school'] selected_school = Courses.objects.filter(school=choice).values() context = {'choice': choice} return render(request, 'add_student2b.html', context) context = {'form': form, 'aschool':aschool} return render(request, 'choose_school3.html', context) else: messages.success(request, "You Must Be Logged In To View Records!") return redirect('main') def add_student2b(request, choice): chosen_school = Courses.objects.filter(school=choice).values() form = AddStudentForm(request.POST) context … -
How to create restore password function with Django rest framework?
I have a Django Rest Framework app. And I try to create reset password function. But the problem I am facing is that some functions are not called by the Django Rest Framework. So I have a module accounts--> templates --> registration and then the html templates in it. Like: password_reset password_reset_confirm password_reseet_done password_reset_form And in the accounts module I have a views.py file: from django.shortcuts import render from django.utils.http import urlsafe_base64_decode from django.utils.encoding import force_str from django.contrib.auth.tokens import default_token_generator from rest_framework import generics from .serializers import ChangePasswordSerializer class PasswordResetConfirmView(generics.GenericAPIView): serializer_class = ChangePasswordSerializer def get(self, request, uidb64, token, *args, **kwargs): try: uid = force_str(urlsafe_base64_decode(uidb64)) user = UserModel.objects.get(pk=uid) except (TypeError, ValueError, OverflowError, UserModel.DoesNotExist): user = None if user is not None and default_token_generator.check_token(user, token): return render(request, 'registration/password_reset_confirm.html', {'validlink': True, 'user': user, 'uidb64': uidb64, 'token': token}) else: return render(request, 'registration/password_reset_confirm.html', {'validlink': False}) def post(self, request, uidb64, token, *args, **kwargs): try: uid = force_str(urlsafe_base64_decode(uidb64)) user = UserModel.objects.get(pk=uid) except (TypeError, ValueError, OverflowError, UserModel.DoesNotExist): user = None if user is not None and default_token_generator.check_token(user, token): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return Response({"message": "Password has been reset successfully."}, status=status.HTTP_200_OK) else: return Response({"error": "Invalid link."}, status=status.HTTP_400_BAD_REQUEST) And a serializers.py file: from django.utils.translation import gettext as _ from … -
Is there any option to get "to-many" relation objects while saving "parent" object?
I have three models class Parent(models.Model): name = models.CharField(blank=True, max_length=20) ... # other fields def _get_childs(self): first_childs = [f'{child.name}' for child in self.one_childs.all()] second_childs = [f'{child.name}' for child in self.two_childs.all()] return [first_childs + second_childs] @classmethod def get_config(cls) -> str: try: instance = cls.objects.get() except cls.DoesNotExist: return '' config = {} for child in instance._get_childs(): config[child] = { 'interval': 1000, ... # other fields } return json.dumps(config, indent=4) class OneChild(models.Model): name = models.CharField(blank=True, max_length=20) parent = models.ForeignKey(Parent, on_delete=models.SET_NULL, blank=True, null=True, related_name='one_childs') ... # other fields class TwoChild(models.Model): name = models.CharField(blank=True, max_length=20) parent = models.ForeignKey(Parent, on_delete=models.SET_NULL, blank=True, null=True, related_name='two_childs') ... # other fields I need to write get_config result to file ('/tmp/config' as example) on Parent save. everything works fine, but i get previous relations childs, not new. i tried to use it in post_save signal for Parent model, but it is does not help. there is a signal for example @receiver(post_save, sender=Parent) def update_config(sender, instance, **kwargs): config_json = instance.get_config() file_path = '/tmp/config.json' with open(file_path, 'w') as file: file.write(config_json) when I save Parent all values become valid except child.name's is there any option to achieve this? -
Deployment of containerized Reat Django app with nginx
I have an app: client in react. server in django. the app is containerized: backend-container and frontend-container as follows (docker-compose.yaml): version: '3.8' services: backend: build: context: ./backend dockerfile: Dockerfile args: POSTGRES_USER: ${POSTGRES_USER} POSTGRES_PASSWORD: ${POSTGRES_PASSWORD} POSTGRES_HOST: ${POSTGRES_HOST} SECRET_KEY: ${SECRET_KEY} DEBUG: ${DEBUG} CORS_ALLOWED_ORIGIN: ${CORS_ALLOWED_ORIGIN} REACT_APP_ALLOWED_HOST: ${REACT_APP_ALLOWED_HOST} image: backend container_name: backend-container ports: - "8000:8000" environment: POSTGRES_USER: ${POSTGRES_USER} POSTGRES_PASSWORD: ${POSTGRES_PASSWORD} POSTGRES_HOST: ${POSTGRES_HOST} SECRET_KEY: ${SECRET_KEY} DEBUG: ${DEBUG} CORS_ALLOWED_ORIGIN: ${CORS_ALLOWED_ORIGIN} REACT_APP_ALLOWED_HOST: ${REACT_APP_ALLOWED_HOST} frontend: build: context: ./frontend dockerfile: Dockerfile args: REACT_APP_ALLOWED_HOST: ${REACT_APP_ALLOWED_HOST} image: frontend container_name: frontend-container ports: - "3000:3000" environment: NODE_ENV: production REACT_APP_ALLOWED_HOST: ${REACT_APP_ALLOWED_HOST} and the app is hosted on an EC2 instance, deployed using github action: name: My workflow on: workflow_dispatch jobs: first-job: runs-on: self-hosted steps: - name: Checkout code uses: actions/checkout@v4 - name: Build the Docker backend image env: POSTGRES_USER: ${{ secrets.POSTGRES_USER }} POSTGRES_PASSWORD: ${{ secrets.POSTGRES_PASSWORD }} POSTGRES_HOST: ${{ secrets.POSTGRES_HOST }} SECRET_KEY: ${{ secrets.SECRET_KEY }} DEBUG: ${{ secrets.DEBUG }} CORS_ALLOWED_ORIGIN: ${{ secrets.CORS_ALLOWED_ORIGIN }} REACT_APP_ALLOWED_HOST: ${{ secrets.REACT_APP_ALLOWED_HOST }} run: | sudo docker-compose -p fullstack down sudo POSTGRES_USER=$POSTGRES_USER POSTGRES_PASSWORD=$POSTGRES_PASSWORD POSTGRES_HOST=$POSTGRES_HOST SECRET_KEY=$SECRET_KEY DEBUG=$DEBUG CORS_ALLOWED_ORIGIN=$CORS_ALLOWED_ORIGIN REACT_APP_ALLOWED_HOST=$REACT_APP_ALLOWED_HOST docker-compose -p fullstack up --build -d I can see the containers are running on my EC2 instance. I configured an nginx on the EC2 instance: server { listen 80; server_name _; location / … -
Review table for two different profile types in Django and PostgreSQL DB
I have a question how I should design this relational database. I have a main profile, which has 2 sub-profiles, which are weak entities. These sub-profiles represent counterparts of a business process, an Employee and an Employer. Given I want to have tables that are related to these sub-profiles, such as "Review" or "Job Posting" (Similar to LinkedIn), which approach would be the most suitable: Creating a separate table for each profile type, e.g., EmployerReview and EmployeeReview Creating a single unified table, which has fields to determine which sub-profile type is sending and receiving the data. e.g., Review sender models.ForeignKey(Profile...) receiver models.ForeignKey(Profile...) sender_type models.CharField(max_length=15, choices=PROFILE_TYPES) receiver_type models.CharField(max_length=15, choices=PROFILE_TYPES) My main concern is the performance issues, e.g., when wanting to query all EmployerProfiles and the related Reviews of that profile. Now, If I have understood correctly, in method 2. you would have to do filter query, which is obviously slower than select_related (Similar to SQL Join?). The gain would be more flexibility and simple complexity, but there would be performance loss. Which of these methods would be more standardized or optimized way for such a problem? I tried creating both of the solutions, and they both work, but I am not … -
SequenceField to share unique IDs across multiple tables and more
Hello Django community, I recently faced a case where I had to have multiple models/tables having unique IDs coming from the same postgresql sequence. I was amazed to see how difficult it is to this from Django and I couldn't find a nice package doing this neither. So I developed django-sequencefield to address this limitation.: https://github.com/quertenmont/django-sequencefield Cherry on the cake, django-sequencefield could also be used to generate uniqueId containing additional data. I showcase a model using an id that is composed of a date (2 bytes) and a unique sequence id (6 bytes). This is useful to cluster the table simultaneously by date and Id while guaranteeing unicity and avoiding the use of composed primary key (not supported by Django). I would like to have feedback on this work, so feel free to try and comment. Thank in advance Loïc -
Can't install Python Imaging Library "Pillow"
I have tried to install pillow library for my Django project it won't install. I have tried many times there are no specific answer for problem on internet. First Try Terminal Input: (venv) PS C:\Users\Samsung\Desktop\lms-django> pip install pillow Terminal Output: Fatal error in launcher: Unable to create process using '"c:\users\samsung\desktop\lms\venv\scripts\python.exe" "C:\Users\Samsung\Desktop\lms-django\venv\Scripts\pip.exe" install pillow': The system cannot find the file specified. Second Try: Terminal Input: (venv) PS C:\Users\Samsung\Desktop\lms-django> python3 -m pip install Terminal Output: The term 'python3' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:8 + python3 <<<< -m pip install + CategoryInfo : ObjectNotFound: (python3:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException I want to find a way to install the python pillow library. -
Django losing connection with Postrgres creating a tenant
Developing a Django project using django-tenants. In the moment of new user registration, the tenant has to be created on the host domain with address "project-url.ru/username/..." Here is view.py with registration def create_user_tenant(request): user = UserClass.objects.get(username=request.POST['username']) schema_name = f'{user.username}_schema' try: with transaction.atomic(): tenant = Tenant(schema_name=schema_name, user=user) tenant.save() logger.debug(f'Tenant {tenant} created') domain = Domain(domain=HOST_NAME, tenant=tenant, is_primary=True) domain.save() logger.debug(f'Domain {domain} created for tenant {tenant}') logger.info(f'Tenant for {user.username} was created.') except IntegrityError as e: logger.error(f'Error creating tenant or domain for user {user.username}: {e}') except Exception as e: logger.error(f'Unexpected error creating tenant or domain for user {user.username}: {e}') def registration(request): error_msg = '' with transaction.atomic(): if request.POST: logger.debug(f"Registration request") form = UserRegistrationForm(data=request.POST) if form.is_valid(): user = form.save() logger.debug(f"User {user.username} has been registered") create_user_tenant(request) return redirect('login') else: error_msg = form.error_messages logger.debug(f"Registration form is invalid. Error {error_msg}") context = { 'form': UserRegistrationForm(), 'error_msg': error_msg, } return render(request, 'users/registration.html', context) However, when saving the tenant tenant.save() I get an error: The connection 'username_schema' doesn't exist. At the same time, if I do the same via ./manage.py shell everything works correctly. DB settings in settings.py: DATABASES = { "default": { 'ENGINE': "django_tenants.postgresql_backend", ..... } } DATABASE_ROUTERS = ( 'django_tenants.routers.TenantSyncRouter', ) MIDDLEWARE = [ 'django_tenants.middleware.main.TenantMainMiddleware', ... ] Postgres runs … -
Serving Static Files with Nginx and Django in Docker
Despite seeing many similar issues in other threads, I've been unable to configure Nginx to serve static files from my Django project. Here are my two static variables in my settings.py: STATIC_URL = '/static/' STATIC_ROOT='/opt/django/portfolio/collectstatic' Here is my dockerfile to build project image: FROM python:3.11-slim WORKDIR opt/django/ COPY pyproject.toml . RUN python -m pip install . COPY ./portfolio/ ./portfolio/ WORKDIR portfolio/ RUN python manage.py collectstatic --noinput RUN python manage.py makemigrations RUN python manage.py migrate EXPOSE 8000 CMD ["gunicorn", "portfolio.wsgi:application", "--bind", "0.0.0.0:8000"] Here is the docker-compose.yml: services: web: build: context: . dockerfile: ./docker/Dockerfile_django container_name: webserver volumes: - static_data:/opt/django/portfolio/collectstatic expose: - "8000" ports: - "8000:8000" depends_on: - db networks: - docker_network db: image: postgres:15 container_name: db_postgres expose: - "5432" ports: - "5432:5432" volumes: - postgres_data:/var/lib/postgresql/data environment: POSTGRES_DB: postgres POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres networks: - docker_network nginx: image: nginx:latest container_name: nginx ports: - "80:80" volumes: - ./nginx/nginx.conf:/etc/nginx/nginx.conf - static_data:/opt/django/portfolio/collectstatic depends_on: - web networks: - docker_network volumes: postgres_data: static_data: networks: docker_network: driver: bridge name: docker_network And finally, here is my nginx.conf: events {} http { server { listen 80; server_name localhost; location /static { alias /opt/django/portfolio/collectstatic; autoindex on; } # skip favicon.ico location /favicon.ico { access_log off; return 204; } location / { proxy_pass … -
Django date() doesn't translate uk and run month names
When I try to get localized datetime in a template using {{ enrolment.datetime_access_ends|date:"j E Y" }} I get 29 July 2025 (instead of expected 29 июля 2025). Localization works fine in all other places. I have this in my settings.py: LOCALE_PATHS = [BASE_DIR / "locale"] # type: ignore TIME_ZONE = "Europe/Kiev" USE_I18N = True USE_L10N = True USE_TZ = True LANGUAGE_CODE = "ru-UA" LANGUAGES = [ ("ru", _("Russian")), ("uk", _("Ukrainian")), ] When I try to get month translation from shell, I get expected results: >>> activate("uk") >>> date(timezone.now(), "F") 'Серпень' >>> activate("ru") >>> date(timezone.now(), "F") 'Август' But when I try to do the same from inside of the view, for some reason it doesn't work: print(get_language()) print(date(timezone.now(), "F")) gives ru August in logs. And if I change language to any other then uk or ru activate("pt") it works fine: pt Agosto -
Django + Javascript - dynamic ModelForm generation issue
I have this code {% extends 'base.html' %} {% block content %} <form method='POST'> <script> function addMemberFnc() { document.getElementById("teamMemberDiv").innerHTML+={{ project_members_form }} } </script> {{ project_form }} <p id="demo" onclick="addMemberFnc()">Add member.</p> <div style="border-style: dotted" id="teamMemberDiv"> {# {{ project_members_form }}#} </div> <button type="submit" class="btn btn-primary my-5">Submit</button> </form> {% endblock %} I would like to add project_member_form based on some action (it does not really matter now what action). This is not working because it seems that JS is not able to see Python variable in <script> block. Here is issue I've got: EDIT: I have got single form without any functions working without any issues. Here is my render method: def project_generation(request): if request.method == 'POST': pass else: project_form = ProjectForm(prefix='Project') project_role_form = ProjectRoleForm(prefix='ProjectRole') project_members_form = ProjectMemberForm(prefix='ProjectMember') # logging.debug(project_form) # logging.debug(project_members_form) return render(request, "project_xml_generation.html", { "project_form": project_form, "project_members_form": project_members_form }, ) -
Django translation html not translating the string when html files are included using include statement
views.py: def process_request(request, data) context = { 'category': datacategory, 'info': data.abc 'language_code': language_code } return TemplateResponse(request, template='.../components/test.html', context=context) test.html: {% load i18n %} {% load static %} <div class=""> <p>{% translate 'hello world' %}</p> {% include 'hash_processor/components/test2.html' %} </div> test2.html: {% load i18n %} {% load static %} <div class=""> <p>{% translate 'hi... world234567' %}</p> {% include 'hash_processor/components/test3.html' %} </div> test3.html: {% load i18n %} {% load static %} <div class=""> <p>{% translate 'heyy world234567' %}</p> </div> django.po: #: templates/hash_processor/components/test.html:6 msgid "hello world" msgstr "hgfghjkl wojehfvejh" #: templates/hash_processor/components/test2.html:6 msgid "hi... world234567" msgstr "hi....fjkherjfger kfhgerhjkf233" #: templates/hash_processor/components/test3.html:6 #, fuzzy #| msgid "hi... world234567" msgid "heyy world234567" msgstr "heyyy...ghewjfgdjhdfr kfhgerhjkf233" output on broswer: string coming for translation in django.po but not rendering in browser till level 2 it is working fine, but at 3 level translated string not showing -
Python Django Form - issue with checkboxes in ModelMultipleChoiceField
I have this model class ProjectMember(models.Model): member_name = models.CharField(max_length=100) member_uid = models.CharField(max_length=15) member_reviewer_uid = models.CharField(max_length=15) member_roles = models.ManyToManyField('ProjectRole', blank=False) member_discipline = models.ManyToManyField('ProjectDiscipline', blank=False) class ProjectRole(models.Model): role_name = models.CharField(max_length=10, unique=True) def __str__(self): return self.role_name this Form class ProjectMemberForm(forms.ModelForm): class Meta: model = ProjectMember fields = ( 'member_name', 'member_uid', 'member_reviewer_uid', 'member_roles' ) # member_roles = forms.ModelChoiceField( member_roles = forms.ModelMultipleChoiceField( queryset=ProjectRole.objects.all(), widget=forms.CheckboxSelectMultiple(attrs={'class': 'form-control'}), required=True, # empty_label=None, # Hide the empty label for the select multiple widget. ) widgets = { 'member_name': forms.TextInput(attrs={'class': 'form-control'}), 'member_uid': forms.TextInput(attrs={'class': 'form-control'}), 'member_reviewer_uid': forms.TextInput(attrs={'class': 'form-control'}), } I have tried also the commented lines of code. I am still getting only this I would call it listbox instead of checkboxes: My issue is that I would like to have it as checkbox instead of this list to crosscheck everything I want to be active. EDIT: Note that I do not intent to save any data into database. This is going to act as configuration server and output is .xml file. -
How do I add custom field in swagger ui in django application?
With every request the api endpoint requires a header name 'VENDOR'. I need to create a field in Django swagger ui to add the VENDOR value and attach it to the headers in every request. I tried customizing swagger settings in Django settings but it didnot work I want something similar like the one in the image but has to be vendor in the field and add to its the request image link -
Unable to display dash-plotly graph in webapp written with django/angular
The company were I work is building a website that is supposed to show some graphs and statistics. The front-end is written in angular and the back-end in python. I would like to use dash to create the plots but I'm having a hard time displaying my test dash app. In the front end there is a button 'draw graph' that when pressed should open a new window with where the app is shown. I tried following the django-plotly-dash tutorial but for some reason I cannot make it work. I'm relatively new to django btw. I have a graph app in the django project. My testing dash app is in dash_app.py and it contains a button that does nothing. from dash import html from django_plotly_dash import DjangoDash app = DjangoDash("Test") app.layout = html.Div([html.Button("Submit", id="submit-value")]) My template is dash_template.html <!DOCTYPE html> <html> <head> <title>Dashboard</title> {%load plotly_dash%} </head> <body> <h1>Dashboard Test</h1> {%plotly_app name="Test" %} </body> </html> And the views.py looks like this. def dash_view(request): return render(request, "graph/dash_template.html") When I click the the draw_graph button, the new window opens and the header Dashboard Test is displayed but the Submit button does not appear. I have already added path("django_plotly_dash/", include("django_plotly_dash.urls")) to the project urls.py … -
Django Email Sending Issue: Email Not Sent and Not Appearing in Sent Items
I'm working on a Django project where I need to send an email with an attached PDF file. My current setup is as follows: Django Version: 4.0.3 Python Version: 3.12.2 Problem: The code runs without throwing any errors. However, the email is not being received by the recipient. The email is also not appearing in the "Sent" folder of the sending Gmail account. Things I've Tried: Verified that the email configuration in settings.py is correct, using the Gmail SMTP server. Checked that the PDF file exists at the specified path. Ensured that there are no exceptions thrown during the email sending process. Tried sending a simple email without attachment, but still no success. Checked Gmail account security settings, including enabling "Less secure app access" and using an App Password. ** Questions: ** What might be causing the email to not be sent or appear in the sent items? Are there any additional debugging steps I can take to figure out what's going wrong? Could there be an issue with Gmail's SMTP server, or is there something I might be missing in the Django configuration? def send_email(request, customer_id): try: order = customer_agent.objects.get(customer_id=customer_id) except customer_agent.DoesNotExist: return HttpResponseNotFound("Order not found") subject = 'Your …