Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create a custom UI for admin interface in Django
Okay, I probably couldn't explain the issue in the title very well but I am building a Django app which will have various contributors. These contributors will not have superuser privileges but only some read/write privileges. Right now, I have a custom AdminSite which can be accessed by the Contributors. Here's the code: admin.py class ContributorAdmin(AdminSite): def has_permission(self, request): return request.user.is_active urls.py urlpatterns = [ path('admin/', admin.site.urls), path('contributor/', contrib_admin_site.urls), path('login/', loginview, name='login'), path('logout/', logoutview, name='logout'), #other paths for the app ] This is working as intended and gives the contributors access to the admin interface with limited privileges. However, what I would like to do is create a custom Admin UI (not the built-in Django one) which will be used by the Contributors. As an example, I would like to have a contributor.html in my templates which provides Admin like interface to the contributors but the styling etc. is all customized. Also, I would like to have my login and logout views to redirect to this custom page only. Right now, the login page redirects to ContributorAdmin so my custom logout view becomes useless. Is it possible to do this? Thanks in advance! -
Can I use hash partitioning on a non-primary key column in a PostgreSQL table?
I am trying to replace an existing table with a partitioned version of that table. I want the schema of the new partitioned table to exactly match the existing non-partitioned table so that I can continue to manage the table through Django migrations. My first attempt at creating the new partitioned table looked something like this: CREATE TABLE partition_test ( row_index bigint, id character varying(128) PRIMARY KEY, vendor_id character varying(128) ) PARTITION BY HASH (vendor_id); Which results in the following error: ERROR: unique constraint on partitioned table must include all partitioning columns DETAIL: PRIMARY KEY constraint on table "product_api_partition_test" lacks column "vendor_id" which is part of the partition key. I am looking for a work around that will allow me to partition on vendor_id while keeping row_index as the primary key. I tried modifying the primary key as follows, however, Django requires a primary key and does not support composite primary keys. Therefore, both of these options would result in an inconsistency between the true schema and what Django believes is the schema. CREATE TABLE partition_test ( row_index bigint, id character varying(128), vendor_id character varying(128) PRIMARY KEY (row_index, vendor_id) ) PARTITION BY HASH (vendor_id); CREATE TABLE api_partition_test ( row_index bigint, … -
Django Pagination with Titles Instead of Numbers
I have a lecture view which I have paginated to 1 lecture per page. I have created a separate list of all the lectures which I want to use as a navigation side bar to the different lectures. I want that side bar to display the lecture titles as links and not numbers. <ul class=""> {% for pg in lecture_single.paginator.page_range %} {% for lecture_x in lecture_single %} <li> <a href="?page={{ pg }}" class="btn">{{ lecture.title }}</a> </li> {% endfor %} {% endfor %} </ul> I tried using a for loops which did work in creating the links but all the lectures where being presented with the same title as opposed to a specific title for a different page -
How to connect sql server to djangorestframework
So I am working on a project and I have already populated the database in mysql workbench 8.3 and I am building an api so I trying to link my database in sql to my django api and I did it but it looks like the connection in my terminal is a brand new one and it isn't showing my databases that are on workbench so I am tried to change permission and give the connection in my terminal all the permission of root but that didn't really do anything. -
Image not found in my Django Project (only in one of the 2 pages)
i'm trying to display an home image at top of the page but it doesn't work. I have the same image in an other page and it works. also if i hold mouse on image source link on the ide it says me that the path is correct. . : Here is the line code (path in the images): <p><img src="../media/images/home.png" width="30px" alt="home image">HOME</p> -
Is this django test project rejected because of code structure?
Hello Dear Python Community, I created a django test project. the client was rejected with these reasons. Client Feedback 1 The code related to the recipe was looking fine but the use register and login code is good. It seems those API's will not even work well. So, I think we should not move forward. Client Feedback 2 Code structure does not looks good. Authentication is not implemented correctly. So, we should not move forward. Here the test project information Build a Recipe Sharing Platform 1. Framework:- Use Django framework to build the REST APIs. 2. User Authentication:- Implement user authentication and authorization to allow users to sign up, log in, and manage their recipes securely. 3. CRUD Operations: Enable users to perform CRUD operations (Create, Read, Update, Delete) on recipes they own. 4. Recipe Details: Include fields such as title, description, ingredients, preparation steps, cooking time, and serving size for each recipe. 5. Recipe Categories: Allow users to categorize recipes into different categories (e.g., starter, main courses, desserts). 6. Search and Filter: Provide functionality to search and filter recipes based on various criteria (e.g., category, ingredients, cooking time). 7. Rating and Reviews: Allow users to rate and review recipes, … -
Django->IntegrityError when Creating a record with a foreign key assign to it model
So I am Following a course of Django API and at last of my project is to create API for a Little Lemon restaurant.I have downloaded the Same Project Source code and now implementing it on my side.Currently i am stuck on a issue for 2 days now i have tried chatgpt, stack-overflow but there are no concrete solution.so the problem is i can't insert a menu-item in the DB. Beacuse it is thorwing an error of IntegrityError at /api/menu-items NOT NULL constraint failed: LittleLemonAPI_menuitem.category_id **This error occurs when i try to insert a menu-item using the Insomia. But if i create the same item using the Super User it is created. This is my View.** class MenuItemListView(generics.ListCreateAPIView): queryset = MenuItem.objects.all() serializer_class = MenuItemSerializer def get_permissions(self): permission_classes = [IsAuthenticated] if self.request.method != 'GET': permission_classes = [IsAuthenticated, IsManager | IsAd This is my Model: class MenuItem(models.Model): title = models.CharField(max_length=255) price = models.DecimalField(max_digits=10, decimal_places=2) featured = models.BooleanField(db_index=True) category = models.ForeignKey(Category, on_delete=models.PROTECT) class Meta: unique_together = [['title', 'category']] def __str__(self): return self.title This is my Serializer class MenuItemSerializer(serializers.ModelSerializer): def validate_category(self, value): try: Category.objects.get(pk=value) return value except Category.DoesNotExist: raise serializers.ValidationError('Invalid category ID.') class Meta: model = MenuItem fields = ['id', 'title', 'price', 'featured', 'category'] … -
Django problem with downloading file from my computer
I am new in Django and I need some assist. I want to download the file which path is in plik.localisation(it has been taken from loop). The problem is with the path. Could someone help me what I am doing wrong? My view.py is: def download(request, path): file_path = os.path.join(settings.MEDIA_ROOT, path) if os.path.exists(file_path): with open(file_path, 'rb') as fh: response = HttpResponse(fh.read(), content_type="application/pdf") response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path) return response raise Http404 Urls path('download/(?P<path>)$', serve,{'document root': path}, name="download"), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Html <div class="com"> {{plik.localisation}} <a href="{% url download/path %}" class="button">downloadz</a> </div> I've tried to change that path but still have problem with it. -
Input Validation with one Text Input and ChooseField of Model Fields in Django
I want to implement a Basic Search function to my Django Project I have a dropdown field with all model Fields of my userdb model. forms.py class searchForm(forms.Modelform): field=forms.ModelChoiceField(queryset=[f.name for f in MyModel._meta.get_fields()],widget=forms.Select(attrs={'class':'form-select','data-live-search':'true'})) class Meta: model=userdb fields='__all__' input=forms.CharField() How can I validate if the input of the input charfield is correctly Formated depending on the selected field in field. -
how can i make a search bar in django?
hello i'm learning django and i'm trying to make some online shop for learning . currently i have a problem in how to make a search bar in django. i have model called "Car" in my models.py and it contains fields like name and price of the car and also it has a field called "tag" and i want to make a search bar using this field . i want when user type a tag in webpage of site , django search and show the items have the same tag. like other websites . Thank you i tried to solve my problem by reading the documents but it didn't help . -
Reuse Django's admin form template for my own forms
When the Django admin renders one of its forms, the fields are rendered with HTML like so: <div> <div class="flex-container"> <label for="id_comment">Comment:</label> <input type="text" name="comment" class="vTextField" maxlength="200" id="id_comment"> </div> </div> When I add my own page to the admin interface and I render a form using {{ form }}, the layout is completely different, and the same field would be rendered like this: <div> <label for="id_comment">Comment:</label> <input type="text" name="comment" id="id_comment"> </div> How can I reuse Django’s form template for my own forms? This is my full HTML template: {% extends "admin/base_site.html" %} {% load i18n admin_urls %} {% block breadcrumbs %} <div class="breadcrumbs"> <a href="{% url 'admin:index' %}">{% translate 'Home' %}</a> &rsaquo; <a href="{% url 'admin:app_list' app_label=opts.app_label %}">{{ opts.app_config.verbose_name }}</a> &rsaquo; <a href="{% url opts|admin_urlname:'changelist' %}">{{ opts.verbose_name_plural|capfirst }}</a> &rsaquo; {{ title }} </div> {% endblock %} {% block content %} <form action="." method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Generate codes"> </form> {% endblock %} I include this extra page in the admin by setting up get_urls in the ModelAdmin class, and returning a TemplateResponse with the form instance. -
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 …