Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting "404 Error: Page not Found" in Django-ninja API
I've faced this problem with all APIs for any application in the project. To be honest, I've no idea what triggers the problem. Probably, wrong import module or mismatch in urls. I'd like to show you my project structure for better understadning: Project structure Here's my code from news/views.py: from asgiref.sync import sync_to_async # Create your views here. from django.core.exceptions import ObjectDoesNotExist from ninja import Router from ninja.errors import HttpError from .models import News from .schemas import NewsIn router = Router(tags=["News"]) @router.post("/") async def create_news(request, data: NewsIn): news = await sync_to_async(News.objects.create)(**data.dict()) return {"id": news.id} @router.put("/{news_id}/") async def update_news(request, news_id: int, data: NewsIn): try: news = await sync_to_async(News.objects.get(id=news_id)) for key, value in data.dict().items(): setattr(news, key, value) await sync_to_async(news.save()) return {"success": True} except ObjectDoesNotExist: raise HttpError(404, "News not found") @router.delete("/{news_id}/") async def delete_news(request, news_id: int): try: news = await sync_to_async(News.objects.get(id=news_id)) await sync_to_async(news.delete()) return {"success": True} except ObjectDoesNotExist: raise HttpError(404, "News not found") And then code from core/urls.py: `from django.contrib import admin from django.urls import path from ninja import NinjaAPI from news.views import router as news_router from partners.views import router as partners_router from educational_programs_and_categories.views import program_router, category_router api = NinjaAPI() urlpatterns = [ path("admin/", admin.site.urls), path("api/", api.urls), ] api.add_router("news", news_router) api.add_router("partners", partners_router) api.add_router("educational_programs", … -
am having this error trying to run my django project runserver is not working
Traceback (most recent call last): File "C:\Users\user\Desktop\TECH STUDIO FILES\Ecommerce\ec\manage.py", line 22, in main() File "C:\Users\user\Desktop\TECH STUDIO FILES\Ecommerce\ec\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management_init_.py", line 399, in execute_from_command_line utility.execute() File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management_init_.py", line 392, in execute self.fetch_command(subcommand).run_from_argv(self.argv) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management_init_.py", line 261, in fetch_command commands = get_commands() ^^^^^^^^^^^^^^ File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management_init_.py", line 107, in get_commands apps = settings.INSTALLED_APPS ^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\conf_init_.py", line 54, in getattr self.setup(name) File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\conf_init.py", line 50, in _setup self.configure_logging() File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\conf_init.py", line 72, in configure_logging from django.utils.log import DEFAULT_LOGGING File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\log.py", line 7, in from django.views.debug import ExceptionReporter, get_exception_reporter_filter File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\views\debug.py", line 12, in from django.template import Template, Context, TemplateDoesNotExist File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\template_init.py", line 53, in from django.template.base import (ALLOWED_VARIABLE_CHARS, BLOCK_TAG_END, File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\template\base.py", line 19, in from django.utils.html import escape File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\html.py", line 14, in from .html_parser import HTMLParser File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\html_parser.py", line 12, in HTMLParseError = _html_parser.HTMLParseError ^^^^^^^^^^^^^^^^^^^^^^^^^^^ AttributeError: module 'html.parser' has no attribute 'HTMLParseError'. Did you mean: 'HTMLParser'? every thing but the server fails to run -
Using PyOTP library,giving message wrong OTP
I am using PyOtp library to generate 6 digit otp ,the backend I am using is python django and the frontend is react. My issue is that sometimes(not always) when I generate OTP and click to verify OTP,I enter the correct OTP which is generated but it gives me wrong OTP message and then when I resend OTP,it takes it as correct one.I am not able to figure out that why even after entering the correct OTP ,it is saying me that it is wrong OTP.What could be the issue.I am not using the latest version of PyOTP,could that be an issue or it is something related to time sync. Kindly help me on this. Thnakyou I used the library implemented in API created in python and integrated it in react. -
DRF formdata with file and nested array of objects not taking nested array of objects
Unable to send nested objects when using formdata. Since I have large number of files using base64 is not a solution. current solution was to use JSON.stringify from client side for product_timings and send it as a single field, But I would like to know if normal modal field with file upload is possible with DRF. Here is my APIView class ProductCreateApi(APIView): permission_classes = [permissions.DjangoModelPermissions] queryset = Product.objects.all().order_by("-created_at") parser_class = [MultiPartParser, FormParser, JSONParser, FileUploadParser] class ProductCreateSerializer(serializers.ModelSerializer): class ProductCreateProductTimingSerializer(serializers.ModelSerializer): class Meta: model = ProductTiming fields = ['start_time', 'end_time'] product_timings = ProductCreateProductTimingSerializer(write_only=True, many=True) product_images = serializers.ListField( child=serializers.ImageField(allow_empty_file=False, use_url=False), write_only=True ) class Meta: model = Product fields = '__all__' In post man I tired product_timings[0][start_time]: 09:30:00 product_timings[0][start_time]: 09:30:00 Still it is throwing validation error messages like { "product_timings": [ { "start_time": [ "This field is required." ], "end_time": [ "This field is required." ] } ] } Please note neither base64 image field for product_images nor single JSON field for product_timings is not the solution I'm looking for. -
Something similar to Counter in a Django table
I have a table in sqlite3 with a column that tells me the winners of a game: (computer = 1, human = 2, tie = 0) The model (I'm working on django) is something like this, at least the necessary part: class GameWinners(models.Model): CHOICES = [(0, 'Draw'), (1, 'Computer'), (2, 'Human')] game_winner = models.IntegerField(choices=CHOICES) I would like to obtain a dictionary that counts me the times that each one has won or the ties. something similar to Counter from collections: games = {0: 27, 1: 125, 2: 170} I know that I could do it this way: tie = GameWinners.objects.filter(game_winner=0).count() computer = GameWinners.objects.filter(game_winner=1).count() human = GameWinners.objects.filter(game_winner=2).count() games = {0: tie, 1: computer, 2: human} But I guess there must be a better way to do it. -
JavaScript: Problem accessing 'change' event for a file input
Aim I have two inputs: (1) a 'file-input', and (2) a 'text-input' I want to listen for a 'change' in 'file-input' (i.e. successful choice of file), and upon such a change set the 'text-input' value to the name of the file. Problem The 'change' event is not triggering when I use addEventListener When I use the input's 'onchange' attribute, it does trigger, but I still don't get access to files Context: This is for a Django project, with Bootstrap 5 on the frontend (NO JQuery). I am using Django Crispy Forms where possible, though I have removed them from this file (to see whether that was what was causing the problem - alas, it wasn't). Attempted Solutions I know this should be easy. I have seen lots of similar posts about this, and I set up a 'dummy' HTML script to ensure I'm not going mad. This is posted below and it works perfectly. <!DOCTYPE html> <html lang="en"> <head> <title>Document</title> </head> <body> <input type="file" name="file" id="file-input" accept=".mp3,.mp4,.mpeg,.mpga,.m4a,.wav,.webm"> <input type="text" name="text" id="text-input"> <script> const fileInput = document.getElementById("file-input"); const textInput = document.getElementById("text-input"); console.log(fileInput); console.log(textInput); fileInput.addEventListener('change', () => { console.log('change registered'); if (fileInput.files.length > 0) { console.log(fileInput.files); console.log(fileInput.files[0].name); textInput.value = fileInput.files[0].name; } }); … -
How to show the ForeignKey' content in Django template
I am beginner in django, there is a question i am fronting is that how to show the content of ForeignKey item, for example i have a table called company, there is a field "parentcompany" for storage the ForeignKey(UID) with the parentcompany, all the company is created on the this company table. I already been success to create this relationship, but I can not show the parentcompany's name in the template. I already tried using this {{company.parentcompany_id.companyName}}, but nothing is shown. -
How can I delete ManyToManyField on Django Model (used in Wagtail Page inheritor)?
I have such field: from wagtail.models import Page class MyModel(Page): ... many_to_many_field = models.ManyToManyField(ToClass, blank=False, related_name='+', verbose_name=_("My models")) ... I tried simply to comment it like this: from wagtail.models import Page class MyModel(Page): ... # many_to_many_field = models.ManyToManyField(ToClass, blank=False, related_name='+', verbose_name=_("My models")) But I've got 'django.core.exceptions.FieldError' while was executing 'python manage.py makemigrations': Traceback (most recent call last): File "D:\projects\myapp\manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "D:\Python311\Lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "D:\Python311\Lib\site-packages\django\core\management\__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "D:\Python311\Lib\site-packages\django\core\management\base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "D:\Python311\Lib\site-packages\django\core\management\base.py", line 443, in execute self.check() File "D:\Python311\Lib\site-packages\django\core\management\base.py", line 475, in check all_issues = checks.run_checks( ^^^^^^^^^^^^^^^^^^ File "D:\Python311\Lib\site-packages\django\core\checks\registry.py", line 88, in run_checks new_errors = check(app_configs=app_configs, databases=databases) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\Python311\Lib\site-packages\wagtail\admin\checks.py", line 70, in get_form_class_check if not issubclass(edit_handler.get_form_class(), WagtailAdminPageForm): ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\Python311\Lib\site-packages\wagtail\admin\panels\base.py", line 162, in get_form_class return get_form_for_model( ^^^^^^^^^^^^^^^^^^^ File "D:\Python311\Lib\site-packages\wagtail\admin\panels\base.py", line 48, in get_form_for_model return metaclass(class_name, tuple(bases), form_class_attrs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\Python311\Lib\site-packages\wagtail\admin\forms\models.py", line 124, in __new__ new_class = super(WagtailAdminModelFormMetaclass, cls).__new__( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ new_class = super().__new__(mcs, name, bases, attrs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\Python311\Lib\site-packages\modelcluster\forms.py", line 259, in __new__ new_class = super().__new__(cls, name, bases, attrs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\Python311\Lib\site-packages\django\forms\models.py", line 327, in __new__ raise FieldError(message) django.core.exceptions.FieldError: Unknown field(s) (many_to_many_field) specified for MyModel What is wrong? How can I delete it? -
post name, email and role in django backend, react frontend
i want to the admin to post name, email and role of a user using frontend, and its stored in backend of django, please note that i dont want the admin to store the password, the user will later on add it djangocode: class UserSerializer(serializers.ModelSerializer): class Meta: model = UserAccount fields = ['email', 'name', 'username', 'password', 'role'] def create(self, validated_data): password = validated_data('password') username = validated_data('username') user = UserAccount( email=validated_data['email'], role=validated_data['role'], name=validated_data['name'] ) if username is not None: username=validated_data['username'], if password is not None: user.set_password(validated_data['password']) user.save() return user react code: const handleSubmit = (event) => { event.preventDefault(); const data = { name : name, email : email, role: role }; console.log("data is "+data); axios.post('http://127.0.0.1:8000/api/register/', data) .then(response => console.log("got it"+response.data)) .catch(error => console.log(error)); console.log('name:', name); console.log('email:', email); console.log('role:', role); -
How to store an object id in django admin
I got a top model like Project, and many sub models like Store, Task, Bug, TestCase. I want to seprate project as isolated workspace in admin. when I select a project, store the current project id, and when I create sub model objects or view change list, all object is belong to this project. -
Unable to read django table in admin or through API
I've added few tables to django app, and two of them are acting weird. I'm unable to read these 2 tables through django admin or postman API however, I'm able to read these table through postgres(pg admin). I'm getting index error in django-admin and postman on these two tables(or django models). These tables has data in them as verified using pgAdmin. The tables are stored in postgres, and the DB is connected to django aplication. Any idea why this could be happening and possible solutions? -
Bad Request (400) on adding new domain from hostinger on vercel hosting
I have purchased domain from hostinger after adding the domain in the domain and changing the nameserver of hostinger to ns1.vercel-dns.com ns2.vercel-dns.com i validated the configuration but when i look the site it gives Bad Request (400) error . pushpblogs.fun Valid Configuration Redirects to www.pushpblogs.fun www.pushpblogs.fun Production Valid Configuration Assigned to main i waited for the dns to apply for 24 hours but still no change made. -
Mayan EDMS ,Calling the API remotely using AJAX getting CORS error
I am creating a new webapp that is going to be making calls to the Mayan EDMS API with javascript/ajax Currently i am getting a CORS error. My mayan installation is running inside a docker container. I did find in the settings for Django in the admin->settings-> Django there is a ALLOWED_HOSTS but there is a green checkmark which indicates it is overwritten by a env var. Any Idea what env var that would be. there is nothing obvious in the .env for the docker file It appears that django-cors-headers is there as well. Just not sure how to config How are other people dealing with this? Thanks randy -
Python route usage
How can I use $ in the python url . This is my usage from django.urls import include, path from vote import views urlpatterns = [ path(r'^$', views.index, name='index') ] but it ending with Using the URLconf defined in election.urls, Django tried these URL patterns, in this order: [name='index'] vote/ ^$ [name='index'] I need to get understand what is the best usage -
(Python/Django) Can I use Python's Django framework w/o using templates?
I am learning how to use the Django framework, and as I am learning about Django's template system, I was wondering, if it would be possible for me to use Django without using templates to render the necessary html documents from views? As an alternative to Django's template system, I would prefer to use JavaScript in order to make the necessary data queries from the sites database(s). This might seem counter productive, but in my opinion, I would prefer to learn the traditional front-end web stack(HTML, CSS, JS), and solidify my skills this way before going down the journey of template systems. At this point, I would be using Django only as a back-end until I was ready to incorporate templates into my dev process. Thank you in advance! This my first post on SO, take it easy! I have tried to use Django's template system, but It's a little comprehensive to learn on top of HTML and CSS at the same time. -
Gives 404 error even when audio file exists: GET /data/audio/5dc18de4d34d12a20b21fbc2506b423f35cfd7fc0fc931874bdfe13b1578aeee.m4a HTTP/1.1" 404 179
enter image description here The file is present and still gives a 404 and works on other machine perfectly fine. It is an audio file which is saved inside data/audio and that is where the local is trying to search which is correct location but still gives 404 -
DJango how to manage redshift connection in a server
I am using redshift in my django application. I know we can use psycopg2 for redshift, but i am planning to use the aws library pip install redshift_connector Currently for every query in my view i run. So here I see its taking time to connect to redshift everytime and thats consuming time than then query time. conn = redshift_connector.connect( host='host.docker.internal', database='dev', port=5439, user='user', password='kkshdjhjhsdj' ) cursor = conn.cursor() cursor.execute("SELECT CURRENT_TIMESTAMP") data = cursor.fetchall() I am not sure how django keeps connection live for database and effeciently handle. If we have to use some thirdparty databases then how to handle connection. Can someone guide me what else needs to be taken care. -
Django template: how to show decimal value as currency format with dollar sign, thousand separator with zero or two decimal points
The field in models.py is: order_amount = models.DecimalField(max_digits=12, decimal_places=2, blank=True, null=True) if the order_amount value is 12345.67, how to display it in Django template for the below two formats: without decimal point: $12,345 without two decimal points: $12,345 -
Am getting empty strings in my django database when trying to save JSON data from ajax request
Am new in coding skills so am creating a website now am stuck , in my website users answer a question by clicking one button choice out of many button choices , i want when a button is clicked data to be sent to the django database but unfortunately when i click the button only empty strings is sent to the database views.py import json from django.http import JsonResponse, HttpResponseRedirect from django.shortcuts import render, redirect from django.urls import reverse from .models import JasonData from .form import QuestionForm # Create your views here. def index(request): """The homepage for Stay_healthy""" return render(request, 'Stay_healthy/index.html') def redirect_to_index(request): """The homepage for Stay_healthy""" return HttpResponseRedirect(reverse('index', args=None)) def json_data_store(request): if request.method == 'POST': # this runs incase the request is an ajax if request.headers.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest': data = json.loads(request.body) form = QuestionForm(data) if form.is_valid(): form.save() return JsonResponse({'status': 'success'}) else: return JsonResponse({'status': 'error'}) else: # this runs incase the request is not ajax form = QuestionForm(request.POST) if form.is_valid(): form.save() return redirect('index') else: form = QuestionForm() return render(request, 'Stay_healthy/question_detail.html', {'form': form}) def check_data(request): stored_data = JasonData.objects.all() return render(request, 'Stay_healthy/check_data.html', {'stored_data': stored_data}) models.py from django.db import models # Create your models here. class JasonData(models.Model): patient_data = models.JSONField(blank=True, null=True, default=dict) form.py … -
How to send multiple objects on serializers.Serializer (got non_field_errors)
I'm trying to send multiple data through a create viewset method to a serializer. However when doing that I get an error as follows: enter image description here Im using many attribute into the serializer, but I sill get the same error. I'm posting data like this: [ { "weekday":"day", "start_time":"time", "end_time":"time" }, { "weekday":"day", "start_time":"time", "end_time":"time" } ] This is the viewset and serializer code: viewset.py class SpecialistAvailabilityView(viewsets.ModelViewSet): model = SpecialistAvailability permission_classes = [IsAuthenticated, IsSpecialist] def get_serializer_class(self): saving_actions = ["create", "update", "partial_update"] if self.action in saving_actions: return WeekDayTimeSerializer return SpecialistAvailabilitySerializer def get_queryset(self): queryset = SpecialistAvailability.objects.filter( specialist__user=self.request.user ).order_by('-start_time__week_day') return queryset def translate_availability(self, data): pass def create(self, request, *args, **kwargs): serializer = WeekDayTimeSerializer(data=request.data, many=isinstance(request.data, list)) print(serializer.initial_data) print(serializer.is_valid()) if serializer.is_valid(): self.translate_availability(serializer.validated_data) return super().create(request, *args, **kwargs) serializer.py import pytz from datetime import datetime from rest_framework import serializers from apps.specialist.models.specialist_availability import SpecialistAvailability from apps.specialist.utils import WEEKDAYS class WeekDayTimeSerializer(serializers.Serializer): weekday = serializers.ChoiceField(choices=WEEKDAYS, required=True) start_time = serializers.TimeField() end_time = serializers.TimeField() # TODO ADD TIME AND WEEKDAY CHECKING # START TIME MUST BE LESS THAN END TIME # JUST ONE DAY MUST BE SENDED IF MANY def validate(self, attrs): self.validate_start_time(attrs['start_time']) self.validate_start_time(attrs['end_time']) self.validate_end_time return super().validate(attrs) def validate_start_time(self, start_time): try: datetime.strptime(start_time, "%H:%M") except: raise serializers.ValidationError("Wrong time format") return start_time … -
Django payment intigration
i want to add a donation page in my DJango project but i have not seen any proper intigration of payment gateway in any articles and videos so plzz help me and give the proper code and explanation. in stripe apy key is not supported in india in razorpay when click on payment error occur amount exceed -
django rest framework: Getting "This field may not be null." with FloatField even with blank=True
Here dummy code to show my problem: In my django models.py I have something like: class MyModel(Model): test_field = SlugField(blank=True, null=False) # some other not-null not-blank fields here def save(self, *args, **kwargs): self.test_field = .... # Setting with a value calculated form the other not-null not-blank fields Here my serializer: from rest_framework import serializers class MyModelSerializer(serializers.ModelSerializer): class Meta: model = MyModel fields = [ ...., 'test_field', ] In my views.py something like: def post_endpoint(request): data = JSONParser().parse(request) serializer = MyModelSerializer(data=data) if serializer.is_valid(): .... serializer.save() return JsonResponse(serializer.data, status=201) This is working as expected: I can send an object to my post_endpoint without my test_field and I get my result with test_field set as expected. serializer.is_valid() returns True in that case. The problem? I need that same functionality but with a FloatField instead of SlugField. But I noticed serializer.is_valid() returns False in that case and I get a "This field may not be null." in serializer.errors in my view function. How is FloatField different from SlugField ? How can I get the expected functionality also with FloatField? djangorestframework==3.14.0 Django==4.0.5 -
Browser not downloading request response, even though Content-Disposition is 'attachment' and Content-Type is 'text/plain'
I am under the impression that if Content-Disposition is set to 'attachment' and Content-Type is set to'text/plain', the browser should download the request response as a .txt, but when I make the request locally on my browser, a download is not initiated. On other pages, like https://textdoc.co/, my browser does download a similar request response, so it doesn't seem like a browser issue. On my server: from django.http import FileResponse ... with open('readme.txt', 'w') as f: f.write('Create a new text file!') response = FileResponse(open("readme.txt", "rb"), as_attachment=True, filename="test.txt") response['Content-Type'] = 'application/download' return response After making this request on my client I get the following results in the google chrome developer console: **Response Headers:** Access-control-allow-origin: http://localhost:3000 Allow: POST, OPTIONS Content-Disposition: attachment; filename="test.txt" Content-Length: 23 Content-Type: application/download Cross-Origin-Opener-Policy: same-origin Date: Thu, 08 Jun 2023 21:46:37 GMT Referrer-Policy: same-origin Server: WSGIServer/0.2 CPython/3.11.3 Vary: Accept, origin X-Content-Type-Options: nosniff X-Frame-Options: DENY **Response:** Create a new text file! I was expecting this request to cause the browser to prompt the user to download the file. However, the browser is not prompting the user. Here is an example of what the prompt looks like on Google Chrome: -
request.POST.get() is returning nothing
The problem is though I am putting correct data in the form, it always redirects to the except block of views.py I tried to change and refresh data in the database but didn't work out. Here is my views.py @login_required(login_url='login') def card_payment(request): card_no = request.POST.get('cardNumber') pay_method = 'Debit card' MM = request.POST['MM'] YY = request.POST['YY'] CVV = request.POST['cvv'] request.session['dcard'] = card_no try: balance = Cards.objects.get(Card_number=card_no, Ex_month=MM, Ex_Year=YY, CVV=CVV).Balance request.session['total_balance'] = balance mail1 = Cards.objects.get(Card_number=card_no, Ex_month=MM, Ex_Year=YY, CVV=CVV).email if int(balance) >= int(request.session['pay_amount']): # print("if ma gayu") rno = random.randint(100000, 999999) request.session['OTP'] = rno amt = request.session['pay_amount'] username = request.user.get_username() print(username) user = User.objects.get(username=username) mail_id = user.email print([mail_id]) msg = 'Your OTP For Payment of ৳' + str(amt) + ' is ' + str(rno) # print(msg) # print([mail_id]) # print(amt) send_mail('OTP for Debit card Payment', msg, 'nafibinnoor@gmail.com', [mail_id], fail_silently=False) return render(request, 'OTP.html') return render(request, 'wrongdata.html') except: return render(request, 'wrongdata.html') HTML form for this view <form action="pessanger_detail_def/card_payment" method="POST" class="creditly-card-form agileinfo_form"> {% csrf_token %} <section class="creditly-wrapper wthree, w3_agileits_wrapper"> <!--<label>Name On Card</label></br> <input type="text" class="pipo1" placeholder="John smith" name="name"></br>--> <label>Card Number</label> <input type="text" class="pipo1" placeholder="**** **** **** *****" name="cardNumber"></br> <label>CVV</label></br> <input type="text" class="pipo1" placeholder="***" name="cvv"><br> <label>Expiration Date</label></br> <input type="text" class="pipo2" placeholder="MM" name="MM"><label> </label><input type="text" class="pipo2" placeholder="YY" … -
Trying to write a django query to count different rows and find the max value
I have a django app that stores documents (photos, pdfs, video, ect.) as well as some metadata (year, decade, etc.). The metadata is stored in a JSONField called metadata in a model called DocumentMetaData. I would like to create a django query that allows me to find the maximum number of documents for a certain metadata name. For example, all documents have in their metadata field a "Decade" value. I can loop through all the decades to find the decade with the most documents, like this: decades = ['1860', '1870', '1890', '1900', '1910', '1920', '1930', '1940', '1950', '1960', '1970', '1980', '1990', '2000','2010', '2020'] max_count = 0 max_decade = "" for decade in decades: count = DocumentMetaData.objects.filter(metadata__has_key='Decade').filter(metadata__Decade=decade).count() if count > max_count: max_count = count max_decade = decade Can I replace this code with a django query using annotate and aggregate? I am just not seeing how to create a query with a loop in it. Thanks!