Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Delete record using class based view in django
How to delete record using class based view ? I am using below view. class UserDeleteView(DeleteView): model = User success_url = reverse_lazy('dashboard') template_name = 'delete_user_confirm.html' Is it possible to avoid template_name = 'delete_user_confirm.html' ? -
Deploying Django Rest Framework Based Microservices That Communicate with Token Authentication
I am developing a docker based application. The application has two components. A core component (CORE) and an interface component (INTERFACE). The world communicates with the INTERFACE component. The INTERFACE component CRUD the database in the CORE component. The ultimate aim of this setup is that I might have different interface components. Also, it applies separation of concerns. When deploying the app. Using docker compose I will establish the communication between the two applications. However, the INTERFACE should communicate with the CORE using Token Based Authentication. My question is how to generate a Token for the INTERFACE inside the CORE during launch. I tried developing a script that generates the token. But it turns out the script requires some Environmental variables that Django Shell sets. -
How to display image in Django admin?
I am currently new to Django and web development and I was wondering if how can I display the image in Django admin? Currently it just shows this: My Django admin I also attached my codes for my urls and models for your reference: models.py models.py urls.py urls.py settings.py settings.py PS: I was following an online tutorial and I wasn't really sure what i did wrong. Thank you. How can the image be displayed in django admin. -
ModuleNotFoundError: No module named 'users.routing.websocket_urlpatterns'; 'users.routing' is not a package
I am tring to setup realtime connection between User Dashboard and Admin Dashboard for Notifications. This is my backend/asgi.py import os from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter, URLRouter from channels.auth import AuthMiddlewareStack from users.routing import websocket_urlpatterns os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backend.settings') application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": AuthMiddlewareStack( URLRouter( websocket_urlpatterns ) ), }) backend/urls.py from django.contrib import admin from django.urls import path, include, re_path urlpatterns = [ path('admin/', admin.site.urls), path('api/users/', include('users.urls')), re_path(r'^ws/', include('users.routing.websocket_urlpatterns')), ] users/routing.py from django.urls import re_path from . import consumers websocket_urlpatterns = [ re_path(r'ws/notifications/', consumers.NotificationConsumer.as_asgi()), ] users/consumers.py import json from channels.generic.websocket import AsyncWebsocketConsumer class NotificationConsumer(AsyncWebsocketConsumer): async def connect(self): self.group_name = 'notifications' # Join room group await self.channel_layer.group_add( self.group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): # Leave room group await self.channel_layer.group_discard( self.group_name, self.channel_name ) async def receive(self, text_data): data = json.loads(text_data) message = data['message'] # Send message to room group await self.channel_layer.group_send( self.group_name, { 'type': 'notification_message', 'message': message } ) async def notification_message(self, event): message = event['message'] # Send message to WebSocket await self.send(text_data=json.dumps({ 'message': message })) When I Test importing in Django Shell it works (venv) lucy@lucy:~/staking_platform$ python manage.py shell Python 3.8.10 (default, Nov 22 2023, 10:22:35) [GCC 9.4.0] on linux Type "help", "copyright", "credits" or … -
How to serialize a related model at depth 2 without serializing intermediate model at depth 1?
I have three models with foreign keys in this direction Order -> Customer -> User. I would like to write a view set for orders that serializes the corresponding user without the intermediate customer. Models: class Order(models.Model): customer = ForeignKey("customers.Customer") class Customer(models.Model): user = ForeignKey("users.User") class User(models.Model): name = CharField(max_length=64) Serializer: class UserSerializer(ModelSerializer): class Meta: model = User fields = ["name"] class OrderSerializer(ModelSerializer): user = UserSerializer(source="customer__user", read_only=True) class Meta: model = Order fields = ["id", "user"] View set: class OrderViewSet(ModelViewSet): queryset = Order.objects.all() serializer_class = OrderSerializer Desired output: [ {"id": 1, "user": {"name": "John"}}, {"id": 2, "user": {"name": "Mary"}}, ] Actual output: [ {"id": 1}, {"id": 2}, ] It works fine if I go via the intermediate customer serializer: class CustomerSerializer(ModelSerializer): user = UserSerializer(read_only=True) class Meta: model = User fields = ["user"] class OrderSerializer(ModelSerializer): customer = CustomerSerializer(read_only=True) class Meta: model = Order fields = ["id", "customer"] but then the output contains the intermediate customer object: [ {"id": 1, {"customer": {"user": {"name": "John"}}}, {"id": 2, {"customer": {"user": {"name": "Mary"}}}, ] -
Could not parse the remainder: '()' from 'topic_files.items()'
I am working on a Django project where I need to display files grouped by topics for a specific submission. Each submission is associated with multiple topics, and each topic can have multiple files. I am encountering an issue when trying to render this in a template. Models: from django.db import models from users.models import UserProfile # Create your models here. class ResearchWork(models.Model): name = models.CharField(max_length=100) description = models.TextField() def __str__(self): return self.name class Topic(models.Model): research_work = models.ForeignKey(ResearchWork, related_name='topics', on_delete=models.CASCADE, null=True) name = models.CharField(max_length=100) def __str__(self): if self.research_work is None: return f"Unassigned - {self.name}" return f"{self.research_work.name} - {self.name}" class Assignment(models.Model): student = models.ForeignKey(UserProfile, related_name='student_assignment', on_delete=models.CASCADE) teacher = models.ForeignKey(UserProfile, related_name='teacher_assignment', on_delete=models.CASCADE) is_accepted = models.BooleanField(default=False) # charfield is_reviewed = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) text = models.TextField(blank=True) def __str__(self): return f"Assignment for {self.student.user.username} with {self.teacher.user.username}" class Submission(models.Model): assignment = models.ForeignKey(Assignment, on_delete=models.CASCADE) SEMESTER_CHOICES = ( ('1', 'Semester 1'), ('2', 'Semester 2'), ('3', 'Semester 3'), ('4', 'Semester 4'), ('5', 'Semester 5'), ('6', 'Semester 6'), ('7', 'Semester 7'), ('8', 'Semester 8'), ) semester = models.CharField(max_length=100, null=True, choices=SEMESTER_CHOICES) research_work = models.ForeignKey(ResearchWork, on_delete=models.CASCADE, null=True) created_at = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): research_work_name = "No Research Work Assigned" if self.research_work is None else self.research_work.name return f"{research_work_name} - for student {self.assignment.student.user.username} … -
cx_Oracle DatabaseError: DPI-1047
I'm trying to run my Django application in Docker, but I'm getting an error: cx_Oracle.DatabaseError: DPI-1047: Cannot locate a 64-bit Oracle Client library: "/root/lib/oracle/instantclient_23_4/libclntsh.so: cannot open shared object file: No such file or directory" The application itself runs on PostgreSQL, but also has a connection to Oracle OS: Ubuntu Server I installed instantclient, and created an env variable via ~/.bashrc using the command: export LD_LIBRARY_PATH=/root/lib/oracle/instantclient_23_4:$LD_LIBRARY_PATH, and added an initialization line in the python file: cx_Oracle.init_oracle_client(lib_dir="root/lib/oracle/instantclient_23_4"), but I still get the above error. If I run the file directly: python3 omega_db.py, the script works fine and shows the database connection, but if I run it through docker-compose up, I get the error. instantclient -
Showing custom error messages but not showing error which i have defined DRF
I am creating a Registration API using DRF but I am getting an custom error message like "Custom user with this email already exists" Please reivew the code below View.py from rest_framework import generics from rest_framework import status from rest_framework.permissions import AllowAny from .serializers import RegisterSerializer from projectname.utils import custom_response class RegisterView(generics.CreateAPIView): serializer_class = RegisterSerializer permission_classes = [AllowAny] def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) if serializer.is_valid(): user = serializer.save() response_data = { "username": user.username, "first_name": user.first_name, "last_name": user.last_name, "email": user.email, "user_type": user.user_type, } return custom_response( success=True, message="User registered successfully", data=response_data, status_code=status.HTTP_201_CREATED ) else: return custom_response( success=False, message="User registration failed", errors={"error_message": list(serializer.errors.values())}, status_code=status.HTTP_400_BAD_REQUEST ) serializer.py from rest_framework import serializers from .models import CustomUser class RegisterSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True) class Meta: model = CustomUser fields = ('email', 'username', 'first_name', 'last_name', 'user_type', 'password') def validate(self, data): required_fields = ['email', 'username', 'first_name', 'last_name', 'user_type', 'password'] errors = {} for field in required_fields: if field not in data or not data[field].strip(): errors[field] = f"{field.replace('_', ' ').capitalize()} is required." if CustomUser.objects.filter(email=data.get('email', '')).exists(): errors['error_message'] = "Email already exists." if CustomUser.objects.filter(username=data.get('username', '')).exists(): errors['error_message'] = "Username already exists." if errors: raise serializers.ValidationError({"error_message": list(errors.values())}) return data def create(self, validated_data): user = CustomUser.objects.create_user( email=validated_data['email'], username=validated_data['username'], first_name=validated_data['first_name'], last_name=validated_data['last_name'], user_type=validated_data['user_type'], password=validated_data['password'] … -
How to integrate third party SOAP API (product data) with an eCommerce store?
I have access to a SOAP web service with over 40 thousand products and need an eCommerce store to connect the web service. The trick is that it cannot store the data locally in the eCommerce platform, and every time there is a search request, the SOAP web service must be called. Which platform would work in this case (Shopify, BigCommerce, Adobe Commerce, etc), or does it require a website built from scratch using a framework such as Django? I tried using Shopify a while back, but I couldn't find a way for it to work without storing products. -
Django apscheduler running thrice at one time
I have a scheduler code that running every minute to send notifications using fcm... I used print statements to know where the issue is, it came to be at scheduler side I saw that it was getting called thrice. I called the backgroundscheduler in apps.py, that generally runs twice so I tried with: urls, admin, models & views.py but strangely those files were also printing twice. I can't understand why... So I used File lock in apps.py: import os from django.apps import AppConfig import threading class MobileapisConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'MobileApis' _lock = threading.Lock() _initialized = False def ready(self): with self._lock: if not self._initialized: lock_file = '/tmp/scheduler_initialized.lock' if not os.path.exists(lock_file): self.initialize_schedulers() with open(lock_file, 'w') as f: f.write('initialized') self._initialized = True def initialize_schedulers(self): from . import seduler seduler.start() seduler.start1() seduler.start2() seduler.start3() print('Schedulers started') but that doesn't seems to work even the file is created with text... The scheduler logs are 3+ times at the same time... What's The best place that will call scheduler only one time? -
Technologies used in GERMANY [closed]
what should I learn that is mostly used? Djnago or NodeJS? I have a little experience with both of them but here I'm talking about learning one in depth you know? This is just a life question it isn't a code that didn't run😂 -
Raise message from a class in models.py in django
I have models class for Inventory Transfers or Issues Details. In the save method, i am accessing current stock level in a different model class for WarehouseStockStatus. I wish to message to the user from models.py if transferred or issued quantity exceeds current inventory levels. I am using django admin screens only. Print method will not work. Raise Validation error doesn't work. Also Messages will not work as it works only in views and templates where you have Request object. Any suggestions on how to proceed ? I expect to print the message to the user. -
Why are my ECS tasks pausing for six hours on startup?
I have a Fargate ECS task that runs a Django app via gunicorn. That task successfully started a few weeks ago and had no issues. It was then replaced by routine AWS maintenance/updates. The replacement task started successfully, but it paused during the execution of the entry point script for longer than the load balancer healthcheck grace period. The task of course failed the health check and that caused ECS to again stop and replace the task. This then happened endlessly, with each replacement task having the same issue. There have been no code changes involved in the Docker image used for the task. I obviously expected no change to the ECS task and that it would run as it did before. After implementing the ECS task deployment circuit breaker to stop the endless task replacement cycle, I left the paused (but running) ECS task alone for a while. I realized from the Cloudwatch logs that the task pauses for exactly six hours each time while in the middle of running the entry point script. Here's the entry point script: set -euo pipefail cd /home/viewer/projects/server || exit export DJANGO_SETTINGS_MODULE=viewer_server.settings export PYTHONPATH="/home/viewer/projects/server/" echo "DJANGO_SETTINGS_MODULE and PYTHONPATH set." python manage.py makemigrations python … -
Create CSV file from converting Json Output into CSV either using Pandas or CSV/Json Library in Django
I am struggling to figure out how to get my already made Json output and also create a csv file from that output. For more clarification, I have created a json file by using write, but I am unsure on how to also create a CSV file during the same process. Maybe I am just not inputting the CSV code in the correct area, or if Django needs some other form of method to process that request. utils.py import json import os import pandas as pd from django.utils import timezone from django.http import HttpResponse from django.db.models import Q from api.models import BlockedList def get_ip_list_json() -> dict: json_response = { "version": "", "description": "", "objects": [ { "name": "", "id": "", "description": "", "ranges": ["2.2.2.2"], }, ], } group_map = {} for ip in BlockedList.objects.filter( Q(end_date__isnull=True) | Q(end_date__gte=timezone.now()) ).select_related("group"): group_id = str(ip.group.id) if group_id not in group_map: group_map[group_id] = { "name": ip.group.name, "id": ip.group.group_id, "description": ip.group.description, "ranges": [], } group_map[group_id]["ranges"].append(ip.address) json_response["objects"] = list(group_map.values()) return json_response def create_ip_file(): try: base_dir = "C://Users/Steven/Desktop" filename = "blocklist.json" full_path = os.path.join(base_dir, filename) with open(full_path, "w") as f: f.write(json.dumps(get_ip_list_json(), indent=4)) except Exception as e: print(e) That is my above code where I create my Json output … -
redis and celery tasks works fine without docker, but using docker the tasks status is always in pending state in my django app
I am trying to write a background task to count the total number of posts. It works fine when I start redis server and celery without using docker but using docker, the tasks state is always pending. To confirm if the task is working, I tried to do it without using docker and it worked fine but as soon I can run it using docker the task stops working. Below is the code I tried: Dockerfile FROM python:3.8-slim-buster ENV PYTHONUNBUFFERED=1 WORKDIR /code COPY requirements.txt requirements.txt RUN pip3 install -r requirements.txt RUN pip3 install ipdb COPY . /code/ docker-compose.yml version: '3' services: db: image: postgres:13 volumes: - postgres_data:/var/lib/postgresql/data environment: POSTGRES_DB: myproject POSTGRES_USER: myprojectuser POSTGRES_PASSWORD: password networks: - mynetwork web: build: . command: bash -c " python manage.py migrate && python manage.py runserver 0.0.0.0:8000 " volumes: - .:/code ports: - "8000:8000" depends_on: - db - es - redis - celery environment: - DATABASE_URL=postgres://myprojectuser:password@db:5432/myproject stdin_open: true # Keep stdin open tty: true # Enable TTY networks: - mynetwork es: image: docker.elastic.co/elasticsearch/elasticsearch:8.13.0 volumes: - esdata01:/usr/share/elasticsearch/data ports: - 9200:9200 environment: - discovery.type=single-node - xpack.security.enabled=false networks: - mynetwork redis: image: redis:latest container_name: rd01 command: redis-server ports: - '6379:6379' networks: - mynetwork celery: build: . command: celery … -
What I can do to get the approximated price for the cloud service
I have an application to run in a server in a specific domain and I want to know how much I'm gonna pay each month in Heroku. It's a website running in python/django to solve the schedulling problem. My user will log-in and fill the form and run the solution. After running the solution they will get the results via a specific page. Is this enough information so I can get an approx. price to pay? If not, what other information I need to reveal in order to get this estimate? I tried to get the estimate using the Heroku calculator, but I got an estimate of $250 dollars per month. I included in the calculator the advanced plan with performance M. I'm not sure if that is all or not. -
Django cannot be recognized
I am doing a coding course where I'll be learning all about Django. From this, it is correct to assume that I am new to everything Django. In the course, I am at the point where I must install Django. The instructor said to use my computer's terminal to install Django. He also said to install Django 2.0.2, as that is the version he would be using. The command he had me use was pip3 install django==2.0.2. Everything installed normally, but when I tried to open Django with Django-admin, I was met with this error: django: The term 'django' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. I tried uninstalling Django, then installing the latest version using: pip install Django, but even though everything installed perfectly, I am still met with the same error when I try to start a new project with Django. I was also given alternate commands that the Bing AI Copilot gave me, such as: python -m Django startproject first_project, but that produced the same type of error. … -
uWSGI: trying to figure out why my application goes frequently timeout
I'm using uWSGI into a Docker container to serve a Django application which is encountering serious timeouts problems almost once per day. For this reason, I am debugging my uWSGI settings, expecially the cheaper settings. Today I had timeouts errors at about 06:30 UTC time, and these are the uWSGI logs in the meantime: 2024-06-12 06:03:02 - [busyness] 1s average busyness is at 100% but we already started maximum number of workers available with current limits (8) 2024-06-12 06:03:03 - [busyness] 1s average busyness is at 100% but we already started maximum number of workers available with current limits (8) 2024-06-12 06:03:04 - [busyness] 1s average busyness is at 100% but we already started maximum number of workers available with current limits (8) 2024-06-12 06:03:05 - [busyness] backlog was non-zero for 60 second(s), spawning new worker(s) 2024-06-12 06:03:05 - [busyness] 18 requests in listen queue but we are already started maximum number of workers (8) 2024-06-12 06:03:06 - [busyness] 1s average busyness is at 100% but we already started maximum number of workers available with current limits (8) 2024-06-12 06:03:07 - [busyness] 1s average busyness is at 100% but we already started maximum number of workers available with current limits … -
How to retireve details by related onetoonefield in Djang Rest Framework?
Hello consider the following simple scenario: class User(models.Model): email = ... fname = ... lname = ... class UserPreferences(models.Model): user = models.OneToOneField(User, to_field="email", ...) preferences = ... Now the UserPreferences table in the db contains id, preferences, user_id. I want to get the preferences of a user by email. I want to use RetrieveAPIView. How to do this? What is the role of to_field if it stores the id of user anyway? I tried the following: class UserPreferencesRetrieveView(generics.RetrieveAPIView): serializer_class = UserPreferencesSerializer queryset = UserPreferences.objects.all() lookup_field = "email" I got the error: Cannot resolve keyword 'email' into field. Choices are: id, preferences, user, user_id -
Storing clients card Django
I need to store customer loyalty cards. It should be flexible. I have several variants of cards with different discount systems. For example, the card by amount of purchases - > $100 - 5%, > $1000 - 10%, etc. Or by amount of visits - > 10 - 3%, 100 - 10%, etc. Furthermore, it should store the different image for different types of cards and sales amount, for example 5% - silver colour, 10% - gold, etc. I came up with the idea of storing in in database as JSON. Visits for example: schema = {1: {'discount': 5%, image: '....', 'style': {'background': ..., 'foreground': ...}, 2: {'discount': 10%, image: '....', 'style': {'background': ..., 'foreground': ...}, 3: {'discount': 15%, image: '....', 'style': {'background': ..., 'foreground': ...}, } class ABSCard(models.Model): title = field work_place = field .... class Discount(models.Model): type = .... schema = JSONField abscard_id = ABSCard But I'm not sure that storing JSON in PostgreSQL is the best way. -
Prevent async task from being executed before the rest of the code on Django
Please help me here. This is my django admin class: My problem is, the check_sync_available validation is not working properly because the async task sync_development (redis/celery) is being executed BEFORE the requests.get according to the logs, how can I prevent that? I've tried to use transactions.oncommit and lots of other things and nothing works. class CourseAdmin(nested_admin.NestedModelAdmin): class Meta: model = Course fields = '__all__' actions = ["sync_course_development"] def sync_course_development(self, modeladmin, request, queryset): api_url = f'https://lalala.lalala.la/check_sync_available/' response = requests.get(api_url, headers={'Content-Type': 'application/json'}) if response.status_code != 200: modeladmin.message_user(request, f'A sync is already in progress, try again later.', messages.ERROR) return None else: print(f"Sync available: {response.status_code}") for course in queryset: sync_development.apply_async([course.id]) modeladmin.message_user(request, f'Courses syncing in background. Please reload the page in a while.', messages.SUCCESS) This is the log so you can see what I'm talking about. Jun 12 18:31:59 ip-xxx-xx-xx-xx celery_worker: [2024-06-12 18:31:59,694: WARNING/ForkPoolWorker-7] Point 765/3802 - Percentage: 19.89245930284848 Jun 12 18:31:59 ip-xxx-xx-xx-xx celery_worker: [2024-06-12 18:31:59,696: WARNING/ForkPoolWorker-7] Point 766/3802 - Percentage: 19.91905538924079 Jun 12 18:31:59 ip-xxx-xx-xx-xx celery_worker: [2024-06-12 18:31:59,698: WARNING/ForkPoolWorker-7] Point 767/3802 - Percentage: 19.945522992123962 Jun 12 18:31:59 ip-xxx-xx-xx-xx web: [2024-06-12 18:31:59 +0000] [5952] [INFO] Booting worker with pid: 5952 Jun 12 18:32:01 ip-xxx-xx-xx-xx web: [2024-06-12 18:32:01 +0000] [5906] [INFO] Autorestarting worker after current request. … -
Centrifugo Django. disconnect after handling command reason="bad request"
I am trying to follow this tutorial: But after following all of the steps I do not see any messages and have this in my centrifugo logs: 2024-06-12 20:42:18 [INF] disconnect after handling command client=5bf22df5-8051-463b-9c41-4a6e9d92865a command=id:6 reason="bad request" user= It seems that it occurs when centrifuge.connect() is executed (in chat.templates.chat.rooms.html file). Here are logs from NGINX container: 192.168.65.1 - - [12/Jun/2024:17:44:26 +0000] "GET /connection/websocket HTTP/1.1" 101 15 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36" 192.168.65.1 - - [12/Jun/2024:17:44:30 +0000] "GET /connection/websocket HTTP/1.1" 101 15 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36" 192.168.65.1 - - [12/Jun/2024:17:44:42 +0000] "GET /connection/websocket HTTP/1.1" 101 15 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36" 192.168.65.1 - - [12/Jun/2024:17:44:44 +0000] "GET /connection/websocket HTTP/1.1" 101 15 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36" 192.168.65.1 - - [12/Jun/2024:17:44:58 +0000] "GET /connection/websocket HTTP/1.1" 101 15 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36" 192.168.65.1 - - [12/Jun/2024:17:45:01 +0000] "GET /connection/websocket HTTP/1.1" 101 15 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 … -
window.addEventListener('scroll', function() {
I'm working on the front end through Django WebFramework and PyCham, but infinite scrolls are not properly applied It is a page that fetches and displays public data APIs. Even if the scroll is stuck to the floor, more content does not come out. my html templates {% extends 'base.html' %} {% load static %} {% block content %} <section> <div class="mainpage_content_container"> <div class="section_wrap"> <div class="slick_container"> <div><img src="{% static 'img/gucciSeoul.jpeg' %}" alt=""></div> <div><img src="{% static 'img/korean_mood1.jpeg' %}" alt=""></div> <div><img src="{% static 'img/white_cow.jpeg' %}" alt=""></div> <div><img src="{% static 'img/colorful.jpeg' %}" alt=""></div> <div><img src="{% static 'img/6.25.jpeg' %}" alt=""></div> <div><img src="{% static 'img/seoulcity.jpeg' %}" alt=""></div> </div> </div> <div class="content_container"> <div class="content_wrap"> <ul> {% for image_info in image_info_list %} <li> <div class="img_wrap"> <img src="{{ image_info.file_url }}" alt="{{ image_info.art_name }}" style="max-width: 300px; min-height: 350px"> <div class="img_info"> <p><strong>작품명 :</strong>{{ image_info.art_name }}</p> <p><strong>일련번호 :</strong>{{ image_info.artCd }}</p> <p><strong>작품가격 :</strong>{{ image_info.price }}</p> </div> </div> </li> {% endfor %} </ul> {% if art_list %} <h2>검색 결과</h2> <ul> {% for art in art_list %} <li> <p>작품 번호: {{ image_info.artCd }}</p> <p>작품명: {{ image_info.art_name }}</p> <p>이미지: {% if art.image_url %} <img src="{{ art.image_url }}" alt="작품 이미지"> {% else %} 이미지 없음 {% endif %} </p> </li> {% endfor %} </ul> {% else … -
Django docker error with Postgres django.core.exceptions.ImproperlyConfigured
Good day. I'm having problems comunicating django app (local) and postgres db (docker ) The db work fine with adminer. But when I try the credentials that I use in adminer... Boom! ...env\Lib\site-packages\django\db\backends\postgresql\base.py", line 29, in raise ImproperlyConfigured("Error loading psycopg2 or psycopg module") django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 or psycopg module SETTINGS DATABASES = { 'default': { 'ENGINE': os.getenv("DB_ENGINE"), 'NAME': os.getenv("DB_NAME"), 'USER': os.getenv("DB_USER"), 'PASSWORD': os.getenv("DB_PASSWORD"), 'HOST': os.getenv("DB_HOST"), 'PORT': os.getenv("DB_PORT") }, 'kettle': { 'ENGINE': os.getenv("DB_ENGINE"), 'NAME': os.getenv("DB_NAME_KETTLE"), 'USER': os.getenv("DB_USER"), 'PASSWORD': os.getenv("DB_PASSWORD"), 'HOST': os.getenv("DB_HOST"), 'PORT': os.getenv("DB_PORT") } } ENV DB_ENGINE='django.db.backends.postgresql' DB_NAME='database' DB_USER='postgres' DB_PASSWORD='1234' DB_HOST='db' DB_PORT='5432' DB_NAME_KETTLE='kettle' ADMINER_PORT=8080 VIRTUAL ENV asgiref==3.8.1 certifi==2024.6.2 cffi==1.16.0 charset-normalizer==3.3.2 cryptography==42.0.8 Django==4.2.3 django-cors-headers==4.2.0 djangorestframework==3.14.0 idna==3.7 psycopg==3.1.19 psycopg2==2.9.6 psycopg2-binary==2.9.6 pycparser==2.22 PyJWT==2.3.0 python-dateutil==2.9.0.post0 python-dotenv==1.0.0 pytz==2024.1 requests==2.31.0 six==1.16.0 sqlparse==0.5.0 typing_extensions==4.12.2 tzdata==2024.1 urllib3==2.2.1 and in my docker , postgres is in the port 5432:5432 -
Objects are displayed below the form field drowdown
I have created a form which is creating a new object of a model in which there is one field which is dropdown as it is a foreign key in model but the objects are also displayed below the field along with the dropdown. Model: class Vehicle(models.Model): type = models.ForeignKey(VehicleType, on_delete=models.CASCADE) number = models.CharField(max_length=10) View: def request_cabbie_upgrade(request): if request.method == 'POST': vehicle_form = VehicleForm(request.POST) if vehicle_form.is_valid(): vehicle = vehicle_form.save(commit=False) vehicle.save() cabbie_request = CabbieRequest(user=request.user, vehicle=vehicle) cabbie_request.save() return redirect('PassengerDashboard') else: vehicle_form = VehicleForm() return render(request, 'users/cabbie_request.html', {'vehicle_form': vehicle_form, 'user': request.user}) Form: class VehicleForm(forms.ModelForm): type = forms.ModelChoiceField(queryset=VehicleType.objects.all(), empty_label="Vehicle Type") class Meta: model = Vehicle fields = ['type', 'number'] Template: {% extends "base.html" %} {% block title %} <title>Cabbie Dashboard</title> {% endblock title %} {% block body %} <div class="container mt-5 pt-5 cabbie-dashboard-container"> <div class="row"> <div class="col-md-12"> <h2>Cabbie Information</h2> <div class="card"> <div class="card-body"> <p><strong>Username:</strong> {{ cabbie.username }}</p> <p><strong>First Name:</strong> {{ cabbie.first_name }}</p> <p><strong>Last Name:</strong> {{ cabbie.last_name }}</p> <p><strong>Email:</strong> {{ cabbie.email }}</p> <p><strong>Phone:</strong> {{ cabbie.phone }}</p> </div> </div> </div> <div class="col-md-12 mt-4"> <h2>Request Cabbie Upgrade</h2> <form method="post"> {% csrf_token %} <div class="form-group"> <label for="id_type">Vehicle Type:</label> {{ vehicle_form.type }} </div> <div class="form-group"> <label for="id_number">Vehicle Number:</label> {{ vehicle_form.number }} </div> <button type="submit" class="btn btn-primary">Submit Request</button> </form> </div> …