Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Running a django app on an apache server with Xampp
I am a junior dev and have landed my first role but have no one here to ask questions to. I have been tasked with migrating our company app from the current server to a new server. I have been doing some research and looking through our code to orient myself with their system design. They are currently running their app directly from their server. I know nothing about server config. From my research i found the mod_wsgi is used and have found the httpd.conf file and saw that it is point to the project folder on the C:/. Can anyone walk me through the process of setting up a new server and what files i need to configure? Currently they have it setup on an apache server which is controlled by xampp (all new to me). I haven't toyed around with things too much because i changed branches the other day and their entire program companywide stopped working. So i dont want to start breaking things until i am sure i can recover it. -
KQL Query Formatting/Prettify Library
I am running a Django web app and would like to show some KQL query to the user. However, the query is in a single line, and I would like to format/prettify it. How can it be done? Do I really have to run a separate server running Node.js that than can prettify the code? Can I use the js files in @kusto/monaco-kusto or @kusto/language-service-next to prettify and syntax highlight the KQL queries on my web app? -
Can't load page..... page not found error?
When I load the pages in my project Django keeps showing me a page not found error. I have already written the views and their corresponding urls in the views.py and urls.py files and it is still saying that the page is not found when I load it. My index file is not affected by this error, but when I want to access other files the error popes up I ran manage.py runserver to load the index page but when I want to access the other pages through the nav-bar the error pops up -
Why is my API retrieving data from the database faster than from Redis?
I'm working with Django and GraphQL to create a backend for an e-commerce application. Initially, the API for retrieving products was slow, so I decided to implement a Redis stack to speed it up. However, I found that retrieving data from Redis is much slower than retrieving it from the database. Below are the details of my implementation: Database Query: def resolve_products(self, info, **kwargs): (filter_objects, method_filter, seller_lst, name, ar_name) = ( product_obj.call_filter_product() ) kwargs["seller_list"] = eller_lst query = ( Products.objects.filter(filter_objects, method_filter, active=True) .filter(variants__seller__id__in=list(seller_lst)) .distinct() ) query = query.filter( Exists( Variant.objects.filter( product_id=OuterRef("id"), seller_id__in=seller_lst, stock_available=True, ) ) ) start_index = int(offset) end_index = start_index + int(kwargs.get("first")) query_set = query[start_index:end_index] final_qs = query_set.annotate( stock_available=Exists( Variant.objects.filter( product_id=OuterRef("id"), seller_id__in=seller_lst, stock_available=True, ) ) ) # Determine hasNextPage has_next_page = end_index < len(query) connection = ProductsConnection( edges=[ProductsConnection.Edge(node=product) for product in final_qs], total_count=query.count(), details={ "header_en": name, "header_ar": ar_name, "method": kwargs.get("method"), }, ) connection.page_info = PageInfo( start_cursor=start_index, end_cursor=( int(kwargs.get("first")) + 1 if int(offset) == 0 else int(offset) + int(kwargs.get("first")) ), has_next_page=has_next_page, has_previous_page=start_index > 0, ) return connection Redis Implementation: seller_lst = obj.get_seller_lst() redis_obj = RedisUtility() data = redis_obj.get_products(seller_lst, **kwargs) if data: product_ids = [int(product['id']) for product in data['products']] products = Products.objects.filter(id__in=product_ids) connection = ProductsConnection( edges=[ProductsConnection.Edge(node=product) for product in products], … -
Transparent png in Django navigation bar not working
I am currently building a website with Django. Then I tried to add a logo to the navigation bar by inserting a png file with transparent background, but strangely the background remained white. So I combined part of base.html and part of navbar.html to create a file called test.html, and here the image is also displayed fine with transparent background. I hope you can help me to solve this problem. I am currently using Django 4.0.3. logo file is IMG_1706.png style.css is empty. logo file test.html My django server [code] test.html (just html) <!-- navigation bar --> <!doctype html> <html lang="ko"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" type="text/css" href="../static/bootstrap.min.css"> <!-- cubestudio CSS --> <link rel="stylesheet" type="text/css" href="../static/style"> </head> <body> <nav class="navbar navbar-expand-lg navbar-light bg-light border-bottom"> <div class="container-fluid"> <a class="navbar-brand"><img src="../static/IMG_1706.png" class="img-fluid" alt="CubeStudio" width="200" height="150"></a> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav me-auto mb-2 mb-rg-0"> </ul> </div> </div> </nav> </body> </html> base.html (django) {% load static %} <!doctype html> <html lang="ko"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" type="text/css" href="{% static 'bootstrap.min.css' %}"> <!-- my CSS --> … -
SMTPAuthenticationError at /appointment/ (535, b'5.7.3 Authentication unsuccessful [BLAPR03CA0003.namprd03.prod.outlook.com 08DCAE8BF31BEC3D]')
My code works absolutely fine on local server, but I deployed it using a custom domain from godaddy and now everything's wrong with it. I am using outlook mail. I don't know how to fix this. Other fixes I've seen only work for organization email and I have a personal email. I don't have the paid office365 version, I don't know if I need it just to send mail. My settings.py: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST = 'smtp-mail.outlook.com' EMAIL_HOST_USER = "email@outlook.com" EMAIL_HOST_PASSWORD = "pass" DEFAULT_FROM_EMAIL = "email@outlook.com" -
How to setup sentry for django celery-beat?
I've setup sentry in my demo python project in settings.py. sentry_sdk.init( dsn=os.getenv('SENTRY_KEY'), # Set traces_sample_rate to 1.0 to capture 100% # of transactions for performance monitoring. traces_sample_rate=1.0, # Set profiles_sample_rate to 1.0 to profile 100% # of sampled transactions. # We recommend adjusting this value in production. # profiles_sample_rate=1.0, ) Now I want to enable it for the celery-beat. What is the way to integrate it or update the existing config in settings.py? The Sentry doc says: Initialize Sentry in the celeryd_init or beat_init signal Does it require to create a celery task.py?How to automatically start this task when running python manage.py runserver or celery? -
Maybe a bad implementation of Django signals
I recently deployed a full stack project using Django, Gunicorn and Nginx. Briefly speaking, it is a website for a friend of mine, a space in which he can share and publish his recent activities (such as published albums, photoshoots and articles). I tried to automatize the information collections for populating a model instance by uploading a file (for a faster, cleaner and easier upload from the admin panel) using several Django signals. My idea was: if I upload from the admin panel a perfectly formatted file (.docx), using signals and other functions I will be able to fill the information and that's it. But, if I delete an instance (ie an Album or an Article), I'd like that this would have effects on files (I mean, delete files from the media folder on the server). Before posting my code, I'd like to tell that in developing this approach works perfectly and it's the same for different models. Sadly, it does not in production. More precisely, the file upload works perfectly, the processing sometimes doesn't (and I'm left with empty fields), the file deletion for some models works, for other does not at all. settings.py INSTALLED_APPS = [ 'musicsite.apps.MusicsiteConfig', ... … -
Custom Email Validation in Djoser Registration Not Working
I'm using Django with Djoser for authentication and need to restrict user registration to only those emails listed in my kontakte table. However, my custom email validation doesn't seem to be invoked. Here are the details: Djoser Configuration: DJOSER = { "PASSWORD_RESET_CONFIRM_URL": "auth/password-reset-confirm?uid={uid}&token={token}", "ACTIVATION_URL": "auth/activation?uid={uid}&token={token}", "SEND_ACTIVATION_EMAIL": True, "USER_CREATE_PASSWORD_RETYPE": True, "PASSWORD_RESET_CONFIRM_RETYPE": True, "PASSWORD_RESET_SHOW_EMAIL_NOT_FOUND": True, "TOKEN_MODEL": None, "FROM_EMAIL": getenv("FROM_EMAIL"), "SERIALIZERS": { "user_create": "users.serializers.CustomUserCreateSerializer", }, } Custom Serializer: from rest_framework import serializers from djoser.serializers import UserCreateSerializer from .models import UserAccount, Kontakte class CustomUserCreateSerializer(UserCreateSerializer): class Meta(UserCreateSerializer.Meta): model = UserAccount fields = ("email", "password", "is_active", "is_staff", "is_superuser") def validate_email(self, value): if not Kontakte.objects.filter(email=value).exists(): raise serializers.ValidationError("You are not allowed to register.") return value def create(self, validated_data): user = UserAccount.objects.create_user( email=validated_data["email"], password=validated_data["password"] ) return user Problem: The custom email validation in CustomUserCreateSerializer doesn't seem to be invoked during registration. I need the registration to check the kontakte table and deny if the email is not found. What I Have Tried: Verified the DJOSER settings point to the custom serializer. Added a print statement in validate_email to check if it's being called (it isn't). Any advice on what might be wrong or how to ensure my custom validation is used would be greatly appreciated. Thanks! -
Django ORM model default not applying in python queryset
I have the below Django ORM which represents a PostgreSQL view. For the field cost_requirement I have set the default value to 0. However the queryset object still populates with None if data is missing for this field. I have made all migrations and I just want the default to apply at the Python side (nothing to do with the database). From the Django documentation I understand I am using this argument correctly. Any suggestions why the default value of 0 is not being applied? class DashboardProduct(models.Model): date = models.DateField() product_id = models.CharField(max_length=50) base_l = models.FloatField(default=0) cost_requirement = models.FloatField(blank=False, null=False, default=0) book = models.CharField(max_length=100, blank=True, null=True) portfolio = models.CharField(max_length=100, blank=True, null=True) sales_5_pnl = models.FloatField(default=0) class Meta: managed = False db_table = 'view_dashboard_product' -
how to add product to my cart in django rest frame work drf
this is my model class Cart(models.Model): id = models.UUIDField(primary_key=True, default=uuid4) created_at = models.DateTimeField(auto_now_add=True) class CartItem(models.Model): cart = models.ForeignKey(Cart, on_delete=models.CASCADE, related_name='items') product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='cart_items') quantity = models.PositiveSmallIntegerField() class Meta: unique_together = [['cart', 'product']] this is my views class CartItemViewSet(ModelViewSet): http_method_names = ['get','post','patch','delete'] serializer_class = CartItemSerializer queryset = CartItem.objects.all() def get_queryset(self): cart_pk = self.kwargs['cart_pk'] return CartItem.objects.select_related('product').filter(cart_id = cart_pk).all() def get_serializer_class(self): if self.request.method == 'POST': return AddCartItemSerializer elif self.request.method == 'PATCH': return ChangeCartItemSerializer return CartItemSerializer def get_serializer_context(self): return {'cart_pk':self.kwargs['cart_pk']} class CartViewSet(CreateModelMixin, RetrieveModelMixin, DestroyModelMixin, GenericViewSet, ): serializer_class = CartSerializer queryset = Cart.objects.prefetch_related('items__product').all() lookup_value_regex = '[0-9a-f]{8}\-?[0-9a-f]{4}\-?[0-9a-f]{4}\-?[0-9a-f]{4}\-?[0-9a-f]{12}' and my serializer class ProductSerializer(serializers.ModelSerializer): title = serializers.CharField(max_length=255, source='name') price = serializers.DecimalField(max_digits=6, decimal_places=2,source='unit_price') unit_price_after_tax = serializers.SerializerMethodField() class Meta: model = Product fields = ['id', 'title', 'price','category', 'unit_price_after_tax', 'inventory', 'description'] def create(self, validated_data): product = Product(**validated_data) product.slug = slugify(product.name) product.save() return product # def update(self, instance, validated_data): # instance.inventory = validated_data.get('inventory') # instance.save() # return instance def get_unit_price_after_tax(self , product): return round(product.unit_price * Decimal(1.09), 2) def validate(self, data): if len(data['name']) < 6: raise serializers.ValidationError('Product lentgh should be at least 6.') return data class CartProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ['id', 'name', 'unit_price'] class ChangeCartItemSerializer(serializers.ModelSerializer): class Meta: model = CartItem fields = ['quantity'] class AddCartItemSerializer(serializers.ModelSerializer): class Meta: … -
ValueError: Field 'id' expected a number but got 'user'
i am fresher at django .i had tried my best for solving but i couldn't find the error .While making migration ,it shows this error " ValueError: Field 'id' expected a number but got 'user' ". enter image description here i am trying to create subfile i.e innerfile inside a folder ,but i am not able to do migrate my project -
how to set login_required in django project,i am not using django inbuild authentication login?
user cannot enter any page by entering the url of any page do i need to change anything in settings .py view.py for login to each dashboard def asset_login(request): if request.method == 'POST': username = request.POST.get('user_id') password = request.POST.get('password') try: user = UserTable.objects.get(username=username, password=password) if user: if user.status == 'inactive': messages.error(request, 'Your account is inactive.') return redirect('asset_login') request.session['name'] = user.name request.session['role'] =user.role if user.role == 'admin': return redirect('admin_dashboard') elif user.role == 'ciso': return redirect('ciso_dashboard') elif user.role == 'fnhead': return redirect('fnhead_dashboard') elif user.role == 'systemadmin': return redirect('systemadmin_dashboard') elif user.role == 'assetowner': return redirect('assetowner_dashboard') else: messages.error(request, 'Unknown user position') return redirect('asset_login') # Redirect to clear form and message except UserTable.DoesNotExist: messages.error(request, 'Invalid username or password') return redirect('asset_login') # Redirect to clear form and message return render(request, 'asset.html') urls.py urlpatterns = [ path('asset_login/', views.asset_login, name='asset_login'), path('admins/', views.admin_dashboard, name='admin_dashboard'), path('assetdb/', views.assetowner_dashboard, name='assetowner_dashboard'), view.py for dashboard def admin_dashboard(request): total_users = UserTable.objects.count() total_assets = AssetTable.objects.count() total_dept=Department.objects.count() total_emp=Employee.objects.count() name = request.session.get('name',None) role = request.session.get('role', None) try: admin_privileges = adminprivileges.objects.get() except ObjectDoesNotExist: admin_privileges = None context = { 'total_users': total_users, 'total_assets': total_assets, 'total_dept':total_dept, 'total_emp':total_emp, 'name':name, 'role':role, 'assetview': admin_privileges.assetview if admin_privileges else False, 'userview': admin_privileges.userview if admin_privileges else False, 'employeeview': admin_privileges.employeeview if admin_privileges else False, 'locationview': admin_privileges.locationview if admin_privileges … -
Django page doesn't display anything
My "News" page isn't working, it's saving info in database but doesn't display anything. Here's HTML: {% extends 'base.html' %} {% block content %} <h1 class = 'product'>News</h1> {% for item in new %} <div><br><strong><a href='/news/{{ item.id }}'>{{ item.title }}:</a></strong><br> {{ item.article }} <br>{{ item.views }} views</div> {% endfor %} {% endblock %} My views.py: def news(request): return render(request, 'news.html', {'news': New.objects.all()}) Models.py: class New(models.Model): title = models.CharField(max_length = 50) article = models.TextField() views = models.IntegerField(default = 0) user_views = models.ManyToManyField(to = User, blank = True) category = models.ForeignKey(to = NewCategory, on_delete = models.SET_NULL, null = True, blank = True, verbose_name = 'Категория') views_qty = models.IntegerField(default = 0) def __str__(self): return self.title -
How to use a single serializer to save multiple models
Problem : I’m unable to save the both models in database from a single serialzer. Description : I’m using djoser auth library for registration and authentication. for that i’m using custom django auth user and mapped it with userprofile model. Since i’m using userprofile along with the django user, i have to use custom register serializer. # My Models class CustomUser(AbstractUser): username = None email = models.EmailField(_("email address"), unique=True) USERNAME_FIELD = "email" REQUIRED_FIELDS = [] objects = CustomUserManager() class UserProfile(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, related_name="userProfile") user_guid = models.UUIDField( default=uuid.uuid4, unique=True, editable=False ) user_type = models.IntegerField(choices=UserType.choices(), default=UserType.BUYER) wallet_balance = models.FloatField() created_at = models.DateTimeField(auto_now=True) updated_at = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['created_at' ] # Corrected the ordering syntax` `#My Serializer CustomUser = get_user_model() class UserProfileSerializer(serializers.ModelSerializer): class Meta: model = UserProfile fields = ['user_guid', 'user_type', 'wallet_balance', 'created_at', 'updated_at'] read_only_fields = ['user_guid', 'created_at', 'updated_at'] class CustomUserCreateSerializer(DjoserUserCreateSerializer): userProfile = UserProfileSerializer() class Meta: model = CustomUser fields = ['id', 'email', 'password', 'userProfile'] extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): user_profile_data = validated_data.pop('userProfile') user = CustomUser.objects.create_user(**validated_data) UserProfile.objects.create(user=user, **user_profile_data) return user` AUTH_USER_MODEL = 'users.CustomUser' DJOSER = { 'SERIALIZERS': { 'user_create': 'users.v1.serializers.CustomUserCreateSerializer', 'user': 'users.v1.serializers.CustomUserCreateSerializer', 'current_user': 'users.v1.serializers.CustomUserCreateSerializer', } }` Error : raise ValueError( ValueError: Cannot assign “{‘user_type’: 1, ‘wallet_balance’: … -
Django REST Framework Does Not Show Image in React Frontend, But Titles and Other Text Are Showing
I am trying to build my blog site with Django as the backend and React as the frontend. For the REST API, I am using the Django Rest Framework library. I created a Blog model with an image field and set the media and static URLs in the settings.py file. Now, when I fetch the blogs in React with Axios, it doesn’t show the images, but I can see the blog titles and other fields. I ensured that the Django settings for media files are correctly configured. The image URLs are present in the API response when I inspect the network requests.enter image description here enter image description here enter image description here -
SQL Query Executor using Django
I am a beginner in software development, I am task to develop a web-based application, in which I use Django Web Framework, that can Execute SQL queries against a MS SQL Server Database, display the results of the query and log the details into the Django database (PostgreSQL), like timestamp, user, SQL Statement, errors, results etc, it is working. But, can you guys give me how to improve this? In my template, I use Ajax, and planning to use reactJS as frontend, but I am not really into it right now due to I need to learn it first. Objective: (1). I want to store the results in the session, retrieve it using ajax from the session and display the results. (2). but I want to add a unique ID using the generate_session_id() to that session data to identify that particular session data and retrieve it using ajax and display it the session data. (3). and to also enable the user to open new tab and run another SQL query executor. (3.1). Every time the page is reloaded or the page is ready, or the user open it in another tab, the unique session id should be different or renew … -
Django module not found
I'm very much a newbie trying to get a hold of Django. I am just getting started, trying to configure the URLs with an app. However, whenever I try to run the server, it tells me the urls module is not found, even when I use the absolute path. I've included some of my code below. from django.urls import include, path urlpatterns = [ path('custom_regions/', include("some\\absolute\\path\\placeholder.urls")), path('admin/', admin.site.urls), ] from django.urls import path from . import views urlpatterns = [ path('', views.index, name = 'index'), ] Considering I've been following the tutorial to a T, I'm not quite sure what I'm doing wrong. -
How to optimize Django autoreload / startup process?
I am currently working on a very large Django project that includes many files and, more importantly, a substantial set of dependencies, including packages like Torch and Transformers. Since installing Torch, I have noticed that the autoreload feature and the entire startup process when using the development server have become very slow. It now takes 10-15 seconds before I can test my code, which is quite frustrating during development. Is there any way to optimize this process, such as telling Django to ignore certain imports or indexing when in DEBUG mode, or any other methods to speed up the autoreload and startup of the Django development server? -
Django Admin TabularInline: How do I hide the object name of a M2M through model?
How do I hide Unit_attribute object (3) from the admin display? admin.py: from django.contrib import admin from core.models import Attribute, Unit class UnitAttributeInline(admin.TabularInline): model = Unit.attributes.through @admin.register(Unit) class UnitAdmin(admin.ModelAdmin): inlines = [UnitAttributeInline] models.py: class Attribute(models.Model): name = models.CharField(max_length=45) class Unit(models.Model): attributes = models.ManyToManyField(Attribute) -
How to create users with different types of fields in django?
how to create models for different types of users with different types of fields in django? Suppose I have 2 users: doctors and nurses, and doctors have a doctor_id, and dept, apart from the fields common between nurses and doctors.How to proceed then? Searched everywhere and scratched my head, can anyone let me know how to approach this? I have tried to write something like this, but it doesnt work. from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): USER_TYPE_CHOICES = ( (1, 'doctor'), (2, 'nurse'), ) user_type = models.PositiveSmallIntegerField(choices=USER_TYPE_CHOICES) class DoctorProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) doctor_id = models.CharField(max_length=6) dept = models.CharField(max_length=255, blank=False, null=False) def __str__(self): return self.user.username class NurseProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) nurse_id = models.CharField(max_length=6) def __str__(self): return self.user.username -
Django Models - trying to get the "best of both worlds" when it comes to copying a model vs subclassing it
Let's say I have a base class (Django model) called Character that looks something like class Character(models.Model): strength = models.blabla dex = models.blabla ... I can set that up with its attributes and hook it up to Admin and everything is lovely. Then I decide I want a NonPlayerCharacter model, which has everything the Character model has, plus a new field or two. I can think of at least two ways to do this, each with pros and cons. Option 1: # The basic obvious stupid-simple answer is just to copy the model and add the fields class NonPlayerCharacter(models.Model): strength = models.blabla dex = models.blabla ... faction = models.blabla Pros: Everything is kept very simple and easy to manage, and if the models need to diverge in the future, that's easy too. Cons: Obvious code duplication and keeping universal changes in sync. If I change a stat or add a method on one, I've got to duplicate it on the other. If I add another type of Character, like Mob, well then it triples the upkeep to keep the necessary parts in sync. Option 2: # The next most obvious solution is to subclass Character class NonPlayerCharacter(Character): faction = models.blabla … -
Django async aadd() not working on ManyRelatedManager models?
Recently I have been developing an app using Django ninja. I want to add Group to user groups, and statement seems have no effect. It does not commit to db. I tried atomic, and all solutions but it does not work. I have db for tests: settings.DATABASES["default"] = { "ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:", "ATOMIC_REQUESTS": False, "TIME_ZONE": "America/Chicago", "CONN_HEALTH_CHECKS": True, "CONN_MAX_AGE": 0, "OPTIONS": {}, "AUTOCOMMIT": True } This is code: group = await cls.repository.get_group_by_name(name) assert group await user.groups.aadd(group) In Django documentation this should work just fine, but it does not. I use AsyncClient from Django to run tests. Any advice ? -
Django Migration Issue With Abstract User
I have created Django application it was working fine at start but now i am facing migration issue with abstract user i remove the migrations files and database from my project and then remigrate it the issue still exist Please any one help me to solve the problem -
Page not found 404 for about
This error is coming .Can someone please help me to come out from that GPage not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/about Using the URLconf defined in Hello.urls, Django tried these URL patterns, in this order: [name='home'] The current path, about, didn’t match any of these. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. code related to that are: from django.shortcuts import render, HttpResponse # Create your views here. def index(request): return HttpResponse("This is Home Page") def about(request): return HttpResponse("This is About Page") from django.contrib import admin from django.urls import path from home import views urlpatterns = [ path("",views.index,name='home'), path("about/",views.about,name='about'), ] from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('',include('home.urls')) ] normal page is working as This is home page.Admin page was also working but now it is also not working.