Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Ignore trans strings which are already translated in app directory
I use django-allauth as a third partie package in my Django project. I copied some templates from django-allauth into my template directory to modify the layout. But I did not touch the translation strings! After running makemessages this strings appears in my .po file even though it is translated in the app directory for django-allauth. (To manage my translations I use Weblate.) How can I stop this behavior? This is blowing up my .po file and is confusing the translators, because we have to notify them not to touch this string. Can I create a list of "msgid" which will ignore some strings? -
Django Admin Soft Dashboard in aws ec2 ubuntu 24.04 using pyhton 3.6.8
For my django admin panel I used django-soft-admin-panel pip for UI, as my python runtime is 3.8 it didn't run, so I downgraded by python to 3.6 and developed the project, the ui and all other things are perfectly working in local. I need to deploy the project in any of the aws services. At first I used lambda, but lambda is only for runtime >= 3.8 then I used Elastic Beanstalk, ebs is only for runtime >= 3.7 then I deployed in EC2 with nginx and gunicorn but the project and server getting crashed. Is there any solution? -
Django Rest Framework Many To Many serializer problem
I'm creating an API in Django Rest Framework and I have a problem with a ManyToMany relation. I'm trying to create an movie and assign genre to it (ManyToMany relationship between movie and genre). Here are my models: class Genre(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(null=False,blank=False,max_length=50) def __str__(self): return self.name class Movie(models.Model): id = models.IntegerField(primary_key=True,null=False,blank=False) adult = models.BooleanField(null=False,blank=False) backdrop_path = models.CharField(null=True,blank=True,max_length=200) budget = models.BigIntegerField (default=0) homepage = models.CharField(null=True,blank=True,max_length=200) original_language = models.CharField(max_length=10) original_title = models.CharField(max_length=200) overview = models.CharField(max_length=1000) poster_path = models.CharField(null=True,blank=True,max_length=200) release_date = models.DateField(null=True,blank=True,) revenue = models.BigIntegerField (default=0) runtime = models.IntegerField(null=True,blank=True) status = models.CharField(max_length=50) tagline = models.CharField(null=True,blank=True,max_length=100) title = models.CharField(max_length=200) genres = models.ManyToManyField(Genre,blank=True) def __str__(self): return self.title here are my serializers: class GenresSerializers(serializers.ModelSerializer): class Meta: model = Genre fields = ['id','name'] def create(self,validated_data): instance, _ = Genre.objects.get_or_create(**validated_data) return instance class MovieGenreSerializer(serializers.ModelSerializer): class Meta: model = Genre fields = ['id'] def create(self, validated_data): instance, _ = Genre.objects.get(**validated_data) return instance class MoviesSerializer(serializers.ModelSerializer): genres = GenresSerializers(many= True) class Meta: model = Movie fields = [ 'id', 'adult', 'backdrop_path', 'budget', 'homepage', 'original_language', 'original_title', 'overview', 'poster_path', 'release_date', 'revenue', 'runtime', 'status', 'tagline', 'title', 'genres' ] # extra_kwargs = {'id': {'read_only': True}} def create(self, validated_data): genres_data = validated_data.pop('genres', []) genresInstances = [] for genre in genres_data: genresInstances.append(Genre.objects.get(pk = … -
Issue with closing modals by clicking outside on specific page
I have implemented modals on my Django website using Bootstrap, where the modals open upon clicking buttons and close when clicking outside of them. This functionality works perfectly on most pages of my website, including the base template. However, I'm encountering an issue on my system page where the modals do not close when clicking outside of them. Here's the relevant code snippet from my base.html: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="{% static 'styles.css' %}"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL" crossorigin="anonymous"></script> </head> <body class="background-image-shop"> <!-- Navbar --> <nav class="main-top-navbar navbar navbar-light bg-black fixed-top navbar-custom"> <div class="container"> <div class="main-top-navbar-elements navbar-text"> <a href="{% url 'shop' %}" class="font-weight-bold text-light" style="margin-right: 20px;">Tribute |</a> <a href="{% url 'temples' %}" class="font-weight-bold text-light" style="margin-right: 20px;">Temples |</a> <a href="#" class="font-weight-bold text-light" style="margin-right: 20px;">Merchandise |</a> </div> <a href="#" class="navbar-brand">Your Logo</a> <!-- Add Product Button (visible for admin users only) --> {% if user.is_authenticated and user.is_superuser %} <button class="btn btn-outline-light" onclick="showAddProductModal()">Add Product</button> {% endif %} <!-- Search Bar --> <div class="shop-slogan"> <p>The Cards Await You!</p> </div> </div> </nav> <!-- Main content --> <div id="main-content"> <!-- Your website content here --> {% block body %} … -
Django message about waiting for process
I created app, which generate pdf file with some content. After filling form by user it is submitted and after about 10 seconds file preview is opening. I want to show message that user should wait for file after hiting Submit. When I add a meesage it shows but not earlier than download start and message it is not visible (it shows too late). Actually to show the messege I need to comment line return responce my view: def pdf_create(request): if (request.method == 'POST'): form = MsdsForm(request.POST) messages.info(request, f'''Please wait for a file.''') if (form.is_valid()): cd = form.cleaned_data # A LOT OF CODE AND THINGS HERE wchich create pdf response = HttpResponse(pdf_output, content_type='application/pdf') response['Content-Disposition'] = f"filename=some_file.pdf" return response else: form = MsdsForm() return render(request, 'msds_form.html',{'form':form}) I searched google for couple of hours and didn't find simple solution. I omit some details or it isn't simple way to do that? I don't know if it is essential in this case but I don't use models. -
Error : Conversion 'rpy2py' not defined for objects of type
I am using python R library to implement the ERGM model to a data set. I am following the below approach def ergm_process(nodes, edges): try: logger.debug(f"Passed Node: {nodes}") logger.debug(f"Edges: {edges}") # Convert node and edge data for R nodes_df = pd.DataFrame(nodes) edges_df = pd.DataFrame(edges) nodes_df['Attendance'] = pd.to_numeric(nodes_df['Attendance'], errors='coerce') if 'id' not in nodes_df.columns: logger.error("Node data must include 'id' keys") return {"error": "Node data incomplete"} # R DataFrame Conversion nodes_r = pandas2ri.py2rpy(nodes_df) # Prepare node and edge data for R node_ids = nodes_df['id'].tolist() edges_tuples = [(edge['from'], edge['to']) for edge in edges] # Log and check edge tuples if not all('from' in edge and 'to' in edge for edge in edges): logger.error("One or more edges are missing 'from' or 'to' keys") return {"error": "Edge data incomplete"} flat_edges = [item for tup in edges_tuples for item in tup] # Setup R environment from rpy2.robjects.packages import importr base = importr('base') network = importr('network', on_conflict="warn") ergm = importr('ergm', on_conflict="warn") # Pass data to R ro.globalenv['nodes'] = nodes_r ro.globalenv['node_ids'] = ro.StrVector(node_ids) ro.globalenv['edges'] = ro.IntVector(flat_edges) # Flatten list of tuples # Run R code ro.r(''' print("Node IDs:") print(node_ids) print("Edges:") print(edges) net <- network::network(matrix(edges, byrow=TRUE, ncol=2), directed=TRUE, vertices=node_ids) # Ensure each attribute is set for (attr_name in colnames(nodes)) … -
How to check if a Django Model Instance contains a foreign key or not
I need to serialize data coming from Django Audit Log Entry in such a way that when in changes field There is a Field present which has a value of foreign key I need to fetch the value of that Foreign key from database and Change the Foreign key with the value. def get_changes(self, obj): changes_data = obj.changes if changes_data: model_name = obj.content_type.model_class().name try: field_mapping = getattr(ma_activity_tracker, f"{model_name}_display_atrb") except AttributeError: field_mapping = {} changes = {} for field, (old_value, new_value) in changes_data.items(): field_name = field_mapping.get(field, field) field_object = globals().get(model_name) print(field_object.User) # if isinstance(field_object, models.ForeignKey): if isinstance(field_object,models.ForeignKey): old_related_obj = field_object.related_model.objects.filter(pk=int(old_value)).first() new_related_obj = field_object.related_model.objects.filter(pk=int(new_value)).first() old_display_value = getattr(old_related_obj, field_name) if old_related_obj else None new_display_value = getattr(new_related_obj, field_name) if new_related_obj else None old_value = old_display_value new_value = new_display_value changes[field_name] = { "Old Value": old_value, "New Value": new_value } return changes return None This is what I tried but to do but the if block never gets executed -
Postman request to django with csrf works but not with request in NextJS
I'm currently working on a login system that needs a POST request and csrf authentication, so I started to work with postman and trying to send requests and took the snippet provided by the generator: const myHeaders = new Headers(); myHeaders.append("X-CSRFToken", "OmgnDDPPS4TRcERF3XNuYw4uJ3OBSwmmSq7ktjM5wX2oT02DWuWZwX57BOOLCA3h"); myHeaders.append("Cookie", "csrftoken=OmgnDDPPS4TRcERF3XNuYw4uJ3OBSwmmSq7ktjM5wX2oT02DWuWZwX57BOOLCA3h"); const requestOptions = { method: "POST", headers: myHeaders, redirect: "follow" }; fetch("http://127.0.0.1:8000/simulazione/api/prova_token/", requestOptions) .then((response) => response.text()) .then((result) => console.log(result)) .catch((error) => console.error(error)); The request above works in postman but if I took this code and write it in nextjs a got the forbidden error [30/Apr/2024 13:11:47] "POST /simulazione/api/prova_token/ HTTP/1.1" 403 2869 These below are the django view and settings: View @csrf_protect def prova_token(request): if request.method == 'POST': return JsonResponse("hello", safe=False) Settings CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True #CSRF_COOKIE_SECURE = False CSRF_COOKIE_HTTPONLY = False SESSION_COOKIE_SECURE = False SESSION_COOKIE_SAMESITE = None ALLOWED_HOSTS = [ ] CSRF_TRUSTED_ORIGINS = ["http://127.0.0.1:3000","http://localhost:3000"] CORS_ALLOW_HEADERS = [ 'accept', 'accept-encoding', 'authorization', 'content-type', 'dnt', 'origin', 'user-agent', 'x-csrftoken', 'csrftoken', 'x-requested-with', ] CORS_ALLOW_METHODS = [ 'DELETE', 'GET', 'OPTIONS', 'PATCH', 'POST', 'PUT', ] CORS_ALLOWED_ORIGINS = [ 'http://127.0.0.1:3000', 'http://localhost:3000', ] # Application definition INSTALLED_APPS = [ 'corsheaders', 'simulazione.apps.SimulazioneConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_nextjs', 'rest_framework', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] I … -
Djano server vs apache2.4 not the same results
i have a weird problem in my django application is that im i have an application runs tools based on their scripts all scripts works fine but only one that works in django server but not in apache2 and the Unable to retrieve my generation from the parent im not sure if this is the issue but i need help on this Thank you o tried to change many things in setttings config and using the apache as admin but im not sure what causing the issue -
Hi. I'm a beginner programmer and I'm trying to write a Django website right now
The fact is that I have no experience at all and I use a tutorial from the Internet. This is a lesson: https://proglib-io.turbopages.org/proglib.io/s/p/django-s-nulya-chast-2-registraciya-avtorizaciya-ogranichenie-dostupa-2022-06-08 When I try to implement the user registration function and in fact just copy the actions of the teacher, my site gives the error: TemplateDoesNotExist at /register/ I don't understand why this is happening... I do not know what I am doing wrong, like I installed pipenv install django-crispy-forms, I only used the pip install django-crispy-forms command, because this command was not executed. I did everything according to the tutorial. -
How can we create authentication system in Django using MongoDB database?
I have a Django project where I am trying to set up authentication system with mongo db I followed various tutorials and documentation but still facing issues. I have tried with djongo module with django to connect mongo db. Also I have custom user. also tried custom authentication backend for mongo db -
Deployment: Procfile with Django Project Structure for more than one App
I need to know how you normally solve this issue. When you start a project, django creates a folder for the project and a second one inside it with the exact same name and the files like: settings.py, init.py, wsgi.py, etc. After Im done with the repo I delete one of the two folders with the same name in order to let Procfile find project.settings inside the wsgi.py. I want to be able to run the Procfile considering the original structure, because I want to learn how to create more than one app inside a project. My exact question is. How should I setup my procfile? right now is like this: web: gunicorn expenses.wsgi --log-file - But Then Procfile doesn't find expenses.wsgi This is my structure: v expenses v expenses > static __init.py asgi.py settings.py urls.py wsgi.py > finances manage.py Procfile requirements.txt runtime.txt I tried changing the Procfile from gunicorn expenses.wsgi to gunicorn expenses.expenses.wsgi but then I will tell my to change os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'expenses.settings') inside the wsgi.py I tried changing the wsgi.py from os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'expenses.settings') to os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'expenses.expenses.settings') but then it will tell me that it couldn't find the module finances. -
Djnamic checkbox, change and disabled or unhide when select
I have three columns named "passive", "discount" and "discountprice" in the rows coming from the database. I use checkbox. If the passive is full, when one of the data-x with the passive label is selected, the others will be disabled. If the discount is full, when one of the ones with the data-y discount tag is selected, the discount price of those with the same discount tag will replace the normal price. It cannot be both discounted and passive. There may be different discount groups or liability groups. I'm stuck. What I wrote was of no use. html {% for mal in mlazm %} <input class="form-check-input" type="checkbox" value="{{ mal.0 }}" name='mlzm{{ forloop.counter }}' data-price="{{ mal.3 }}" data-bprice="{{ mal.7|default:'0' }}" id="{{ mal.0 }}{{ mal.0 }}" {% if mal.4 %}disabled{% endif %}> {%endfor%} js var $checkboxes = $('.myCheckBox').change(function() { var $checked = $checkboxes.filter(':checked'); if ($checked.length >= 3) { $checkboxes.filter(':not(:checked)').prop('disabled', true); } else { $checkboxes.prop('disabled', false); } }); -
My context processor document is being a complete arse
I am literally going to scream. Why can I not get any bloody text to appear from my function in my contect-processor.py to work? I am going to scream so bloody loudly because I am fed up of Django not doing as it's told. PROJECT -|project -|careers -|models.py -|context_processor.py -|templates -|template.html #context_processors.py from .models import Careers def careers_exist(request): # Check if there are any active careers careers_available = Careers.objects.filter(active=True).exists() # Prepare the context dictionary based on availability if careers_available: header = {'header': 'Current vacancies'} else: header = {'header': 'No Vacancies'} return {'header' : header} #template.html <h2>{{ header.header }}</h2> Why is my template still blank despite doing everything correctly. What a stupid bloody thing. -
Which languange/framework should I use? [closed]
I'm getting ready to do my final project. It should be a web app that will show fitness progress by entering it into the system. The progress just given, which has to be written down by the user, will be shown in the form of a graph. I am mainly concerned about the look of the overall application, but at the same time a good backend of course with a database. The original idea was to use Python with Django and React for frontend. But recently I was recommended to use Next.js for both frontend and backend. What is your opinion on what you would use? Or do you have any other opinion? -
Photo upload app Using Flutter and Django
I want to make a (Photo Upload app ) using Flutter and Django Does anyone here have any experience using the Django / Django REST framework, as the backend for a mobile app built with Flutter which has the feature of uploading multiple photos? or anyone who built any apps like the feature of Facebook? If there are any please give me your GitHub repository link or teach me how to build this featured app or if there exists any course please suggest me. ..................... -
Choose which model manager to use when doing prefetch_related?
I have a Product model in my Django app, which uses a custom model manager where all the prefetch_related statements are made: class ProductManager(models.Manager): def get_queryset(self): return ( super() .get_queryset() .select_related("core_product") .prefetch_related("images") .prefetch_related("bundled_products") ) class Product(models.Model): _base_manager = ProductManager objects = ProductManager() # ... model fields This works fine; when I use the ORM and within the Admin the custom manager is used, preventing a whole bunch of duplicate queries. The problem is when I have another model that has a prefetch_related to the Product model: it now inherits all the prefetch_related from the Product, even though that's not necessary. It causes a whole bunch of unnecessary queries to be made. class OfferManager(models.Manager): def get_queryset(self): return ( super() .get_queryset() .select_related("flag") .prefetch_related("condition_products") .prefetch_related("limited_to_users") .order_by("-priority") ) Here the condition_products field is that Product model from above, and just by including this prefetch_related, all of its prefetch_related statements are also inherited. How can I prevent this from happening? Can I specify which object manager to use in the prefetch_related - so that is uses a "bare" manager? -
Django: how to filter based on custom field
I have a custom field in my extra action view that gets added by overriding to_representation() in serializer. I want to add a filter based on that value. How can I achieve that? views.py class MyFiltersetclass(filters.Filterset): name = filters.CharFilter(lookup_expr="exact", field_name="name") class Meta: model= MyModel fields = ["name"] class MyViewset(): .... @action(detail=True, method=["get"], queryset=MyModel.objects.filter(type=1), serilizer=MyModelSerializer, filterset_class=MyFiltersetclass) def action(self, request, *args, **kwargs): qs = self.get_object() queryset = obj.filter_queryset(queryset) page = obj.paginate_queryset(queryset) if page: serializer = obj.get_serializer(page, many=True) else: serializer = obj.get_serializer(queryset, many=True) return obj.get_paginated_response(serializer.data) model.py class MyModel(models.Model): name = models.TextField(blank=True, null=True) summaries = models.JSONField(blank=True, null=True) @property def summary(self): if not self.summaries: return {} return custom_func(self.summaries) class Meta: db_table = "model_view_1" managed = False serializer.py class MyModelSerializer(serializers.ModelSerializer): summary = serializers.ReadOnlyField() def to_representation(self, instance): data = super().to_representation(instance) summary = data.pop("summary") data["field_1"] = summary.get("field_1") return {**data} class Meta: model = MyModel exclude = ["summaries"] Now I want to add a filter that could filter based on field_1 just like how we have added filter for name in filterset class. -
How we can notify mobile app about messages (Django/React Native)?
What is the best implementation of notifications (about messages, new posts) to the client, Websockets, push notifications, or webhooks? The project consists of a server part in Django and React Native on the client. WebSockets, WebHooks, PUSH -
Extract the item image out of an RSS feed (multiple RSS feed types - feed parser/python)
Working on a project that pulls articles from 20+ rss feeds and the the variety of feed formats for where the articles image is, is driving me bonkers. I'm happy for the articles image to be missing in some cases, and I'll fall back to a set image but I don't want that happening more than 20% of the time. Using Python & Feedparser (DJANGO Project) I've gotten this far: # Try and get the image url try: # Looking for images embedded in enclosures post_image = sanitize_url(str(c.enclosures[0].href)) except: try: # Looking for images embedded in media content post_image = sanitize_url(str(c.media_content[0]["url"])) except: try: # Looking for images embedded in content post_image = sanitize_url(c.content[0]["value"]) except: post_image = "no image found" Had to build a sanitise URL function that does 3 things: Takes a string that extracts out a URL (in situations where the above pulls more than the URL) Trims URLS down to remove parameters that might cause problems i.e 342.jpg?w=25 Then does a final check of the string to make sure it has a mimetype in case the final url is not an image. I'm going in circles here, for every example of an RSS feed this does work on, … -
why i can not deploy python web app easily?
why I can not deploy the Python web application and put it in a folder like the WWW folder of the Apache server so I can access it immediately? like any server-side programming language like PHP? always I have to find a VPS service, of a Cloud computer to be accessed as root, put my files then run the server of python with another server like Nginx or Apache and I have to do a lot of configuration, why it is not like PHP I can through it in the folder of the server and install PHP and this is everything? -
allow locally hosted dockerized django app to be accessed from the interweb through a local dockerized traefik instance?
The problem: From a browser on my windows machine, I can access the default django page via: localhost:5000 192.168.1.100:5000 But, not via my domain example.com From the same windows machine: I can access the traefik dashboard via monitor.example.com So I know that the routing from the interweb to an internal docker container works. Note: django app is minimum required for django app to display django default page My home lab setup using Cloudflare to point example.com to my external IP address Local edge router port forwarding 80, 443 to docker-main server (x.x.x.165) docker-main server hosting traefik docker instance docker desktop on windows hosting simple django app (x.x.x.100) Note: using cloudflare origin certificates, rather than letsencrypt The traefik docker-compose.yml file is: networks: mynet: external: true services: traefik: image: docker.io/library/traefik:2.11.2 container_name: traefik ports: - 80:80 - 443:443 # -- (Optional) Enable Dashboard, don't do in production - 8080:8080 environment: - CF_DNS_API_TOKEN=[cloudflare token] - TZ=[local timezone] volumes: - /var/run/docker.sock:/var/run/docker.sock:ro - ./config/traefik.yml:/etc/traefik/traefik.yml:ro # For the static configuration - ./config/config.yml:/etc/traefik/config.yml:ro # For any dynamic configuration you add - ./certs:/certs:ro # location for the certs - ./logs:/var/log/traefik labels: - "traefik.enable=true" - "traefik.http.middlewares.traefik-auth.basicauth.users=admin:[password]" - "traefik.http.middlewares.traefik-https-redirect.redirectscheme.scheme=https" - "traefik.http.middlewares.sslheader.headers.customrequestheaders.X-Forwarded-Proto=https" - "traefik.http.routers.traefik.entrypoints=web" - "traefik.http.routers.traefik.rule=Host(`monitor.example.com`)" - "traefik.http.routers.traefik.middlewares=traefik-https-redirect" - "traefik.http.routers.traefik-secure.entrypoints=websecure" - "traefik.http.routers.traefik-secure.rule=Host(`monitor.example.com`)" … -
I'm using Django and django-auth-ldap. How do I make all users to be staff?
I'm using django-auth-ldap for athentication. I want all new users to be assigned as staff. How do I do that? I know about AUTH_LDAP_USER_FLAGS_BY_GROUP, but I don't want to bother assigning people to a specific group. I know that there exists django_auth_ldap.backend, but I can't find a good working example of it. As a follow up (or combination?), I want to assign a set of default user permissions, for new users. Thanks. -
Unauthorized (401) while i sent a Post request to the server
when i try to add a post to my server i get 401 Unauthorized i sent my jwt in postman with Bearer jwt but nothing change . i think the probleme in the api where exactly i don't have any idea i use django as backend and react as frontend those are all my code urls.py : from django.contrib import admin from django.urls import path, include, re_path from django.views.generic import TemplateView urlpatterns = [ #path('admin/', admin.site.urls), path('auth/', include('djoser.urls')), path('auth/', include('djoser.urls.jwt')), path('', include('crm.urls')), ] urlpatterns += [re_path(r'^.*', TemplateView.as_view(template_name='index.html'))] views.py : from django.shortcuts import render ,redirect ,get_object_or_404 from rest_framework.parsers import MultiPartParser, FormParser from .serializers import PostSerializer from rest_framework.viewsets import ModelViewSet, GenericViewSet from .forms import CreateUserForm, LoginForm from rest_framework.response import Response from rest_framework import status #, UploadForm from rest_framework.decorators import api_view, action from django.contrib.auth.decorators import login_required, user_passes_test from .models import Post, PostImage # - Authentication models and functions from django.contrib.auth.models import auth from django.contrib.auth import authenticate, login, logout def homepage(request): return render(request, 'crm/index.html') def register(request): form = CreateUserForm() if request.method == "POST": form = CreateUserForm(request.POST) if form.is_valid(): form.save() return redirect("my-login") context = {'registerform':form} return render(request, 'crm/register.html', context=context) def my_login(request): form = LoginForm() if request.method == 'POST': form = LoginForm(request, data=request.POST) if form.is_valid(): username … -
Is there a way to annotate the count for all objects without grouping by another column?
I have code that looks like the following: filtered_queryset = Object.objects.filter(...misc filters) match time: case "year": qs = filtered_queryset.annotate(year=TruncYear("created_at")).values("year") case "month": qs = filtered_queryset.annotate(month=TruncMonth("created_at")).values("month") case "week": qs = filtered_queryset.annotate(week=TruncWeek("created_at")).values("week") case _: qs = filtered_queryset final_count = qs.annotate(count=Count("id")) In each case, I am expecting data that looks like the following # Each case { [{ "TIME": ... "count": ... }, ... ] } # Default { [{ "count": ... }] } I was under the impression that Count() was a terminal expression in django and that the queryset would be evaluated. However, the default case returns a queryset instead of evaluating. What am I missing here that causes it to not evaluate the queryset? I know that I can just call filtered_queryset.count() instead of trying to do this via annotate, but it causes extra code to check for the default case and adds code smell.