Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Retrieving image with javascript to display Django
I am trying to retrieve an image via Javascript function that calls a function from my views that has the image. I need help with populating the image: Views: def view_company_logo(request): print('GETTING LOGO') client = Client.objects.get(user=request.user) logo ='' try: logo= client.customer.first().logo.logo print('GOT LOGO') return JsonResponse({'logo':logo, 'media_url':settings.MEDIA_URL}, safe=False) except Exception as e: print(e) return JsonResponse({'logo':logo}, safe=False) HTML File: I am using the image id "company_logo" here: In the bottom, I am using Javascript: <script type="text/javascript"> function get_company_logo() { $.ajax({ url: '/get/company_logo/', method: 'GET', success: function (data) { console.log(data['logo']) display_image(data['logo']) } }) } function display_image(image){ document.getElementById("company_logo").src = image.url; } get_company_logo(); </script> Called by URL: url(r"^get/company_logo/$", views.view_company_logo), How do I get the image to display? -
page-break not working on headings ( python, weasyprint )
I want to create a pdf out of html content. I use beautifulsoup to get html string and then create PDF using weasyprint and python out of it. I have issue when i want to show headings ( specifically h3 ) on a new page ( though this doesn't work for any of the h tags ). Now, I have this code in html {% block report %} <style> h3 { page-break-before:always; } </style> <div class="container" style="padding-top:45px"> <div class="row"> <div class="col-12"> <h1 id="h1-title" class="mb-5">{{report.title|safe}}</h1> <div class="control-head"> <h3 id="1.-first-section">1. First Section</h3> <hr> <p>{{obj.some_content_one|safe}}</p> </div> <div class="control-head"> <h3 id="2.-second-section">2. Second Section</h3> <hr> <p>{{obj.some_content_two|safe}}</p> </div> <div class="control-head"> <h3 id="3.-third-section">3. Third Section</h3> <hr> <p>{{obj.some_content_three|safe}}</p> </div> <div class="control-head"> <h3 id="4.-fourth-section">4. Fourth Section</h3> <hr> {{obj.some_content_four|safe}} </div> </div> </div> </div> {% endblock report %} And when i use page-break-after in h3 tags, weasyprint only renders content until this first h3 including the h3.string... If i use page-break-before: always; then weasyprint renders first "control-head" and {{obj.some_content_one|safe}} and stops rendering second at the end of the page where second h3 is ( it basically renders second control-head h3.string and content from {{obj.some_content_two|safe}} until it fills the page and then stops rendering pdf any further).. I tried using page-break-after/before on … -
test if any object refer to by a base model has a value specified in django orm
Well consider two models: class School(models.Model): name = models.TextField(default="hello world") class Student(models.Model): key = models.TextField(default="somedata") a = models.ForeignKey(Vendor) So a many to one relationship from School to Student How would I get (from School's perspective) all School which have a Student that set "key" to the required value? Especially in the already existing query: School.objects.filter(Q(name="hello world") | Q(queryshould_here)) I've tried A.objects.filter(Q(name="hello world") | Q(student__key="test")) However that (obviously) fails with: django.core.exceptions.FieldError: Unsupported lookup 'v' for ManyToOneRel or join on the field not permitted. -
Large GET Request to DRF causes 504 Gateawy Time-out
I have a database with about 3 million records, and I want to retrieve these records to be displayed by a Django web app. However, attempting to pass these via Model.objects.all() passed by templating a javascript variable causes my Apache server to crash. So, I created a Django REST Framework endpoint which returns these records. But, this returns a 504 Gateway Timeout when I make the GET request. How can I retrieve all these records to display in my Django app? I would like to avoid paging or filtering. -
Error while using "pyttsx3" with "react-speech-recognition"
Error in text-to-speech: run loop already started Backend Code from django.shortcuts import render from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status import os import google.generativeai as genai from dotenv import load_dotenv import pyttsx3 from langchain_google_genai import GoogleGenerativeAIEmbeddings from langchain_community.vectorstores import FAISS from langchain_google_genai import ChatGoogleGenerativeAI from langchain.prompts import PromptTemplate from langchain.chains.question_answering import load_qa_chain # Load environment variables load_dotenv() genai.configure(api_key=os.getenv("GOOGLE_API_KEY")) # Initialize TTS Engine engine = pyttsx3.init() voices = engine.getProperty('voices') engine.setProperty('voice', voices[0].id) class VoiceBotView(APIView): def post(self, request): user_message = request.data.get('query') VoiceBotFunction.speak("Searching") try: response_text = VoiceBotFunction.get_voice_response(user_message) VoiceBotFunction.speak(response_text) print(response_text) return Response({'query': user_message, 'response': response_text}) except Exception as e: print(f"Exception occurred: {e}") return Response({'error': 'Internal server error'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) class VoiceBotFunction: def speak(text, rate=120): try: engine.setProperty('rate', rate) engine.say(text) engine.runAndWait() # run and wait method, it processes the voice commands. engine.stop() if engine._inLoop: engine.endLoop() except Exception as e: print(f"Error in text-to-speech: {e}") def get_conversational_chain(): prompt_template = """ Answer the question as detailed as possible from the provided context, make sure to provide all the details, if the answer is not in provided context just say, "Answer is not available in the Database", don't provide the wrong answer\n\n Context:\n {context}?\n Question: \n{question}\n Answer: """ model = ChatGoogleGenerativeAI(model="gemini-pro", temperature=0.3) prompt = PromptTemplate(template=prompt_template, input_variables=["context", "question"]) … -
graphql query using django for xml data
How can we implement GraphQL query that allows querying values from any selected set of elements from the below xml file using django? <encspot> <file type="audio"> <Name>some filename.mp3</Name> <Encoder>Gogo (after 3.0)</Encoder> <Bitrate>131</Bitrate> <Response> <data> <text>sample data</text> <frequency>200Hz</frequency> </data> </Response> </file> </encspot> -
Template Rendering Issue
I have done Url shortner using django in Python. I am unable to render the template and getting the error as shown. Please help me with this. error picture I have tried some methods and tried ChatGPT, somehow I didn't meet with the answer I was searching for. Anyone help me to sort this out.. -
How to Add Cron Jobs from Multiple Django Applications to Crontab Without Conflict?
I have two Django applications that I'm running on Amazon Linux using Gunicorn. Each Django application has its own cron jobs defined in the settings.py file using django_crontab. However, I'm facing issues when trying to add cron jobs from both applications to the crontab. Here is the structure of my applications: Application 1 /path/to/app1/ ├── manage.py ├── app1/ │ ├── settings.py │ └── ... Application 2 /path/to/app2/ ├── manage.py ├── app2/ │ ├── settings.py │ └── ... In settings.py of each application, I have defined cron jobs like this: # app1/settings.py CRONJOBS = [ ('*/10 * * * *', 'app1.cron.my_scheduled_task'), ] # app2/settings.py CRONJOBS = [ ('*/15 * * * *', 'app2.cron.another_scheduled_task'), ] When I try to add the cron jobs for each application using the following commands: cd /path/to/app1 source /path/to/venv/bin/activate python manage.py crontab add cd /path/to/app2 source /path/to/venv/bin/activate python manage.py crontab add When i do the python manage.py crontab add for the second application, i get an error RuntimeError: No job with hash 65f37180992aa5435pidg617281f3e6 found. It seems the crontab is out of sync with your settings.CRONJOBS. Run "python manage.py crontab add" again to resolve this issue! This hash ID corresponds to a job from the first application. How … -
forms.ModelMultipleChoiceField with widget=FilteredSelectMultiple not working on custom new Django Admin
I am trying to show the forms.ModelMultipleChoiceField on custom new admin form page but it doesn't seem to show it the way it is showing on the Django page that was already made e.g. model product django admin page. Mine forms.ModelMultipleChoiceField is looking like this: Shows how my forms.ModelMultipleChoiceField looks like When it should look like this: Shows how forms.ModelMultipleChoiceField should look like forms.py: from django import forms from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit from django.contrib.admin.widgets import FilteredSelectMultiple from home.models import Collection, Tag, Product class ProductAssignForm(forms.Form): from_name = forms.CharField(required=True, max_length=255, label='From Name') to_name = forms.CharField(required=True, max_length=255, label='To Name') assign_collections_name = forms.ModelMultipleChoiceField( queryset=Collection.objects.all(), required=False, widget=FilteredSelectMultiple( verbose_name='Collections', is_stacked=False ), label='Assign Collection Name' ) tags = forms.ModelMultipleChoiceField( queryset=Tag.objects.all(), required=False, widget=FilteredSelectMultiple( verbose_name='Tags', is_stacked=False ), label='Tags' ) class Meta: model = Product fields = ['collections', 'tags'] # Include the tags field in the fields list def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.form_method = 'POST' self.helper.add_input(Submit('submit', 'Assign Products')) partial code form admin.py: @admin.register(Product) class ProductAdmin(admin.ModelAdmin): form = ProductAdminForm list_display = ('name', 'quantity', 'price', 'first_collection') exclude = ('user', 'updated',) def save_model(self, request, obj, form, change): if not obj.user: obj.user = request.user obj.save() def first_collection(self, obj): first_collection = obj.collections.first() return first_collection.name if first_collection … -
Configuring SSH port forwarding for Django app on VPS: Browser access issues
I am running a Django application on my laptop at port 8000. The app works locally and I want to make it accessible to others over the internet via SSH remote port forwarding to a VPS. I've connected to my VPS using the following command: ssh -R 9090:localhost:8000 remote_user@remote_host I tried to confirm that the port forwarding works: netstat -tunl | grep 9090 tcp 0 0 0.0.0.0:9090 0.0.0.0:* LISTEN tcp6 0 0 :::9090 :::* LISTEN I can use telnet on the VPS to connect to port 9090 and issue a GET request to retrieve the home page. This part works as expected. However, when I try to open the application in a browser using http://remote_host:9090, it does not load and I get a 503 error. I have already added a rule to the INPUT chain of iptables on my VPS to allow incoming connections to port 9090: sudo iptables -A INPUT -p tcp --dport 9090 -j ACCEPT I've temporarily uninstalled iptables on my laptop. My questions are: Am I missing something in my setup that prevents the application from being accessible over the internet? Was I wrong to assume that this method would make my app accessible over the internet … -
Nested query in Django, need to compare the processing time
time_limit = timezone.now() - timedelta(hours=30) time_limit_str = time_limit.strftime('%Y-%m-%d %H:%M:%S') in_review_records = RequestedData.objects.filter( Q(status='In Review') & ( Q(additional_details__isnull=True) | Q(additional_details__processing_details__isnull=True) | ( Q(additional_details__processing_details__has_key=account_name) & Q(additional_details__processing_details__account_name__lte=time_limit_str) ) | ( Q(additional_details__processing_details__isnull=False) & ~Q(additional_details__processing_details__has_key=account_name) ) ) ).annotate(processing_details=KeyTransform('processing_details', 'additional_details')).annotate(account_name=KeyTransform(account_name, 'processing_details')) ################## account = "abc" here i am trying to get all the records if the additional_details is empty if processing_details in additional_details is empty if processing_details has key account then check the value (which is processing time ) is not in past 30 hours and if processing_details has keys but it is not "abc" we are free to include it i tried so many things but nothing seems to work lastly the format of additional_details which is a json model field is like JSONField(default=dict, null=True, blank=True) "additional_details" : {"processing_details": {"sas": "2024-07-19 11:03:20", "aditi account": "2024-07-20 11:03:20", "irs-account-2": "2024-07-23 11:03:20"}} -
Django OTP Verification Through Email
Registration always goes in successful but then after submitting otp for verification, first error response "error":"authentication failed" and when I try again "error": "error": "OTP or email not found in session.". class UserRegistrationView(APIView): def post(self, request, format=None): serializer = UserRegistrationSerializer(data=request.data) if serializer.is_valid(): user = serializer.save() # Generate and store OTP otp = generate_otp() request.session['otp'] = otp request.session['email'] = user.email request.session['otp_timestamp'] = timezone.now( ).isoformat() # Save as ISO format string # Send OTP to user via email email_subject = 'Your OTP Code' email_message = f'Your OTP code is { otp}. It will expire in 5 minutes.' try: send_mail(email_subject, email_message, settings.EMAIL_HOST_USER, [user.email]) return Response({"message": "Registration successful. Please check your email for the OTP."}, status=status.HTTP_201_CREATED) except Exception as e: return Response({"error": f"Failed to send OTP. Please try again. Error: {str(e)}"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class UserRegistrationSerializer(serializers.ModelSerializer): university = serializers.CharField(write_only=True) gender = serializers.CharField(write_only=True) class Meta: model = User fields = ( "id", "username", "email", "password", "university", "gender", ) extra_kwargs = {"password": {"write_only": True}} def validate_email(self, value): university = self.initial_data.get('university') if university in UNIVERSITY_EMAIL_PATTERNS: pattern = UNIVERSITY_EMAIL_PATTERNS[university] if not re.match(pattern, value): raise serializers.ValidationError(f"""Invalid email address for { university}. Please use a valid student email.""") if User.objects.filter(email=value).exists(): raise serializers.ValidationError( 'A user with this email already exists!') … -
File directory error in python when running python manage.py runserver
I am in the initials stages of starting a django project. Everything is set, I have already installed django, python, virtual env and started myproject project. When I run the command python manage.py runserver I get an error saying no file directory. I have tried any troubleshooting method but the server won't run. -
One common document table vs separate tables for multiple entities: scalability, optimization, and maintainability
I have three tables: inspections, accidents, and claims. Each of these tables has a one-to-many relationship with a documents table, where users can upload documents specific to each record. The process of uploading documents is identical across all three tables. I'm wondering whether to create: A) One common documents table that stores documents for all three entities, with a foreign key referencing the respective table (e.g., inspection_id, accident_id, or claim_id). or B) Separate documents tables for each entity, e.g., inspection_documents, accident_documents, and claim_documents. [enter image description here](https://i.sstatic.net/gw1393oI.png) Which approach is best in terms of: Scalability: Will one approach handle large amounts of data and user traffic more efficiently? Database optimization: Which approach will result in faster query performance and better data retrieval? Maintainability: Which approach will be easier to manage, update, and extend in the long run? Please provide insights and recommendations based on your experience with similar scenarios. here is my models.py class SafetyInspection(models.Model): status = models.CharField(max_length=30, choices=status_choices, default='Closed') #mandatory driver = models.ForeignKey( TeamMember, on_delete=models.CASCADE, related_name='safety_inspections', ) vehicle = models.ForeignKey( Equipment, on_delete=models.CASCADE, related_name='vehicle_safety_inspections', null=True, blank=True ) trailer = models.ForeignKey( Equipment, on_delete=models.CASCADE, related_name='trailer_safety_inspections', null=True, blank=True ) date = models.DateField(null=True, blank=True) start_time = models.TimeField(null=True, blank=True) end_time = models.TimeField(null=True, blank=True) level = … -
Django Profile Page Not Displaying Related Worker Information with Djoser
I'm working on a Django application where users can be either normal app users or workers with additional details. I'm using Djoser for user authentication and registration. I'm having trouble with my profile page, which is supposed to display both user and worker information, but it only shows user information. Here's a brief overview of my code: #models.py from django.db import models from django.contrib.auth.models import AbstractUser, PermissionsMixin from django.utils.translation import gettext_lazy as _ from .managers import CustomUserManager class User(AbstractUser, PermissionsMixin): username = None first_name = models.CharField(_('First name'), max_length=100) last_name = models.CharField(_('last name'), max_length=100) email = models.EmailField(_('Email Address'), max_length=254, unique=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=False) date_joined = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = "email" REQUIRED_FIELDS = ["first_name", "last_name"] objects = CustomUserManager() class Meta: verbose_name = _("User") verbose_name_plural = _("Users") def __str__(self): return self.email @property def get_full_name(self): return f"{self.first_name} {self.last_name}" class Worker(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) categories = models.ManyToManyField('Category', related_name='workers') rating = models.DecimalField(max_digits=12, decimal_places=2, null=True, blank=True) numReviews = models.IntegerField(null=True, blank=True, default=0) pricePerHour = models.DecimalField(max_digits=12, decimal_places=2, null=True, blank=True) gender_choices = [ ('M', 'Male'), ('F', 'Female'), ] gender = models.CharField(max_length=1, choices=gender_choices) profile_photo = models.ImageField(upload_to='profile_photos/', null=True, blank=True) num_tel = models.CharField(max_length=20) small_description = models.TextField(null=True, blank=True) description = models.TextField(null=True, blank=True) _id = models.AutoField(primary_key=True, editable=False) def __str__(self): return f"{self.user.email} - … -
Using Django REST Framework to make sure cross-platform
I want to create cross platform site in Django, which can work with other clients, like my own c++ apps. Imagine someone creating social media in which you can post videos and articles. What I want is to be able to get all the articles and videos in my c++ app, also be able to do the same in my web browser. Here's some questions: Can I use REST Framework only on authentication and app requests, and for the browser requests simply render HTML file using Django's built-in render() func? Logic for that is when you are in browser you are going on URLs like my-site.com/, my-site.com/about-us, etc., but when you are in c++ app you are going like my-site.com/api/v1, my-site.com/api/v1/about-us. Will it work like that? If it will work like that, how to make you authorize both in browser and in app using REST Framework, but for other parts of the site except for authorization use separate functionality (as I said earlier)? Any help appreciated. -
JSON format from Django serializer
I am using Django serializer for JSON. Using the documentation here. https://docs.djangoproject.com/en/5.0/topics/serialization/ Why does the serializer produce messy output? The documentation offers no solution. How can I get a clean, well formatted JSON without pk and model? View from django.http import HttpResponse, JsonResponse from django.core import serializers @csrf_protect def cityLookup(request, **kwargs): country = kwargs.get('Country') city = kwargs.get('Place') queryset = GeoNames_location.objects.filter(geoCountry_code=country, feature_class='P', geoAsciiName__istartswith=city).order_by('-geo_population')[:5] data = serializers.serialize("json", queryset, fields=["geoAsciiName", "geoLongitude", "geoLatitude", "geo_timezone", "geo_population", "geoCountry_code"]) return JsonResponse(data, safe=False) # Need security check Response "[{\"model\": \"ui.geonames_location\", \"pk\": 5128581, \"fields\": {\"geoAsciiName\": \"New York City\", \"geoLatitude\": \"40.714270\", \"geoLongitude\": \"-74.005970\", \"geoCountry_code\": \"US\", \"geo_population\": 8804190, \"geo_timezone\": \"America/New_York\"}}, {\"model\": \"ui.geonames_location\", \"pk\": 4645421, \"fields\": {\"geoAsciiName\": \"New South Memphis\", \"geoLatitude\": \"35.086760\", \"geoLongitude\": \"-90.056760\", \"geoCountry_code\": \"US\", \"geo_population\": 641608, \"geo_timezone\": \"America/Chicago\"}}, {\"model\": \"ui.geonames_location\", \"pk\": 4335045, \"fields\": {\"geoAsciiName\": \"New Orleans\", \"geoLatitude\": \"29.954650\", \"geoLongitude\": \"-90.075070\", \"geoCountry_code\": \"US\", \"geo_population\": 389617, \"geo_timezone\": \"America/Chicago\"}}, {\"model\": \"ui.geonames_location\", \"pk\": 5101798, \"fields\": {\"geoAsciiName\": \"Newark\", \"geoLatitude\": \"40.735660\", \"geoLongitude\": \"-74.172370\", \"geoCountry_code\": \"US\", \"geo_population\": 281944, \"geo_timezone\": \"America/New_York\"}}, {\"model\": \"ui.geonames_location\", \"pk\": 4776024, \"fields\": {\"geoAsciiName\": \"Newport News\", \"geoLatitude\": \"36.980380\", \"geoLongitude\": \"-76.429750\", \"geoCountry_code\": \"US\", \"geo_population\": 182385, \"geo_timezone\": \"America/New_York\"}}]" -
Issues with Serving Django App via Subpath in Apache
I have a Django application (Django version 4.2.11) that I want to serve under a subpath using Apache. Specifically, I want to serve the app at https://example.com/subpath so that other Django app URLs can be accessed as subpaths. For example: https://example.com/subpath/admin should load the Django admin page. https://example.com/subpath/api should load the API endpoints. However, I am encountering a 404 error when I try to access these URLs. Here is my current Apache configuration to redirect Django app to a subpath: <VirtualHost *:443> ServerName example.com DocumentRoot /var/www/html SSLEngine on RewriteEngine on # Redirect /subpath to INTERNAL_IP:8000 RewriteCond %{REQUEST_URI} ^/subpath RewriteCond %{HTTP:Upgrade} =websocket RewriteRule /(.*) ws://INTERNAL_IP:8000/$1 [P,L] RewriteCond %{REQUEST_URI} ^/subpath RewriteCond %{HTTP:Upgrade} !=websocket RewriteRule /(.*) http://INTERNAL_IP:8000/$1 [P,L] ProxyPass /subpath http://INTERNAL_IP:8000/ ProxyPassReverse /subpath http://INTERNAL_IP:8000/ ProxyRequests Off </VirtualHost> My Django urls.py file: from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from apscheduler.schedulers.background import BackgroundScheduler from my_app.management.commands import run_schedules urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('my_app.urls')), path('api/', include('auth_app.urls')), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) admin.site.site_header = 'My API Administration' admin.site.index_title = 'My API Admin Area' admin.site.site_title = 'My API Administration' scheduler = BackgroundScheduler() scheduler.add_job(run_schedules.Command().handle, 'interval', minutes=0.50) scheduler.start() Issue Despite these configurations, I'm still … -
Filterset_class does not working when view is called from test
I have a drf method view: @action(detail=False, methods=["get"], filterset_class=None) def count(self, request, *args, **kwargs): ... and of course, there is a filterset_class defined on class level. When I called this endpoint from postman, this filterset_class override is working, but when I called it from tests, the override is not working. Im using APIRequestFactory to do the request from test like factory = APIRequestFactory(email=user.email) view = NotificationsMessagesView.as_view({"get": "count"}) response = view(request) result = response.render() assert result.data["count"] == 1 My versions: Django = "3.2" djangorestframework = "3.12.4" django-filter = "22.1" Could someone help me? I trying to find maybe so bugreports, but i dont find anything. I think, the override of filterset_class should be applied when the view is requested from tests. -
How to send MDM commands to push an app to iOS device in python
"""<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>Command</key> <dict> <key>Identifier</key> <string>com.zhiliaoapp.musically</string> <key>RequestType</key> <string>RemoveApplication</string> </dict> </dict> </plist>""" In this plist, I provide the command to remove a third-party application installation. I used to perform this task using Python 2.7, but I now want to update the code to Python 3. How can I send a command to an iOS device using Python and Django? This is a plist form of commands. -
Django with gunicorn: sending requests - concurrency
We've got a Django application configured with gunicorn. That means several workers are processed in parallel. Now for some functionality we need to call a service for reverse geocoding looking something like this: reverseGeocodingURL = s.geocodingURL + '?lat=' + str(latitude) + '&lon=' + str(longitude) + '&api_key=' + s.apiKey Now it appears that sometimes the responses seem to be not aligned to the requests. It's probably a concurrency issue when one gunicorn worker receives the reponse of a request issued by another worker. Is this possible? And what possibilities do we have to circumvent this problem? -
Display data into modal form through django
I am very much new to django. I am trying to display the details of a student record in a modal form once details button clicked. But it is showing an empty modal form. Below is the code snippet. Please let me know if I am doing something wrong here. Thanks in advance. Here are the views def student(request): students = Student.objects.values("standard__standard_name", "studentid","firstname","lastname","status","nationality","Gender") return render(request, 'student.html', { 'students':students }) def student_detail(request, studentid): try: student_object = Student.objects.filter(studentid=studentid) student = student_object.values("studentid","firstname","lastname","standard__standard_name","status","nationality","dob","Gender","religion","parent__parentid") print(student) except student.DoesNotExist: raise Http404('student not found') return render(request, 'student_detail.html', {'student':student}) student.html snippet <div class="tab-pane fade show active" id="show-students-pane" role="tabpanel" aria-labelledby="show-students" tabindex="0"> <table class="table table-striped table-bordered table-hover"> <th>Name</th> <th>Standard</th> <th>Gender</th> <th>Status</th> <th>Nationality</th> {% for student in students %} <div class="studentname"> <tr> <td>{{ student.firstname |capfirst }} {{ student.lastname |capfirst }}</td></a> <td>{{ student.standard__standard_name }}</td> <td>{{ student.Gender }} </td> <td>{{ student.status }} </td> <td>{{ student.nationality }} </td> <td><button type="button" class="modalbtn btn btn-primary" data-bs-toggle="modal" data-bs-target="#studentModal" onclick="localtion.href='/student/<studentid>/detail/ student.studentid'">Details</button></td> </tr> </div> {% endfor %} </table> <div class="modal" id="studentModal"> <div class="modal-dialog"> <div class="modal-content"> <!-- Modal Header --> <div class="modal-header"> <h4 class="modal-title" id="studentModal">{{ student.firstname }}</h4> <button type="button" class="btn-close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <!-- Modal body --> <div class="modal-body"> {% include 'student_detail.html' %} </div> <!-- Modal footer --> … -
$ python -m django startproject mysite . Command 'python' not found, did you mean , it is not working [closed]
django-admin.py startproject mysite . refresh command not found $ python -m django startproject mysite . Command 'python' not found, did you mean : command 'python3' from deb python3 command 'python' from deb python-is-python3 -
Add custom field to wagtailadmin ModelAdmin
I'm trying to add a custom field to wagtail ModelAdmin, but not sure how to do that. I tried from wagtail_modeladmin.options import ModelAdmin, modeladmin_register from wagtail_modeladmin.views import EditView from django import forms from django.contrib.admin.utils import quote from wagtail.log_actions import registry as log_registry from dzen_wagtail.football_maps.models import FootballMap class FootballMapAdminForm(forms.ModelForm): extra_link = forms.URLField( label="Extra link", widget=forms.URLInput(attrs={"type": "button"}), ) field_order = ["tg", "name", "location", "history", "covering", "extra_link", "status"] class Meta: model = FootballMap fields = ["tg", "name", "location", "history", "covering", "extra_link", "status"] def __init__(self, *args, **kwargs): super(FootballMapAdminForm, self).__init__(*args, **kwargs) self.fields["extra_link"].initial = "https://example.com" class FootballMapEditView(EditView): def get_form(self): return FootballMapAdminForm(instance=self.instance) @modeladmin_register class FootballMapAdminSite(ModelAdmin): model = FootballMap menu_label = "Карта коробок" menu_icon = "circle-check" edit_view_class = FootballMapEditView def get_list_display(self, request): list_display = ["location", "status"] return list_display But looks like I go in wrong direction, and such can be achieved in ModelAdmin itself -
Django Postgresql ORM optimisation
I have a PostgreSQL view called view_sales_dashboard - this consists of several millions rows of daily sales data. In the Django view I want to present a table grouped by the products, with the columns as the total base_daily_pnl of different time periods - Daily, Month to date (MTD), Quarter to date (QTD), Year to date (YTD) and Inception to date (ITD) In order to try and limit the number of SQL queries I am creating 5 querysets to then generate the table. To improve the efficiency of this I investigated the logs and expected to see 5 SQL queries. However the logging shows 20 queries (5 product types * the 4 aggregate groupings + the daily series request). See below the Django code, ORM model and the logs. Can anyone advise 1.) why so many SQL queries are being triggered 2.) how to optimise? queryset_sales_all = SalesDashboard.objects.all() queryset_daily_products = queryset_pnl_all.filter(position_date__range=[latest_pnl_date_str, latest_pnl_date_str]).values('product').annotate(base_daily_pnl=Sum('base_daily_pnl'),base_lmv=Sum('base_lmv')) for daily in queryset_daily_product: matching_mtd = queryset_pnl_all.filter(position_date__range=[start_mth_str,latest_pnl_date_str]).values('product').annotate(mtd_pnl=Sum('base_daily_pnl')).get(product=daily['product']) matching_qtd = queryset_pnl_all.filter(position_date__range=[start_qtd_str, latest_pnl_date_str]).values('product').annotate(qtd_pnl=Sum('base_daily_pnl')).get(product=daily['product']) matching_ytd = queryset_pnl_all.filter(position_date__range=[start_year_str, latest_pnl_date_str]).values('product').annotate(ytd_pnl=Sum('base_daily_pnl')).get(product=daily['product']) matching_itd = queryset_pnl_all.filter(position_date__range=[start_itd_str, latest_pnl_date_str]).values('product').annotate(itd_pnl=Sum('base_daily_pnl')).get(product=daily['product']) daily['mtd_pnl'] = matching_mtd['mtd_pnl'] daily['qtd_pnl'] = matching_qtd['qtd_pnl'] daily['ytd_pnl'] = matching_ytd['ytd_pnl'] daily['itd_pnl'] = matching_itd['itd_pnl'] pnl_product = SummaryPnlProductTable(queryset_daily_product) Below is the ORM model: class SalesDashboard(models.Model): unqiue_id = models.IntegerField(primary_key=True) sales_id = models.CharField(max_length=50) base_daily_pnl …