Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
push reload or invoke javascript function from server
I have Django + React + uwsgi application. Uwsgi access to the database. Now I want to reload Django(React) web applicataion triggered by Database is changed. For example User open the web application Administrator use mysql command on server Insert into mytable(name) values("data") User's application will be reloaded or some javascript function be called. It's something like push reload from server. In my idea. Web application access the database to check the value is altered in every seconds. However It requires to access API every seconds. (And at most it has the one seconds delay, or requires too much api access) Is this a good practice ? Is there any good method for this purpose?? -
Sucessful compilation but browser can't access site
I am doing my first project with Django and React. Whenever i run npm run dev the project compiles succesfully. But once I go to the browser, it says that the site can't be reached and that localhost rejected the conection. I tried running PORT=8001 npm run dev but the same keeps happening. I have read other options about changing the webpack.config.js file, like this devServer: { contentBase: path.join(__dirname, 'dist'), compress: true, port: 3000, open: true, }, but my project has no dist folder -
Inspecting celery tasks in django
Is importing celery app and calling control.inspect() the best way for inspecting active tasks? Also, I'm using RabbitMQ as my broker. from core.celery import app def get_running_tasks(request): i = app.control.inspect() i.active() # retrieving active tasks -
How do I ensure that only certain domain names can sign up using django authentication tools?
I want to restrict my signups to certain colleges while building a product using django. I want to do something similar to how Autodesk approves its users. I have a list of the domain names. I tried manually allowing sign-ups for certain domain names. This was done in the code itself and not connected to a database of domain names. I saw an answer linking a model but for a blocklist. I need to do the opposite. -
Learning Django without DTL
I just finished my second React course and become more confident with it by creating a several web application. Now my plan is to go fullstack, I decided to start learning Django because am kinda good with python, the course is really straight forward and well explained, the problem started with lectures talking about DTL (Django Template Language), i ended up getting lost and bored because am already familiar with front-end library, is there any course that focuses on backend development side of django ? I tried to follow with those lectures and did understand but it conflict with my React knowledge -
Save DateTime in mysql database based on Asia/Tehran time zone
I have a Django project where I have used a DateTime field in one of its models. In this database field, I want to save the date and time of this moment. Also, my database is mysql type and on the server. First of all I have set Django settings. LANGUAGE_CODE = 'en-us' TIME_ZONE = 'Asia/Tehran' USE_I18N = True USE_TZ = True Also, to be sure, I edited the database model as follows. class Register(models.Model): card = models.ForeignKey(Card, on_delete=models.CASCADE, db_index=True) member = models.ForeignKey('member.Members', on_delete=models.CASCADE, db_index=True) field = models.ForeignKey(Field, on_delete=models.CASCADE) start_date = models.DateTimeField(null=True, blank=True) end_date = models.DateTimeField(null=True, blank=True) session_count = models.IntegerField(null=True, blank=True) is_active = models.BooleanField(default=True) def save(self, *args, **kwargs): tehran_tz = pytz.timezone('Asia/Tehran') if self.start_date: self.start_date = self.start_date.astimezone(tehran_tz) if self.end_date: self.end_date = self.end_date.astimezone(tehran_tz) super(Register, self).save(*args, **kwargs) I have also set the time zone in the database using the following command. SET GLOBAL time_zone = 'Asia/Tehran'; SET time_zone = 'Asia/Tehran'; The result of executing the following command in the database is as follows. SHOW VARIABLES LIKE 'time_zone'; The interesting thing is that when I print the time and date in the terminal, it shows correctly, but when I save it in the database, it is saved as UTC. -
parser add_mutually_exclusive_group - how can I set a default value?
We use Python and Django for our websites. We set a test command that adds to the default Django test command: from django.core.management.commands import test class Command(test.Command): def add_arguments(self, parser): super().add_arguments(parser=parser) group = parser.add_argument_group('language options', 'These arguments are mutually exclusive. Default: --test-default-languages') language_group = group.add_mutually_exclusive_group() language_group.add_argument( "--test-all-languages", action="store_true", help="Run tests for all languages, and don't skip languages.", ) language_group.add_argument( "--test-default-languages", action="store_true", help="Run tests for default languages (English, French, Hebrew + randomly select one more language or none).", ) language_group.add_argument( "--test-only-english", action="store_true", help="Run tests for only English.", ) # ... Now, in the models we have this code: class SiteDiscoverRunner(DiscoverRunner): def __init__(self, *args, **kwargs): # ... super().__init__(*args, **kwargs) self.test_all_languages = kwargs.get('test_all_languages', False) self.test_default_languages = kwargs.get('test_default_languages', False) self.test_only_english = kwargs.get('test_only_english', False) if ((self.test_all_languages is False) and (self.test_only_english is False)): self.test_default_languages = True Tests must be run with one of the above command line arguments or none. If none then the test_default_languages value should be true. I would like to know if the parser can make self.test_default_languages True if none of the 3 arguments is given, so I can remove the command self.test_default_languages = True in the model? I searched and didn't find out how to do it. -
How to catch Django's OperationalError exception thrown in django-main-thread
I use a Postgres 16.2 database in my Django 5.0 project configured like so: ### settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'DB_NAME', 'USER': 'DB_USER', 'PASSWORD': 'DB_PASS', 'HOST': 'DB_HOST', 'PORT': '5432', } } It works well, no issue here. However, when I simulate a database outage (typically, I'm stopping the database service on my computer), I end up with an exception that I cannot manage to catch: Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/local/lib/python3.12/site-packages/django/db/backends/base/base.py", line 275, in ensure_connection self.connect() File "/usr/local/lib/python3.12/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/django/db/backends/base/base.py", line 256, in connect self.connection = self.get_new_connection(conn_params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/django/db/backends/postgresql/base.py", line 277, in get_new_connection connection = self.Database.connect(**conn_params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/psycopg2/__init__.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ psycopg2.OperationalError: could not translate host name "api-db" to address: Temporary failure in name resolution The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/usr/local/lib/python3.12/threading.py", line 1073, in _bootstrap_inner self.run() File "/usr/local/lib/python3.12/threading.py", line 1010, in run self._target(*self._args, **self._kwargs) File "/usr/local/lib/python3.12/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python3.12/site-packages/django/core/management/commands/runserver.py", line 136, in inner_run self.check_migrations() File "/usr/local/lib/python3.12/site-packages/django/core/management/base.py", line … -
Python (Django) project structure for web system
I going to satart to develop a web system using Python (Django) in the backend, but i want to start with fhe correct project structure or project tree. I will divide the project in two sections (Frontend and Backend), into the backend i pretend to add the templates and static files. What is the correct structure for a python (Django) web project? -
I have a problem in reverse function Django
i'm learning django and I spent a long time to let reverse() work but I failed. I don't want to use {% url ''....%}. this is the models.py I created 2 tables Category & Product from django.db import models class Category(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Product(models.Model): name = models.CharField(max_length=100) category = models.ForeignKey(Category, on_delete=models.CASCADE) price = models.DecimalField(max_digits=10, decimal_places=2) def __str__(self): return self.name this is urls.py from django.urls import path from . import views app_name = 'myapp' urlpatterns = [ path('product' , views.all_products , name= 'products'), path('product/<int:product_id>/', views.product_detail, name='product_detail'), ] this is views.py from django.shortcuts import render, get_object_or_404 from django.urls import reverse , reverse_lazy from .models import Product def all_products(request): products = Product.objects.all() context = { 'products' : products } return render(request , 'index.html',context) def product_detail(request, product_id): product = get_object_or_404(Product, id=product_id) detail_url = reverse_lazy ('myapp:product_detail', args = [product_id]) return render(request, 'product_detail.html', { 'product': product, 'detail_url': detail_url, }) this is index.html The problem is reverse function when I click on achor tag i didn't opens the detail_page <!DOCTYPE html> <html> <head> <title>Product Detail</title> </head> <body> {% for product in products%} <a href="{% url 'myapp:product_detail' product.id%}" onclick="show()"><h1>{{ product.name }}</h1></a> {% endfor%} <!-- --> </body> </html> this is product_detail.html {{product}} type … -
MultiValueDictKeyError at /api/products/
I'm encountering a MultiValueDictKeyError in my Django project when trying to access the API at http://127.0.0.1:8000/api/products/. The error occurs on this line: category = self.request.GET['category']. Here is my view: class ProductList(generics.ListCreateAPIView): queryset = models.Product.objects.all() serializer_class = serializers.ProductListSerializer def get_queryset(self): qs = super().get_queryset() category = self.request.GET['category'] category = models.Product.objects.get(category) qs = qs.filter(category=category) return qs My Product model is defined as follows: class Product(models.Model): category = models.ForeignKey(ProductCategory, on_delete=models.SET_NULL, null=True, related_name='product_in_category') retailer = models.ForeignKey(Retailer, on_delete=models.SET_NULL, null=True) title = models.CharField(max_length=200) detail = models.CharField(max_length=200, null=True) price = models.FloatField() def __str__(self) -> str: return self.title Here is my serializer: class ProductListSerializer(serializers.ModelSerializer): productreview = serializers.StringRelatedField(many=True, read_only=True) class Meta: model = models.Product fields = ['id', 'category', 'retailer', 'title', 'detail', 'price', 'productreview'] def __init__(self, *args, **kwargs): super(ProductListSerializer, self).__init__(*args, **kwargs) I am trying to call a list of products according to the product category from my React frontend, but I keep encountering the MultiValueDictKeyError. I tried using GET.get and various other approaches but haven't been able to resolve the issue. Here is the error traceback: Request Method: GET Request URL: http://127.0.0.1:8000/api/products/ Django Version: 4.2.13 Exception Type: MultiValueDictKeyError Exception Value: 'category' How can I fix this error and properly filter the products by category? -
Why does Swagger duplicate my documentation in endpoints using {format}?
I am creating documentation with Swagger in a Django project, I don't understand why it duplicates some endpoints by adding {format} at first sight they are the same endpoints: for example GET /profile/v1/{id} there is also a version with {format} settings.py: REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', ), 'DEFAULT_PARSER_CLASSES': ( 'rest_framework.parsers.JSONParser', ), "DEFAULT_AUTHENTICATION_CLASSES": [ "rest_framework_simplejwt.authentication.JWTAuthentication", ] } on views.py: class ProfileDetailView(APIView): permission_classes = [FullProfilePermissionGroup] def get_object(self, pk): try: return Profile.objects.get(pk=pk) except Profile.DoesNotExist: raise Http404 @swagger_auto_schema( operation_description="Retrieve a single profile by ID.", responses={ 200: openapi.Response( description="Profile retrieved successfully", schema=ProfileSerializer ), 404: openapi.Response(description="Profile not found"), }, produces=["application/json"] ) def get(self, request, pk): profile = self.get_object(pk) serializer = ProfileSerializer(profile) return Response(serializer.data) It is not a blocking problem, but I would like to eliminate it, can you help me? Thanks -
Maintaining product data across AJAX requests for invoice creation
I'm working on a Django application for creating invoices. Users can add multiple products to an invoice before submitting it. I'm facing an issue where the product data isn't being maintained between AJAX requests when creating the invoice (this is my supposition). My current setup: 1- I have an add_product view that handles AJAX requests to add products. 2- I'm storing the added products in the session: if 'products' not in request.session: request.session['products'] = [] request.session['products'].append(product_details) request.session.modified = True 3- I have a create_invoice view that should use these stored products: products = request.session.get('products', []) if not products: return JsonResponse({'error': 'No products added'}, status=400) # Create invoice with products... 4- I'm making AJAX calls from the frontend to add products and create the invoice. The problem: When I call the create_invoice view, request.session.get('products', []) is always empty, even though I've added products. -
django stripe on deploy Error verifying webhook signature
i have django react app, i added stripe to django, react build files i set on static django i have tested on localhost with stripe cli is working fine but after i deploy my django project on vercel and create endpoint on https://dashboard.stripe.com/test/webhooks to handle stripe webhooks event i get error https://i.sstatic.net/51zS8MrH.png, (after i create new webhook endpoint i set new webhook_secret_key so problem not in webhook_secret_key) I searched on the Internet how to fix it, they advised to set on payload request.body.decode('utf-8) or request.data but nothing helped my code (this code on localhost is working fine but on deployed server i get error, for deployed server i changed webhook_secret_key to new secret_webhook_key from https://dashboard.stripe.com/test/webhooks and site_url to deployed server) from django.conf import settings from django.http import HttpResponse from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from .models import DepositHistory from django.views.decorators.csrf import csrf_exempt from decimal import Decimal import stripe from rest_framework.decorators import api_view from usersAuth.models import AppUser stripe.api_key = settings.STRIPE_SECRET_KEY class StripeCheckoutView(APIView): def post(self, request): if self.request.user.is_authenticated: try: checkout_session = stripe.checkout.Session.create( line_items=[ { 'price': 'price_1PY4d6GKlfpQfnx9EFKpod75', 'quantity': 1, }, ], metadata={"user": f'{self.request.user}'}, mode='payment', success_url=settings.SITE_URL + '/?success=true&session_id={CHECKOUT_SESSION_ID}', cancel_url=settings.SITE_URL + '/?canceled=true', ) return Response({"url": checkout_session.url}) except: return Response( … -
django using aggregate() and distinct() together
I have a filterset that has following attributes: dosFromGte = filters.DateFilter(method="search_by_dos_from_gte", lookup_expr="gte") dosToLte = filters.DateFilter(method="search_by_dos_from_lte", lookup_expr="lte") # One of these methods: def search_by_dos_from_lte(self, queryset: Chart, name: str, value: str) -> Chart: return queryset.annotate(max_dos=Min("diagnosis__dos_from")).filter(max_dos__lte=value) # using annotate and aggregate Min(). I need to run few annotations and then only fetch distinct ids. queryset = self.filter_queryset(self.get_queryset().exclude(state__in=repo_exclude)) queryset = queryset.annotate( ChartId=F("chart_id"), MemberId=F("member__member_id"), ChartStatus=F("state__name"), ).values( "ChartId", "MemberId", "MemberName", "ChartStatus" ).distinct("id") When I apply these filters ?clientId=11&project=56&dosFromGte=2023-08-17&dosToLte=2023-08-19 this tries to run Min() and then distinct on ids. This gives NotImplementedError("aggregate() + distinct(fields) not implemented.") So I tried to work around a bit and queryset.values( "id", "ChartId", "MemberId", "MemberName", "ChartStatus" ) # remove duplicate charts based on pk, i.e. id df = df.drop_duplicates('id') df = df.drop('id', axis=1) which kind of felt like a hack and dirty work around. Is there a cleaner ORM way to do it? -
How to filter Categories and Subcategories using listview in Django
I have Category and SubCategory models in Django and I need to get descendant of Category model in 'class SubCategoriesListView' `models.py class Category(models.Model): name = models.CharField('Категория', max_length=150, default='name') url = models.SlugField(max_length=160, unique=True) class SubCategory(models.Model): name = models.CharField('SubCategory', max_length=150, default=True) url = models.SlugField(max_length=160, unique=True) image = models.ImageField('Pic', upload_to='img', null=True, blank=True) category = models.ForeignKey(Category, on_delete=models.CASCADE) How to filter subcategories linked with category model? (I have to use detailview later, so solution must be with the using ListView model) `views.py class CategoriesListView(ListView): model = Category queryset = Category.objects.all() template_name = 'catalog/category_list.html' context_object_name = 'category_list' class SubCategoriesListView(Category, ListView): model = SubCategory queryset = SubCategory.objects.all() template_name = 'catalog/subcategory_list.html' context_object_name = 'subcategory_list'` -
POO (Python w/Django) [closed]
Bonjour, bonsoir, Je vous demande votre aide afin de comprendre le principe et comment faire de la Programmation Orienté Objet, je suis actuellement en formation de Développeur Web & Web Mobile, et j'apprends actuellement la POO mais en regardant des vidéos diverses pour comprendre, et même avec les cours je n'arrive pas à comprendre le fonctionnement, (Je n'ai pas eu d'exercice sur ça, j'ai directement eu un devoir), pourrais-vous me montrer un exemple de POO avec une "Description" ou des détails svp. PS : Mon devoir est sur une application bibliothécaire à remettre aux gouts du jour. Voici à quoi il ressemble. def menu(): print("menu") if name == 'main': menu() class livre(): name = "" auteur = "" dateEmprunt = "" disponible = "" emprunteur = "" class dvd(): name = "" realisateur = "" dateEmprunt = "" disponible = "" emprunteur = "" class cd(): name = "" artiste = "" dateEmprunt = "" disponible = "" emprunteur = "" class jeuDePlateau : name = "" createur = "" class Emprunteur(): name = "" bloque = "" def menuBibliotheque() : print("c'est le menu de l'application des bibliothéquaire") def menuMembre(): print("c'est le menu de l'application des membres") print("affiche tout") Comprendre, … -
Django: Vendor Dashboard Not Displaying All Orders for Products Sold
I'm working on a Django project where I have a vendor dashboard that should display all orders for the products uploaded by the current vendor. However, the dashboard is only showing orders placed by one user and not orders placed by other users for the same products. Models: Here are the relevant models: class Product(models.Model): pid=ShortUUIDField(length=10,max_length=100,prefix="prd",alphabet="abcdef") user=models.ForeignKey(CustomUser, on_delete=models.SET_NULL ,null=True) cagtegory=models.ForeignKey(Category, on_delete=models.SET_NULL ,null=True,related_name="category") vendor=models.ForeignKey(Vendor, on_delete=models.SET_NULL,null=True,related_name="product") color=models.ManyToManyField(Color,blank=True) size=models.ManyToManyField(Size,blank=True) title=models.CharField(max_length=100,default="Apple") image=models.ImageField(upload_to=user_directory_path,default="product.jpg") description=RichTextUploadingField(null=True, blank=True,default="This is a product") price = models.DecimalField(max_digits=10, decimal_places=2, default=1.99) old_price = models.DecimalField(max_digits=10, decimal_places=2, default=2.99) specifications=RichTextUploadingField(null=True, blank=True) tags=TaggableManager(blank=True) product_status=models.CharField(choices=STATUS, max_length=10,default="In_review") status=models.BooleanField(default=True) in_stock=models.BooleanField(default=True) featured=models.BooleanField(default=False) digital=models.BooleanField(default=False) sku=ShortUUIDField(length=10,max_length=100,prefix="sku",alphabet="abcdef") date=models.DateTimeField(auto_now_add=True) updated=models.DateTimeField(null=True,blank=True) class Meta: verbose_name_plural="Products" def product_image(self): return mark_safe('<img src="%s" width="50" height="50"/>'%(self.image.url)) def __str__(self): return self.title def get_percentage(self): new_price=((self.old_price-self.price)/self.old_price)*100 return new_price def get_product_price_by_size(self , Size): return self.price + Size.objects.get(name = Size).price class CartOrder(models.Model): user=models.ForeignKey(CustomUser,on_delete=models.CASCADE) item=models.CharField(max_length=100) price= models.DecimalField(max_digits=10, decimal_places=2,default="1.99") paid_status=models.BooleanField(default=False) order_date=models.DateTimeField(auto_now_add=True) product_status=models.CharField(choices=STATUS_CHOICE, max_length=30,default="processing") class Meta: verbose_name_plural="Cart Order" class CartOrderItems(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) vendor = models.ForeignKey(Vendor,on_delete=models.CASCADE,default=1) #I have to fix the default order=models.ForeignKey(CartOrder,on_delete=models.CASCADE,related_name="cartorderitems") # product = models.ForeignKey(Product, on_delete=models.CASCADE, default=1) invoice_num = models.BigIntegerField(blank=True,null=True) product_status=models.CharField(max_length=200) item=models.CharField(max_length=100) image=models.CharField(max_length=100) qty=models.BigIntegerField(default=0) price= models.DecimalField(max_digits=12, decimal_places=2,default="15") total= models.DecimalField(max_digits=12, decimal_places=2,default="20") color=models.ForeignKey(Color,on_delete=models.SET_NULL,null=True,blank=True) size=models.ForeignKey(Size,on_delete=models.SET_NULL,null=True,blank=True) class Meta: verbose_name_plural="Cart Order Items" def catagory_image(self): return mark_safe('<img src="%s" width="50" height="50"/>'%(self.image.url)) def oder_img(self): return mark_safe('<img src="/media/%s" width="50" height="50"/>'%(self.image)) View: Here is the view … -
How to mark a DRF ViewSet action as being exempt from the application of a custom middleware?
I've created a Custom Django Middleware and added to the MIDDLEWARE settings variable correctly. from django.http import HttpResponseForbidden class MyCustomMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): return self.get_response(request) def process_view(self, request, view_func, view_args, view_kwargs): # Perform some internal actions on the `request` object. return None Since this is applied to all DRF ViewSets by default, I would like to exempt some actions that don't need this check. The idea would be to check a flag inside the process_view function taking inspiration from the Django CsrfViewMiddleware which checks if the csrf_exempt variable has been set by the csrf_exempt decorator. So I modified the custom middleware and created a custom decorator to exempt views explicitly. from functools import wraps from django.http import HttpResponseForbidden class MyCustomMiddleware: ... def process_view(self, request, view_func, view_args, view_kwargs): if getattr(view_func, "some_condition", False): return HttpResponseForbidden("Forbidden on custom middleware") # Perform some internal actions on the `request` object. return None def custom_middleware_exempt(view_func): @wraps(view_func) def _view_wrapper(request, *args, **kwargs): return view_func(request, *args, **kwargs) _view_wrapper.some_condition = True return _view_wrapper Having this I do something like this and it correctly enters the custom decorator before going inside the Django middleware. from rest_framework import viewsets from rest_framework.decorators import action from rest_framework.response import … -
Django return "You are not allowed to perform this action." when creating a new entry
I have an application which i want to run scripts. Those scripts are stored in a database. This is how i do all of this using Django 5.0.1 : First of all, this is my settings file : #... INSTALLED_APPS = [ # Django apps 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # My apps 'personal', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] #... This is my urls file : from django.contrib import admin urlpatterns = [ path('admin/', admin.site.urls), #... ] This is my models file : from django.db import models from django.core.exceptions import ValidationError from django.conf import settings from os.path import join class Product(models.Model): name = models.CharField(max_length=50, null=False, blank=False, unique=True) def __str__(self): return self.name class Type(models.Model): short_name = models.CharField(max_length=3, null=False, blank=False, unique=True) complete_name = models.CharField(max_length=30, null=False, blank=False) def __str__(self): return self.complete_name class Version(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) version = models.CharField(max_length=30, null=False, blank=False) constraints = [ models.UniqueConstraint(fields=['product', 'version'], name='unique_product_version'), ] def __str__(self): return f"{self.product} {self.version}" class TypeTestRelation(models.Model): type = models.ForeignKey(Type, null=False, blank=False, related_name='attributed_tests', on_delete=models.CASCADE) test = models.ForeignKey(Test, null=False, blank=False, on_delete=models.CASCADE) class Meta: unique_together = ['type', 'test'] class Test(models.Model): name = models.CharField(max_length=50, null=False, blank=False, unique=True) file = models.FileField(upload_to=join(join(settings.BASE_DIR, "static"), "scripts"), null=True, blank=False) # Add the file field … -
Django pet-project for beginners [closed]
I start to study django and have no idea what do i can write most useful for practicing this in the beginning. Could anyone give some advices for choosing theme for my unboarn projectc? Maybe blog or onlain-shop, Idk.. Thanks! I try to write one site with using db SQLite, auth, admin panel, models, some simple model etc. This is my start background -
What is the fastest way to query for items with an existing foreign key and many-to-many entry in Django?
I have a simple model with a foreign key and a many-to-many relationship: class Car(models.Model): uuid = models.UUIDField() is_red = models.BooleanField() class Owner(models.Model): car = models.ForeignKey(Car, to_field="uuid", on_delete=models.CASCADE) class Driver(models.Model): cars = models.ManyToManyField(ProtectedArea, related_name="cars") Now a lot of my application logic relies on cars on which at least one of the three conditions: it is red, it has at least one owner, it has at least one driver is true. It might be an important information, that in reality the Car-model contains some rather big polygonal data, maybe that is relevant for performance here? I have a custom manager for this but now matter how I built the query it seems extremely slow. Times are taken from my local dev machine with ~50k cars, 20k Owners, 1.2k Drivers. The view is a default FilterView from django-filter without any filters being actually active. My manager currently looks like this: class ActiveCarManager(models.Manager): def get_queryset(self): cars_with_owners = Owner.objects.values("car__uuid").distinct() cars_with_drivers = Drivers.objects.values("cars__uuid").distinct() return ( super() .get_queryset() .filter( Q(uuid__in=cars_with_owners) | Q(uuid__in=cars_with_drivers) | Q(is_red=True) ) ) The view generates 2 queries from this, one count query and one query to fetch the actual items. The query that is so slow is the count query. On our … -
get the lastest record of an object
I have two models: Cat (id, name) CatRecords (id, cat_id, status, created_time) Each day, a cat have one record about the status of the cat I want to get all the cats and the latest record of each, sorted by the created_time of the record I can get all records of each cat, but I cannot get the latest record of each The query class of Cat: class Query(graphene.ObjectType): all_cats = graphene.List(CatType) cat = graphene.Field(CatType, cat_id=graphene.UUID()) latest_record = graphene.Field(CatRecordType) def resolve_all_cats(self, info, **kwargs): cats = Cat.objects.all() return cats def resolve_cat(self, info, cat_id): return Cat.objects.get(cat_id=cat_id) def resolve_latest_record(self, info): subquery = CatRecord.objects.filter(cat_id=OuterRef("id")).order_by( "-created_time" ) return ( Cat.objects.all() .annotate(latest_record=Subquery(subquery.values("id")[:1])) .values("latest_record") ) My query query { latestRecord{ id name } } the error is { "errors": [ { "message": "Received incompatible instance \"<QuerySet [{'latest_record': UUID('3d2af716-94aa-4952-9050-4d7f69384e3d')}, {'latest_record': UUID('0705aeda-a2ec-47c3-8bd1-1aa445c40444')}]>\".", "locations": [ { "line": 2, "column": 3 } ], "path": [ "latestRecord" ] } ], "data": { "latestRecord": null } } -
Django Social Authentication Issue: Unable to Login Using Facebook or LinkedIn
I'm facing an issue with integrating social authentication (Google, Facebook, LinkedIn) into my Django web application using social-auth-app-django. While Google login works fine, I'm unable to get Facebook or LinkedIn login to function correctly. Login | Facebook Error | Linkedin Error | Linkedin Error2 I followed the setup instructions for social-auth-app-django and configured the keys and secrets for Google, Facebook, and LinkedIn in my settings.py. Google authentication works as expected, redirecting users to the correct page after login. However, when attempting to log in using Facebook or LinkedIn, the authentication process fails silently without any clear error message or redirection.Steps Taken: Verified client IDs and secrets for Facebook and LinkedIn are correctly set in settings.py. Ensured correct scopes and field selectors are configured for LinkedIn. Checked that all necessary middleware and context processors are included in settings.py. from pathlib import Path import os import logging BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = 'django-insecure-@*#c*5am%k5_-@#axxxxxxxxxxxah=(h9pbnf!z-x01h@n#66' DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'demo', 'social_django', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'social_django.middleware.SocialAuthExceptionMiddleware', ] ROOT_URLCONF = 'signin.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', … -
how change the MARKDOWNX_MEDIA_PATH in Django setting to include the image name in the path?
I am using the markdown library, i want to change the path to the images in a way that it contains the name of the file, according to the markdown [doc][1] the path can change by adding something like : from datetime import datetime MARKDOWNX_MEDIA_PATH = datetime.now().strftime("markdownx/%Y/%m/%d") i tried adding image.name but it didn't work in the setting now i was wondering if i can inject the file name here in the setting some how?