Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django admin panel redirects and URL issues: Incorrect paths in admin sites
I have a Django app for a REST API, and I also need to use the Django admin for some tasks. When I run the app locally and try to access the admin panel with the URL http://localhost:8000/admin, Django redirects me to http://localhost/localhost/admin. Also, when I try to access the login panel as http://localhost:8000/admin/login, I can see a valid login page. However, after clicking on 'Log In', a POST request is sent to http://localhost:8000/lo/admin/login/. I checked how HTML files are created for Django admin. I found a variable, app_path, that is passed to the template for creating the login page. The value for this variable is assigned in /usr/local/lib/python3.8/site-packages/django/contrib/admin/sites.py as app_path': request.get_full_path(). I created an endpoint to test the values returned from the get_full_path() function. When I call the endpoint http://localhost:8000/api/getadminurls, the value from get_full_path() is http/api/getadminurls. From all of this, I came to the conclusion that Django is not able to find the correct values that should be filled into those templates, but I was not able to find how to fix this. -
Tailwind css is not being served in Django App
I've been working on this Tailwind+Django project and it was working fine. Now it's not serving css. I've run the commanands py manage.py runserver and py manage.py tailwind start and there's no problem on servers. here is Settings.py STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' AUTH_USER_MODEL = 'authen.CustomUser' TAILWIND_APP_NAME = 'theme' INTERNAL_IPS = [ "127.0.0.1", ] NPM_BIN_PATH = r"C:\Program Files\nodejs\npm.cmd" urls.py from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path("__reload__/", include("django_browser_reload.urls")), path('',include('authen.urls')), path('rental/',include('rental.urls')), path('roommate/',include('roommate.urls')), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Tailwind.config.js module.exports = { content: [ '../templates/**/*.html', '../../templates/**/*.html', '../../**/templates/**/*.html', ], theme: { extend: {}, }, plugins: [ require('@tailwindcss/forms'), require('@tailwindcss/typography'), require('@tailwindcss/line-clamp'), require('@tailwindcss/aspect-ratio'), ], } here is the project structure Thanks for your time. if any further information is needed please ask. -
Get data from model in django with ajax
I have a django website which needs interaction through ajax. One of my pages includes a checkbox and I would like the data displayed on the client to depend on the state of my checkbox. Here is my view.py : ... def sales_view(request): dataModel = DataModel() return state_view(request, dataModel.m_bp.m_sales.m_name, sales_html) ... And my template sales_html.py (not a .html file as I use airium : from airium import Airium from contextlib import contextmanager from ..DataModel import DataModel @contextmanager def sales_html(a: Airium, dataModel: DataModel): # Page Heading with a.div(klass="d-sm-flex align-items-center justify-content-between mb-4"): a.h1(klass="h3 mb-0 text-gray-800", _t=dataModel.m_bp.m_sales.m_name) a.input(type = "checkbox", id = "yearMonthToggle", onclick = "myFunction()") a.script(src = "{% static 'src/js/test.js' %}", type = "text/javascript") # Get data from the model. myData = dataModel.getMyData() ... # Display the main ItemsGroups. a.div(klass="yearMonthContainer") ...code that will depend on user interactions... Note that I use airium rather than direct html + dtl to handle model dependent display (as I find it easier to handle all the data logic but this does not change much for my question. And for the javascript I have found this below, but I cannot find an easy way to call a django view from my script, the only think whih I … -
Django, Nginx, Gunicorn: 400 Bad Request when trying to access the AWS EC2 instance externally
I am encountering a "400 Bad Request" error when attempting to access my Django application externally on an AWS EC2 instance. Notably, the application functions correctly when accessed locally on the server. This issue arises when using Nginx as a reverse proxy and Gunicorn as the application server. For example when I'm on the ec2 instance and uses the command "curl --unix-socket /run/gunicorn.sock localhost/events/" I get the right data from the database. In the chrome console I can see this error: "The Cross-Origin-Openor-Policy header has been ignored, because the URL's origin was untrustworthy. It was defined either in the final response or a redirect. Please deliver the response using the HTTPS protocol. You can alos use the localhost origin instead." I have looked at the nginx logs and I don't get any information from that. I have tried many different solutions and looked and followed various tutorials and documentations, but it still won't work. I will add here some of the files that might be needed in figuring out this problem, and ask if you need more information, or can give me any direction of what I could try. tutorials I have looked at: https://www.youtube.com/watch?v=7O1H9kr1CsA https://medium.com/@madhankm/set-up-django-with-nginx-and-gunicorn-on-ubuntu-20-04-lts-8a02748435fe, settings.py (The important parts) … -
Django Docker Nginx can't load static files
I have a django project. I want to deploy it on AWS using Docker. Here is my services in docker-compose-prod.yml: ... api: image: meduzzen-backend-api container_name: django entrypoint: ./start_prod.sh tty: true stdin_open: true volumes: - .:/code - ./code:/apps - static:/code/static expose: - "8000" ports: - "8000:8000" depends_on: - postgres-db - redis env_file: - .env networks: - api-db-redis ... nginx: image: meduzzen-backend-nginx container_name: nginx volumes: - static:/static - ./nginx-conf.d:/etc/nginx/conf.d ports: - "80:80" depends_on: - api volumes: static: ... meduzzen-backend-api image was built from Dockerfile: FROM python:3.11.3-alpine ENV PYTHONBUFFERED=1 # Enable pytest-django ENV DJANGO_SETTINGS_MODULE=meduzzen_backend.settings WORKDIR /code COPY requirements.txt . RUN pip install -r requirements.txt --upgrade pip COPY . . # Copy start.sh script into project folder COPY start.sh . # Give access rights to start.sh RUN chmod +x start.sh RUN chmod +x start_prod.sh EXPOSE 8000 meduzzen-backend-nginx was built from Dockerfile: FROM nginx:1.25.3-alpine COPY ./default.conf /etc/nginx/conf.d/default.conf default.conf: upstream django { server api:8000; } server { listen 80; server_name localhost; location / { proxy_pass http://django; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /static/ { alias /static/; add_header Access-Control-Allow-Origin *; } } start_prod.sh: #!/bin/sh python manage.py migrate python manage.py collectstatic --noinput gunicorn meduzzen_backend.wsgi:application --bind 0.0.0.0:8000 Pages are loaded but it can't load static … -
Django parameterized tests - Problems
I want to test my Django app. To avoid code clones, i want to usere paramerezided testes. I also want to use variables i initialized in the setUp(), to avoid hardcoding e.g. primary keys. But i did not find a fitting solution. Idea 1: Loop from django.test import TestCase from app.models import Example class TestClass(TestCase): @classmethod def setUp(self): self.param1 = Example.object.create(att="foo") self.param2 = Example.object.create(att="bar") def test_example(self): for testcase in testcases: self.assertEqual(param.att,"expected) Problem: Cant find failed tests without adding extra debug messages. Idea 2: parameterized library from django.test import TestCase from app.models import Example from parameterized import parameterized class TestClass(TestCase): param1 = None param2 = None def setUp(self): self.param1 = Example.object.create(att="foo") self.param2 = Example.object.create(att="bar") @parameterized.expand([ (param1,"foo"), (param2,"bar"), ]) def test_example(self,param, expected): self.assertEqual(param.att,"expected) Problem: param is still None in the test Idea 3: getattr from django.test import TestCase from app.models import Example from parameterized import parameterized class TestClass(TestCase): param1 = None param2 = None def setUp(self): self.param1 = Example.object.create(att="foo") self.param2 = Example.object.create(att="bar") @parameterized.expand([ ("param1","foo"), ("param2","bar"), ]) def test_example(self,param, expected): param = getattr(self, param) expected = getattr(self, expected) self.assertEqual(param.att,"expected) Problem: very slow -
Hreflang conflicts and missing self-referencing hreflang issue in Django-based site
Issue 1: No self-referencing hreflang Description: Issue Type: No self-referencing hreflang. Page URLs: Page URL 1 Page URL 2 Current Hreflang Values: <link href="http://localhost:1300/en/catalogue/category/somecategory/for-kids_1532/" rel="canonical"/> <link href="http://localhost:1300/en/catalogue/category/somecategory/for-kids_1532/?sort_by=newest" hreflang="x-default" rel="alternate"/> <link href="http://localhost:1300/fi/catalogue/category/somecategory/for-kids_1532/?sort_by=newest" hreflang="fi-FI" rel="alternate"/> <link href="http://localhost:1300/sv/catalogue/category/somecategory/for-kids_1532/?sort_by=newest" hreflang="sv-SE" rel="alternate"/> <link href="http://localhost:1300/sv/catalogue/category/somecategory/for-kids_1532/?sort_by=newest" hreflang="sv-AX" rel="alternate"/> <link href="http://localhost:1300/en/catalogue/category/somecategory/for-kids_1532/?sort_by=newest" hreflang="en" rel="alternate"/> Desired Outcome: Include a self-referencing hreflang tag for the current language. Assumptions: The absence of a self-referencing hreflang tag might be due to the link href containing parameters. Issue 2: Conflicting hreflang and rel=canonical Description: Issue Type: Conflicting hreflang and rel=canonical. Page URLs: Page URL 1 Page URL 2 Current Hreflang Values: <link href="http://localhost:1300/en/blog/1072/" rel="canonical"/> <link href="http://localhost:1300/en/blog/1072/" hreflang="x-default" rel="alternate"/> <link href="http://localhost:1300/fi/blog/1072/" hreflang="fi-FI" rel="alternate"/> <link href="http://localhost:1300/sv/blog/1072/" hreflang="sv-SE" rel="alternate"/> <link href="http://localhost:1300/sv/blog/1072/" hreflang="sv-AX" rel="alternate"/> <link href="http://localhost:1300/en/blog/1072/" hreflang="en" rel="alternate"/> Desired Outcome: Ensure consistency between hreflang and rel=canonical URLs. Assumptions: Conflicting hreflang and rel=canonical issue might be due to the same URL marked as canonical and alternate. Additional Context: Code Snippets: base.html: {% with canonical_url=request.build_absolute_uri %} <link rel="canonical" href="{% canonical_url request %}" /> {% endwith %} {% for alt in ALTERNATES %} <link rel="alternate" href="{{ alt.href }}{% if request.GET %}?{{ request.GET.urlencode }}{% endif %}" hreflang="{{ alt.hreflang }}" /> {% endfor %} context_processor.html: def i18n_alternates(request): """ Generate hreflang alternate URLs for … -
How implement channels with different chats
enter image description here I have a Django project in which I need to implement a chat, as in the photo. I tried using django channels, but I was able to implement one specific chat. How to properly implement a chat of this format. Maybe socketio or something like that would be more optimal. Thanks -
Django Rest Framework for blog site
I want to create a simple blog site using django where i also want to shere my product to show only. Is it needed to install Django Rest Framework here? Can i see my website on mobile without rest framework? I am expecting your help here. -
django.db.utils.OperationalError: connection to server at "localhost" (::1), port 5432 failed: FATAL: role "postgres" does not exist
django.db.utils.OperationalError: connection to server at "localhost" (::1), port 5432 failed: FATAL: role "postgres" does not exist This error is I can not slove. please give me a hint. I can not try anything because the issue has a lot. But, I try every thing Ican not solve -
Cannot resolve keyword 'average_rating' into field
Here is my models and views file. class Article(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='articles') caption = models.CharField(max_length=250) @property def average_rating(self): return self.articlecomments.all().aggregate(Avg('rate')).get('rate__avg', 0.00) class ArticleComment(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) article = models.ForeignKey(Article, on_delete=models.CASCADE, null=True, blank=True, related_name='articleratings') author = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, related_name='articleratings_author') rate = models.IntegerField(default='0') class ArticleByCategoryViewSet(viewsets.ModelViewSet): permission_classes = (IsAuthenticated,) queryset = Article.objects.all().order_by('-average_rating') serializer_class = ArticleSerializer pagination_class = StandardResultsSetPagination What I try to do is sort the articles by its rating but it does not work. It gives me this error: raise FieldError("Cannot resolve keyword '%s' into field. " django.core.exceptions.FieldError: Cannot resolve keyword 'average_rating' into field. Choices are:...... I used it as a property.How can I solve this problem?Is there an alternative way? -
CORS Errors while accessing the REST API in REACT
I have installed the django-cors-headers and configured the following in my settings.py ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'atpdocuments', 'rest_framework', 'rest_framework.authtoken', 'corsheaders', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ALLOWED_ORIGINS = [ "http://localhost:3000", # or specific domains # other allowed origins... ] After adding this also im not able make a request from React. Getting the following error Access to fetch at 'http://127.0.0.1:8000/api/login' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'. I have tried the above methods but still iam getting the cors errors. -
How to order a Django queryset by two separate columns
I have a ‘Entry’ model with two columns, ‘wins’ and ‘points’. Right now I am ordering them by wins but when there are two people with the same amount of wins I would like to fall back on points as a tie breaker. Is there a way to order by 2 separate data points? -
Video Title space giving Directory not found error
I am working on a downloader but while downloading a video (eg. Staying Alive) The space between Staying and Alive is giving directory error I tried to fix using methods given by chatgpt but it doesnt work for my case def download_video(video_url, download_path, resolution='720p'): video = YouTube(video_url) stream = video.streams.filter(res=resolution, file_extension='mp4').first() if stream: print(f"Downloading: {video.title}") file_path = os.path.join(download_path, f"{slugify(video.title)}.mp4") stream.download(download_path) return file_path else: print(f"Error downloading: {video.title}") return None def create_zip(zip_filename, files_to_zip): with zipfile.ZipFile(zip_filename, 'w') as zip_file: for file_path in files_to_zip: #each file to the zip file print(file_path) file_name = os.path.basename(file_path) zip_file.write(file_path, file_name) def download_files(request, downloaded_files): base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) filename = '/test.zip' filepath = base_dir + '/media' + filename create_zip(filepath, downloaded_files) thefile = filepath filepath = os.path.basename(thefile) chunk_size = 8192 response = StreamingHttpResponse(FileWrapper(open(thefile, 'rb'), chunk_size), content_type=mimetypes.guess_type(thefile)[0]) response['Content-Length'] = os.path.getsize(thefile) response['Content-Disposition'] = "Attachment;filename=%s" % filename return response How exactly I have to do the fix? -
annotate() + distinct(fields) is not implemented. Python Django Error
When I try to use annotate with distict following error occurs NotImplementedError at /guest/book/1/checkavailability/ annotate() + distinct(fields) is not implemented. Request Method: GET Request URL: http://localhost:8000/guest/book/1/checkavailability/?start_date=2023-11-19&end_date=2023-11-28 Django Version: 4.2.7 Exception Type: NotImplementedError Exception Value: annotate() + distinct(fields) is not implemented. Exception Location: /home/abk/Desktop/project-qb/django/lib/python3.11/site-packages/django/db/models/sql/compiler.py, line 872, in as_sql Raised during: booking.views.views.RoomsAvailableBetweenSpecificDatesView Python Executable: /home/abk/Desktop/project-qb/django/bin/python Python Version: 3.11.4 Here is my query booked_rooms = RoomBooking.objects.filter( (Q(booking__start_date__range=(lookup_start_date, lookup_end_date)) | Q(booking__end_date__range=(lookup_start_date, lookup_end_date)) | Q(booking__start_date__lt=lookup_start_date, booking__end_date__gt=lookup_end_date)), booking__hotel=self.hotel, booking__guest_status__in=[ settings.NOT_CHECKED, settings.CHECKED_IN], ).select_related('booking', 'room').exclude(room__is_deleted=True).distinct('room__room_number').values(room_type=F('room__room_type')).annotate(count=Count('room__room_type')).order_by('room__room_type') Here is my model class RoomBooking(models.Model): booking = models.ForeignKey("Booking", on_delete=models.CASCADE) room = models.ForeignKey("Room", on_delete=models.CASCADE) class Room(models.Model): room_number = models.CharField(max_length=25) hotel = models.ForeignKey("Hotel", on_delete=models.CASCADE) room_type = models.CharField(max_length=25) rate = models.IntegerField(validators=[MinValueValidator(0)]) is_deleted = models.BooleanField(default=False) class Booking(models.Model): NOT_CHECKED = 'not checked' CHECKED_IN = 'checked in' CHECKED_OUT = 'checkout out' CANCELLED = 'cancelled' GUEST_STATUS = [ (NOT_CHECKED, "NOT_CHECKED"), (CHECKED_IN, "CHECKED_IN"), (CHECKED_OUT, 'CHECKED_OUT'), (CANCELLED, "CANCELLED") ] hotel = models.ForeignKey('Hotel', on_delete=models.CASCADE) guest = models.ForeignKey( "authentication.User", on_delete=models.CASCADE, null=True) total_rooms = models.IntegerField( default=1, validators=[MinValueValidator(1)]) start_date = models.DateTimeField() end_date = models.DateTimeField() booked_date = models.DateTimeField(auto_now_add=True) guest_status = models.CharField( max_length=15, choices=GUEST_STATUS, default=NOT_CHECKED) How could I make the same query without the issue ? After some googling I've found that if we try to call distinct on an annotated query, it sometimes works, sometimes get's … -
Async/Await Fetch POST parameters for text/html
How do I POST parameters for content type text/html without sending it as an object? Posting using body : {} or body: JSON.Stringify({}) posts data an object. I want data to be posted as individual values. $(document).on('click', '#update', async () => { try { const response = await fetch("/getupdate",{ method:'POST', headers:{ 'Content-Type':'text/html; charset=utf-8' }, body: JSON.stringify({ "country": getCookie("country"), "city": getCookie("city").replace(/"/g, ""), "action": 1, "csrfmiddlewaretoken": $('input[name=csrfmiddlewaretoken]').val() }), }); } catch (error){ console.log(error) } }); Got an object instead of individual values - { "country": "US", "city": "Miami", "action": 1, "csrfmiddlewaretoken": "iLoS4Bsgdyc6EhOtQKiiXrIqr9S1eojdhdyEeClA8qI5ei2WpfQQu1JrduLrbndndR" } Expecting individual values - "country": "US", "city": "Miami", "action": 1, "csrfmiddlewaretoken": "iLoS4Bsgdyc6EhOtQKiiXrIqr9S1eojdhdyEeClA8qI5ei2WpfQQu1JrduLrbndndR" -
Django and Docker image (Postgres): could not translate host name "db" to address
I am trying to run a django project using a database created on a docker image but I fail with grace all over again. Let me show you my error when I use > python manage.py migrate: System check identified some issues: WARNINGS: ?: (staticfiles.W004) The directory 'D:\2xProjects\Python\ExploreHub\explore_hub\static' in the STATICFILES_DIRS setting does not exist. Traceback (most recent call last): File "D:\2xProjects\Python\ExploreHub\.dj-env\Lib\site-packages\django\db\backends\base\base.py", line 289, in ensure_connection self.connect() File "D:\2xProjects\Python\ExploreHub\.dj-env\Lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "D:\2xProjects\Python\ExploreHub\.dj-env\Lib\site-packages\django\db\backends\base\base.py", line 270, in connect self.connection = self.get_new_connection(conn_params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\2xProjects\Python\ExploreHub\.dj-env\Lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "D:\2xProjects\Python\ExploreHub\.dj-env\Lib\site-packages\django\db\backends\postgresql\base.py", line 275, in get_new_connection connection = self.Database.connect(**conn_params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\2xProjects\Python\ExploreHub\.dj-env\Lib\site-packages\psycopg2\__init__.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ psycopg2.OperationalError: could not translate host name "db" to address: No such host is known. The above exception was the direct cause of the following exception: Traceback (most recent call last): File "D:\2xProjects\Python\ExploreHub\explore_hub\manage.py", line 22, in <module> main() File "D:\2xProjects\Python\ExploreHub\explore_hub\manage.py", line 18, in main execute_from_command_line(sys.argv) File "D:\2xProjects\Python\ExploreHub\.dj-env\Lib\site-packages\django\core\management\__init__.py", line 442, in execute_from_command_line utility.execute() File "D:\2xProjects\Python\ExploreHub\.dj-env\Lib\site-packages\django\core\management\__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "D:\2xProjects\Python\ExploreHub\.dj-env\Lib\site-packages\django\core\management\base.py", line 412, in run_from_argv self.execute(*args, **cmd_options) File "D:\2xProjects\Python\ExploreHub\.dj-env\Lib\site-packages\django\core\management\base.py", line 458, in execute output = self.handle(*args, **options) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\2xProjects\Python\ExploreHub\.dj-env\Lib\site-packages\django\core\management\base.py", line 106, … -
Django, Nginx, Gunicorn: 400 Bad Request when accessing AWS EC2 instance externally
I am encountering a "400 Bad Request" error when attempting to access my Django application externally on an AWS EC2 instance. Notably, the application functions correctly when accessed locally on the server. This issue arises when using Nginx as a reverse proxy and Gunicorn as the application server. For example when I'm on the ec2 instance and uses the command "curl --unix-socket /run/gunicorn.sock localhost/events/" I get the right data from the database. In the chrome console I can see this error: "The Cross-Origin-Openor-Policy header has been ignored, because the URL's origin was untrustworthy. It was defined either in the final response or a redirect. Please deliver the response using the HTTPS protocol. You can alos use the localhost origin instead." I have looked at the nginx logs and I don't get any information from that. I have tried many different solutions and looked and followed various tutorials and documentations, but it still won't work. I will add here some of the files that might be needed in figuring out this problem, and ask if you need more information, or can give me any direction of what I could try. tutorials I have looked at: https://www.youtube.com/watch?v=7O1H9kr1CsA https://medium.com/@madhankm/set-up-django-with-nginx-and-gunicorn-on-ubuntu-20-04-lts-8a02748435fe, settings.py (The important parts) … -
Django Project on Linode Server not pointing to the right PostgreSQL database
I am new to django and just uploaded a project to Linode through Nginx server. I am facing a very weird problem. When I first uploaded the project, the PostgreSQL database was "pinkgiraffedb". However, after encountering some problem on migration, I decided to create a new database called "mydb" and pull data from there. Unfortunately, the project is still pointing towards the old database. I have tried to solve the problem, but none worked so far. What I am doing wrong? I have restarted nginx server several times but it didn't work. Changed Debug from TRUE to False in settings.py but it didn't work. Any suggestion would be on how to solve it would be appreciated. Thank you in advance. Previously, I deleted the whole "pinkgiraffedb" database but then I started to see operational/programming error on Django admin. So created the DB again and ran migration. Restarted server several times. 'mydb' table migrations list of databases settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'mydb', 'USER': 'postgres', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '5432', } }``` -
How to return actual data from a serializer Django
I'm trying to test a register_customer api endpoint I'm working on on Django, but I'm getting the the user_id as a response instead of the actual user's data. ` { "data": { "user_id": 15 }, "message": "Thank you for registering" }` I have a Customer model that has a OneToOne relationship with the CustomUser ` class Customer(models.Model): user_id = models.OneToOneField(CustomUser, on_delete=models.CASCADE)` And here's my serializer: ` from rest_framework import serializers from .models import Customer, CustomUser import logging logger = logging.getLogger(name) class UserSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True, required=True) confirm_password = serializers.CharField(write_only=True, required=True) class Meta: model = CustomUser fields = [ "email", "first_name", "last_name", "phone_number", "password", "confirm_password", ] def validate_password(self, value): # Password must be at least 8 characters long if len(value) < 8: raise serializers.ValidationError( "Password must be at least 8 characters long." ) # Check for at least one uppercase character if not any(char.isupper() for char in value): raise serializers.ValidationError( "Password must contain at least one uppercase character." ) # Check for at least one special character special_characters = "!@#$%^&*()-_=+[]{}|;:'\",.<>/?" if not any(char in special_characters for char in value): raise serializers.ValidationError( "Password must contain at least one special character." ) # Check for at least one number if not any(char.isdigit() for … -
django autocomplete for filtered queryset
I am trying to customize django-admin when working with django rest framework. I am adding Article object, which may have Participants (users who contributed to writing the article), and I want to create autocomplete when choosing users, but display only Users who are active and team_members. For now, all Users get displayed despite filtering. Here is my code: class ParticipantInlineForm(forms.ModelForm): class Meta: model = Participant fields = '__all__' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) user_field = self.fields['user'] if hasattr(user_field, 'queryset'): user_field.queryset = user_field.queryset.filter(is_active=True, is_team_member=True) class ParticipantInline(admin.TabularInline): model = Participant form = ParticipantInlineForm autocomplete_fields = ['role', 'user'] # here! Here are my User and Participant models: class User(AbstractUser): """ Расширение стандартной модели пользователя Django """ patronymic = models.CharField(max_length=100, null=True, blank=True, verbose_name="Отчество") date_joined = models.DateField(null=False, default=timezone.now, verbose_name="Дата регистрации") profile_info = models.CharField(max_length=500, null=True, blank=True, verbose_name="Биография") profile_picture = models.ImageField(upload_to='images/users/', null=True, default='images/alt_image.jpg', verbose_name="Аватар") is_team_member = models.BooleanField(default=False, verbose_name="Член команды") full_name = models.CharField(max_length=255, blank=True, verbose_name="Полное имя") # sort of caching for quick search article_participated = models.ManyToManyField('Article', through='Participant', related_name='parts', verbose_name="Участники в создании") favourites = models.ManyToManyField('ContentObject', through='Favourite', related_name='favs', verbose_name="Избранное") class Participant(models.Model): """ Какую конкретно роль пользователь сыграл при создании """ user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="Пользователь") article = models.ForeignKey(Article, on_delete=models.CASCADE, verbose_name="Статья") role = models.ForeignKey(Role, null=True, blank=True, on_delete=models.SET_NULL, verbose_name="Фактическая роль") With … -
Docker Django Gunicorn Nginx "This site can’t be reached" error
I have django project. I want to do deployment on AWS. I have docker-compose-prod.yml file: version: "3.8" services: api: image: meduzzen-backend-api container_name: django entrypoint: ./start_prod.sh tty: true stdin_open: true volumes: - .:/code - ./code:/apps - static:/static expose: - "8000" ports: - "8000:8000" depends_on: - postgres-db - redis env_file: - .env networks: - api-db-redis celery: image: meduzzen-backend-api container_name: celery command: celery -A meduzzen_backend worker -l INFO volumes: - .:/code - ./code:/apps depends_on: - postgres-db - redis env_file: - .env networks: - api-db-redis celery-beat: image: meduzzen-backend-api container_name: celery-beat command: celery -A meduzzen_backend beat -l INFO --scheduler django_celery_beat.schedulers:DatabaseScheduler volumes: - .:/code - ./code:/apps depends_on: - postgres-db - redis env_file: - .env networks: - api-db-redis flower: image: mher/flower:latest container_name: flower command: celery --broker=redis://redis_cache:6379/0 flower ports: - "5555:5555" depends_on: - celery - celery-beat - redis networks: - api-db-redis postgres-db: image: postgres:latest container_name: postgres_db ports: - "5432:5432" volumes: - data:/var/lib/postgresql/data env_file: - .env networks: api-db-redis: # Have access the database using pgadmin4 ipv4_address: 172.24.0.6 pg-admin: image: dpage/pgadmin4:latest container_name: pg_admin env_file: - .env ports: - "5050:5050" networks: - api-db-redis redis: image: redis:latest container_name: redis_cache ports: - "6379:6379" networks: - api-db-redis nginx: image: meduzzen-backend-nginx container_name: nginx volumes: - static:/static - ./nginx-conf.d:/etc/nginx/conf.d ports: - "80:80" depends_on: - api volumes: … -
Pressure Notifications Not Displaying in bidvertiser
I am having an issue with the pressure notifications on my website. I have added the sw.js file to the root directory of my site, and I have selected a location for the notifications to display. However, when I open the site, only the text "by BidVertiser" is displayed in place of the ad. I have checked the following: The site is fully loaded. There is not a lot of activity on the site. There are not a lot of visitors to the site. I have also tried the following: Using a different location for the notifications. Using different sizes and types of images for the notifications. I am still having the same issue. -
Django post save on user registration question
I have a custom user model and I am using all-auth to register users. I am attempting to use a post save signal to auto assign new users to a specific group based on their email domain. For example, I user with the email joe@domainone.com might be assigned to group 2 based on the @domainone.com email. I also have a model that stores email domains and associated groups. So far it doesn't look like the signal is being called when I register a new user via and all-auth form at http://localhost:8000/accounts/signup/. Any ideas to fix this? Models: from django.contrib.auth.models import AbstractUser from django.db import models from allauth.account.models import EmailAddress from django.contrib.auth.models import Group class CustomUser(AbstractUser): age = models.PositiveIntegerField(null=True, blank=True) preferred_name = models.CharField(null=True, blank=True, max_length=75) # adds model for entering company email domains and assigning groups class EmailDomainGroup(models.Model): email_domain = models.CharField(max_length=255, unique=True) group = models.ForeignKey(Group, on_delete=models.CASCADE) def __str__(self): return self.email_domain apps.py from django.apps import AppConfig class AccountsConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'accounts' ready_executed = False # Add this flag def ready(self): if not self.ready_executed: import accounts.adapter import accounts.signals print('signal called') import accounts.admin self.ready_executed = True # Set the flag to True after executing the logic signals.py # accounts/signals.py from django.db.models.signals … -
How to make only the last few characters show in a CharField for a django model
I have a model with a secret key field: class Settings(model.Models): secret_key = models.CharField(max_length=100) I do not want this field to be seen publicly. How do I make only the last few characters show and star out or hide the rest.