Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django template counter with "with" statement
{% with counter=1 %} {% for order in sales %} <tr> {% ifchanged order.date and order.dealer %} <td scope="row">{{ counter }}</td> {% with counter=counter|add:1 %} {% endwith %} {% else %} <td></td> {% endifchanged %} </tr> {% endfor %} {% endwith %} why is the counter '1' all the time? How can the counter be increased by 1 each time it is inside ifchanged statement? -
dumping django historical data in different database using django routers
I am using the django-simple-history package to track changes in my model. Now, I want to dump only the historical data into another database. I attempted to achieve this using a router, but I encountered an error: django.db.utils.OperationalError: (1824, "Failed to open the referenced table 'common_user'") The issue appears to be because the common_user table is in the default database and not in the history database. Here's the codes: # routers.py class HistoryRouter: def db_for_read(self, model, **hints): model_name = model.__name__ if 'historical' in model_name.lower(): return 'history_db' return 'default' def db_for_write(self, model, **hints): print('3'*100) model_name = model.__name__ if 'historical' in model_name.lower(): return 'history_db' return 'default' def allow_migrate(self, db, app_label, model_name=None, **hints): if hints.get("db") is not None: return db == hints.get("db") if model_name != None: if 'historical' in model_name.lower(): return db == 'history_db' return db == 'default' #models.py class Profile(models.Model): profile_type = models.ForeignKey(ProfileType, on_delete=models.PROTECT) user = models.ForeignKey(User, on_delete=models.CASCADE) nickname = models.CharField( max_length=64, unique=True, blank=False, null=False) org = models.ForeignKey( Org, null=True, on_delete=models.CASCADE, blank=True, related_name="user_org" ) address = models.ManyToManyField(Address, blank=True) is_active = models.BooleanField(default=True) is_section_admin = models.BooleanField(default=False) is_organization_admin = models.BooleanField(default=False) is_organization_member = models.BooleanField(default=False) date_of_joining = models.DateField(auto_now_add=True, null=True, blank=True) referral = models.CharField( max_length=64, blank=True, null=True) referred = models.CharField( max_length=64, blank=False, null=False, unique=True, default=uuid.uuid4().hex) history = HistoricalRecords(m2m_fields=(address, … -
Retrieving Video Duration During Save Operation in Django Model using OpenCV
I’m attempting to extract the duration of a video file within the Django model’s save method. I plan to use the OpenCV library for this purpose. My current challenge is properly accessing the video file in the isOpened() method of OpenCV to ensure that I can extract the duration. The problematic part seems to occur when I attempt to access the file during the execution of the super().save(*args, **kwargs) method, which I believe I need to call twice, once before and after obtaining the video duration, to ensure the file path is accessible to OpenCV. def save(self, *args, **kwargs) -> None: if not self.pk: super().save(*args, **kwargs) path = self.content.path self.duration = get_video_duration(path) return super().save(*args, **kwargs) Is this the correct approach? -
Django ORM One-To-Many relationships problem
Models: class Mark(models.Model): name = models.CharField(max_length=200, verbose_name="Марка", unique=True, null=True) #... class Model(models.Model): mark = models.ForeignKey(Mark, on_delete=models.CASCADE, verbose_name="Марка") name = models.CharField(max_length=200, verbose_name="Модель", unique=True, null=True) #... class Car(models.Model): vin = models.CharField(max_length=100, null=True) #... class Image(models.Model): car = models.ForeignKey(Car, related_name='images', on_delete=models.CASCADE) image = models.ImageField(upload_to=get_upload_path, verbose_name="Фото") #... How to make the following query in Django ORM without raw: query = "SELECT c.*, m.name mark_name, JSON_ARRAYAGG(img.image) image FROM incarcatalog_car c \ LEFT JOIN incarcatalog_mark m ON m.id=c.mark_id \ LEFT JOIN incarcatalog_image img ON img.car_id=c.id \ WHERE c.id>%s \ GROUP BY c.id;" queryset = Car.objects.raw(query, [id]) My problem... I did a left join for the Mark, Model tables, but I don’t know how to connect the car table with the Image table queryset = Car.objects.select_related("mark", "model").all() But i don't know how to create realtionship with Image table. -
'ascii' codec can't encode characters while uploading file in django and cpanel
hello I have a Django project. it work perfectly in local host but when I deployed it on cPanel I got an error when I want to upload an image. 'ascii' codec can't encode characters in position 37-43: ordinal not in range(128) /home/monkeymo/virtualenv/django/3.10/lib/python3.10/site-packages/django/core/files/storage/filesystem.py, line 106, in _save can you help me about this? -
Python Django Server - Production
When running my Django Server in Production mode, there is a problem with the render of one HTML. I have a HTML template, i copy and modify the content of it (according to some enter values) NAME_TEMPLATE.html then render this in to a different NAME_MODIFY.HTML. When i restart the server the 1st and 2nd render work then after it's always render the 1st and 2nd render in a random order. But if i check my NAME_MODIFY.HTML content, i can see the value display is not what it's in it. An image of the HTML content and what it display in chrome. CONTENT OF HTML and RENDER I try different explorer, CTRL+F5 but seems not worked. But if set the Django Server in DEBUG mode, then the issue disappear, when i enter always different value, i can see my value changed. Hope it's enough clear. Thanks in advance. CTRL+F5, Different Explorer, DEBUG MODE -
How to view FPDF pdf via http response in Django?
Hello I'm trying to view pdf on browser new tab via FPDF. getting error here my code. class PDFWithHeaderFooter(FPDF): def header(self): # Add your header content here self.set_font('Arial', 'B', 12) self.cell(0, 10, 'Your Header Text', 0, 1, 'C') def footer(self): # Add your footer content here self.set_y(-15) self.set_font('Arial', 'I', 8) self.cell(0, 10, 'Page %s' % self.page_no(), 0, 0, 'C') @login_required(login_url='/') def Print_Quote(request, pk): id = Quote.objects.get(id = pk) term = id.terms.all() quote_item = Quote_item.objects.filter( quotes = id ) sub_total = quote_item.aggregate(Sum('sub_total')) gst_total = quote_item.aggregate(Sum('gst_total')) total = quote_item.aggregate(Sum('total')) pdf = FPDF(format='letter') pdf = PDFWithHeaderFooter() # Add content to the PDF pdf.add_page() pdf.set_font('Arial', 'B', 16) pdf.cell(40, 10, 'Hello, World!') # Save the PDF to a HttpResponse pdf.output() return HttpResponse(pdf, content_type='application/pdf') **I'm view pdf on new tab but it's show me error ** -
In Django i can't display a form in index from another page. I only see the button and I don't see the textboxes
I would like to view the registration form directly on the index.html page (home page). The registration form was created in registration/register.html. I call it in index.html using: {% block content %} {% include 'registration/register.html' %} {%endblock%} In the urlpatterns of App1/views.py, i use: path("register_request", views.register_request, name='register_request') The problem is that on the index.html i see the form button, but not its textboxes (username, email, password). I can't understand where I'm wrong. Can you tell me what i'm doing wrong and can you show me code how to fix it? This is App1: App1 .migrations .static .templates ..index.html ..registration ...register.html index.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>University</title> <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet"> <link href="https://getbootstrap.com/docs/5.3/assets/css/docs.css" rel="stylesheet"> <link href="/static/css/style.css" rel="stylesheet"> </head> <body> ....... ....... {% block content %} {% include 'registration/register.html' %} {%endblock%} </body> </html> App1/templates/registration/register.html <!--Register--> <div class="container py-5"> <h1>Register</h1> <form method="POST"> {% csrf_token %} {{ register_form.as_p }} <button class="btn btn-primary" type="submit">Register</button> </form> <p class="text-center">If you already have an account, <a href="/login">login</a> instead.</p> </div> App1/forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User # Create your forms here. class NewUserForm(UserCreationForm): email = … -
In django, is there a problem in checking csrf token only from request.META?
I'm experimenting with a custom FileUploadHandler that directly uploads a file to the cloud as the chunks are coming from the client. The problem is that Django's CsrfViewMiddleware accesses request.POST, which triggers the file upload handler before the view and starts the upload without any checks. Because of this, I've made a subclass of CsrfViewMiddleware with a slight change: to first check for csrf token in request.META, then request.POST. This way I can access the request in the view function before the file upload handler is called, but after csrf token protection, by putting the csrf token in the header. My perception is that both FileUploadHandler and CsrfViewMiddleware are more internal in Dango's implementation. Everything seems to work, but I'm afraid to break something unexpected with the custom CsrfViewMiddleware. Any input? from django.conf import settings from django.middleware.csrf import ( CsrfViewMiddleware, REASON_NO_CSRF_COOKIE, REASON_CSRF_TOKEN_MISSING, InvalidTokenFormat, RejectRequest, UnreadablePostError, _check_token_format, _does_token_match, ) class HeaderCsrfViewMiddleware(CsrfViewMiddleware): """only difference from CsrfViewMiddleware is csrf token checked first in request.META, then request.POST (defaut is other way around) if csrf token is in request.META, request.POST never is accessed makes possible to csrf protect a view before file upload handlers gets called """ def _check_token(self, request): # get secret from the … -
Why does the form not appear on my Django Webpage?
I am trying to display a search form on a Django webpage, I've included the search view function, the search form and DHTML. The form simply will not appear on the page, instead I only see the base.html template. I have disabled all CSS that could interfere and verified that base.html does not effect it. Additionally I've verified that the form is correctly passing to the view function and html. Help would really be appreciated as I feel my head is about to explode. HTML {% extends 'base.html' %} {%block title%} {% if form.is_valid and search_text%} Search Results for "{{ search_text }}" {% else %} UrMix Search {% endif %} {% endblock %} {% block content %} <h2> Search for Songs </h2> <form method="GET" action="{% url 'song_search' %}"> {% csrf_token %} {{ form.as_p }} <button type="submit" class="btn btn-primary">Search</button> </form> {% if form.is_valid and search_text %} <h3> Search results for <em> {{search_text}}</em></h3> <ul class = "list-group"> {% for song in songs%} <li class="list-group-item"> <span class="text-info">Name: </span> <a href="{%url 'song_detail' song.pk%}"> {{song}}</a> <br/> </li> {% empty %} <li class = "list-group-item">No result</li> {% endfor %} </ul> {% endif %} {% endblock %} Search View def song_search(request): search_text = request.GET.get("search", "") form = … -
Multiple filtering on Django Prefetch
Based on my codebase: class City(models.Model): name = models.CharField(max_length=100) ... class District(models.Model): city = models.ForeignKey(City, on_delete=models.CASCADE) class Park(models.Model): district = models.ForeignKey(District, on_delete=models.CASCADE, related_name="parks") class Plant(models.Model): name = models.CharField(max_length=200) plant_type = models.CharField(max_length=200) park = models.ForeignKey(Park, on_delete=models.CASCADE, related_name="plants") def plants_of_type_in_park(plant_type, park): return park.plants.filter(plant_type=plant_type) def generate_garden_report(): report_data = {} plant_types = ["rose", "tulip", "daisy", ...etc] districts = District.objects.all() districts = districts.prefetch_related("parks", "parks__plants") for dist in districts.all(): for park in districts.parks.all(): for plant in plant_types: report_data[dist.city.name][plant] += plants_of_type_in_park(plant, park).count() return report_data My objective is to optimize the generate_garden_report function using prefetching. I have added districts.prefetch_related("parks", "parks__plants"). However, since plants_of_type_in_park uses a filter, it triggers another query. My approach was to prefetch each filter: districts = districts.prefetch_related("parks", "parks__plants") for plant in plant_types: districts = districts.prefetch_related(Prefetch("parks_plants", queryset=Plant.objects.filter(plant_type=plant))) But, as parks_plants can only be assigned once, I can't create multiple filters for this. My goal is to prefetch everything needed with minimal impact on the plants_of_type_in_park function, as it is used elsewhere in the codebase. -
Why is docker compose saying no such file or directory?
I have a simple vue + django project and I want to be able to containerize this project with docker but I've run into some issues. I have dockerfiles and docker compose files in each subfolder - frontend and backend - and if I cd into either I can successfully start each individual project using docker compose with no problems. However, I want to be able to run one single docker compose command that can create both images simultaneously. I currently have a docker compose file in the root directory of the project and I am including the compose files and referencing them in the services. It works fine with just the vue service but gives me an error when I include the django services. Error code is this: failed to solve: failed to read dockerfile: open /var/lib/docker/tmp/buildkit-mount2369903057/Dockerfile: no such file or directory The django project was created using cookiecutter so it has everything I need in the project. Here is a simple version of my file structure: - backend - compose - Dockerfile - docker-compose.yml - frontend - Dockerfile - docker-compose.yml - docker-compose.yml Here is my backend compose file: volumes: api_local_postgres_data: {} api_local_postgres_data_backups: {} services: django: build: context: . … -
Procfile for deploying django in Heroku "web: gunicorn [app name]:application -b xx.xxx.xxx.xx:8000"
I'm trying to deploy my app and the Profile seemed to be wrong and my app crashes before I can view it. I tried to write this in the Procfile: web: gunicorn SC_BASIS:application -b 127.0.0.1:8000 and I was expecting it to run since I previously had problems with web: gunicorn SCBASIS.wsgi However, it still errors with the following message. I'm not sure what is wrong: Starting process with command `gunicorn SC_BASIS:application -b 127.0.0.1:8000` 2023-12-22T22:28:22.256483+00:00 app[web.1]: [2023-12-22 22:28:22 +0000] [2] [INFO] Starting gunicorn 21.2.0 2023-12-22T22:28:22.256752+00:00 app[web.1]: [2023-12-22 22:28:22 +0000] [2] [INFO] Listening at: http://127.0.0.1:8000 (2) 2023-12-22T22:28:22.256788+00:00 app[web.1]: [2023-12-22 22:28:22 +0000] [2] [INFO] Using worker: sync 2023-12-22T22:28:22.258739+00:00 app[web.1]: [2023-12-22 22:28:22 +0000] [7] [INFO] Booting worker with pid: 7 2023-12-22T22:28:22.259865+00:00 app[web.1]: Failed to find attribute 'application' in 'SC_BASIS'. 2023-12-22T22:28:22.259934+00:00 app[web.1]: [2023-12-22 22:28:22 +0000] [7] [INFO] Worker exiting (pid: 7) 2023-12-22T22:28:22.280621+00:00 app[web.1]: [2023-12-22 22:28:22 +0000] [8] [INFO] Booting worker with pid: 8 2023-12-22T22:28:22.280808+00:00 app[web.1]: [2023-12-22 22:28:22 +0000] [2] [ERROR] Worker (pid:7) exited with code 4 2023-12-22T22:28:22.281142+00:00 app[web.1]: Failed to find attribute 'application' in 'SC_BASIS'. 2023-12-22T22:28:22.281204+00:00 app[web.1]: [2023-12-22 22:28:22 +0000] [8] [INFO] Worker exiting (pid: 8) 2023-12-22T22:28:22.300841+00:00 app[web.1]: [2023-12-22 22:28:22 +0000] [2] [ERROR] Worker (pid:8) exited with code 4 2023-12-22T22:28:22.300880+00:00 app[web.1]: Traceback (most recent call … -
Error: django.db.utils.OperationalError: unrecognized token: ":"
When I try to save some Django model like for example this one: class UserProfile(models.Model): address = models.CharField(max_length=100, blank=True) payment_type = models.CharField(max_length=20, default="Undefined") total_no_of_products = models.IntegerField(default=0) total_paid = models.FloatField(default=0) ids = ArrayField(models.IntegerField(null=True, blank=True), default=list) user = models.OneToOneField(NewUser, on_delete=models.CASCADE, default=None) metadata = models.ManyToManyField(Metadata) def __str__(self): return f"{self.user.user_name}" I get in return following error: Error: django.db.utils.OperationalError: unrecognized token: ":" I try to figure out what cause this problem and I found that when I comment out this line ids = ArrayField(models.IntegerField(null=True, blank=True), default=list) problem disappear. Does anybody have idea why is this? Currently I'm using Django 5.0 with default sqlite3 db. Tnx! -
Extension for VS Code in Django projects where it is possible to view the page in real time
I need an extension for VS Code that simulates the browser on the VS Code screen itself. The problem is that I need to work on the page in real time, the way I work today, I need to change the html and css in my project, go to my browser, clear my browser's cache and only then load the page and check if you agree. I would like something similar to what the 'HTML play' extension does (this doesn't work because it doesn't load the static CSS and JS files as they are added to DJango). Any indications? I've already tried using: HTML Play Live Server -
sync_to_async decorator, async view in Django
I am trying to follow the video tutorial and try to understand async view and @sync_to_async decorator in django. I have this code: import time import asyncio from asgiref.sync import sync_to_async from django.http import HttpResponse from movies.models import Movie from stories.models import Story @sync_to_async def get_movies_async(): print('prepare to get the movies...') time.sleep(2) qs = Movie.objects.all() print('got all the movies') @sync_to_async def get_stories_async(): print('prepare to get the stories...') time.sleep(5) qs = Story.objects.all() print('got all the stories') async def main_view_async(request): start_time = time.time() await asyncio.gather(get_movies_async(), get_stories_async()) total = (time.time() - start_time) print("total: ", total) return HttpResponse('async!') But when I call main_view_async from my browser it still takes 7 seconds, not 5 seconds like in the video tutorial. The tutorial might be outdated (year 2020). Or perhaps I am doing something wrong? Can you please help? My output prepare to get the movies... got all the movies prepare to get the stories... got all the stories total: 7.0126471519470215 The tutorial terminal output prepare to get the movies... prepare to get the stories... got all the movies got all the stories total: 5.0126471519470215 -
Unable to use '?' to pass parameters when using pyodbc in Django for large query
Working on: Django framework pyodbc package (MSSQL Version 18) DS: Azure synapse I would like to know what is the best way to go about when trying to load a large number of parameters into the SQL query for Azure synapse. The scale I'm looking for is in millions. I can split the parameters into chunks of 2k which is the limit specified here: https://learn.microsoft.com/en-us/azure/synapse-analytics/sql-data-warehouse/sql-data-warehouse-service-capacity-limits#queries However, that would mean the number of queries would be too many. ~500 per million parameters. This isn't just for 1 type of parameter for e.g in where clause I may have 2 columns, each column with its own set of a million values which I would like to pass through the query params. What's the best way to about this? As a sidenote: I hadn't been able to get the queries working with '?' parameter holder, I had to use '%s' to fix this. Thanking in advance! -
drop down list is not getting populated in django, when data if fetched from databse
i want data from my database to display on the dropdown list , when user click on it, but its not happening my code is all correct , i am not able to find any mistakes please help me. this is my booking.html file <!-- booking.html --> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Book a Court</title> <style> body { font-family: 'Arial', sans-serif; margin: 0; padding: 0; background-color: #f4f4f4; } header { text-align: center; background-color: #333; color: white; padding: 20px; } .container { max-width: 600px; margin: 50px auto; background-color: rgba(255, 255, 255, 0.8); padding: 20px; border-radius: 10px; box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); } form { display: grid; gap: 15px; } label { font-weight: bold; } input, select { padding: 10px; border: 1px solid #ccc; border-radius: 5px; width: 100%; box-sizing: border-box; } button { background-color: #333; color: white; padding: 10px; border: none; border-radius: 5px; cursor: pointer; } </style> </head> <body> <header> <h1>Book Your Slot</h1> </header> <div class="container"> <form action="{% url 'book' %}" method="POST"> {% csrf_token %} <label for="id_name">Name:</label> <input type="text" id="id_name" name="name" required> <label for="id_mobile_number">Mobile Number:</label> <input type="text" id="id_mobile_number" name="mobile_number" required> <label for="id_court">Court:</label> <select id="id_court" name="court" required> {% for court in courts %} <option … -
Django QuestionForm in forms.py not Creating Instance in questions.html
I have a QuestionForm in forms.py meant to create instances of a Question model to appear in questions.html. However, when I submit the form, I am redirected back to ask_question.html without any new instance being created. Debugging Steps: 1. Admin Panel Creation I am able to create an instance of the Question model through the Django admin panel, which is currently the only instance displaying. 2. Frontend Submission I have tried creating an instance of the Question model using the front end, and no error message appears. However, no instance of the Question model appears in the questions.html template. 3. I inspected QuestionForm in forms.py it appears to be working as intended. class QuestionForm(forms.ModelForm): subject = forms.CharField(max_length=100, required=True, help_text='Enter a subject line for your question.') body = forms.CharField(widget=forms.Textarea, max_length=10000, required=True, help_text='Enter the main body of your question.') teacher_standard = forms.MultipleChoiceField( required=False, widget=forms.CheckboxSelectMultiple, choices=[(1, 'High Expectations'), (2, 'Promoting Progress'), (3, 'Subject Knowledge'), (4, 'Planning'), (5, 'Differentiation'), (6, 'Assessment'), (7, 'Behaviour Management'), (8, 'Professionalism')], help_text='Select the standard(s) for which you are asking the question.' ) class Meta: model = Question fields = ['subject', 'body', 'teacher_standard'] 4. inspecting the Question model in models.py it appears to be working as intended. class Question(models.Model): title … -
Celery (with Redis) shows task as registered but nothing gets executed when called from python-django on EC2
I am totally lost on this one and hoping someone can help. I am using Celery-Redis to execute a long running task for my Django project. The setup works perfectly on my local Windows setup. I have been working on porting this to AWS EC2 for last few days with Nginx/Gunicorn running on Ubuntu. And at this point, everything seems to be working except the background task execution. I have installed Redis and Celery on the same EC2 instance where I have the webserver running. Both (Redis/Celery) start without issues and they acknowledge each other (connection is established). Celery even shows the registered tasks. However, whatever I do, the task does not get executed when the request is made from Django. I have put logging everywhere in the code and can see the task (executed with .delay()) being called but after that everything stops. The call never returns. No error messages either in Nginx or Gunicorn logs. Celery and Redis-server both are running on the terminal with logging on so that I can see any messages. No messages in any of them as if they are not called at all. I have also tried to execute the task without .delay … -
store.models.variation_price.product.RelatedObjectDoesNotExist: variation_price has no product
I am working on a Django project which has models shown below. I'm trying to filter filter_horizontal field in admin.py. class VariationManager(models.Manager): def color(self): return super(VariationManager,self).filter(variation_category='color', is_active=True) def sizes(self): return super(VariationManager, self).filter(variation_category='size', is_active=True) variation_category_choice = ( ('color', 'color'), ('size', 'size'), ) class Variation(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) variation_category = models.CharField(max_length=100, choices=variation_category_choice) variation_value = models.CharField(max_length=100) objects = VariationManager() class variation_price(models.Model): price = models.IntegerField() product = models.ForeignKey(Product, on_delete=models.CASCADE) variations = models.ManyToManyField(Variation, blank=True) is_active = models.BooleanField(default=True) In admin.py of project, I have: class variation_priceForm(forms.ModelForm): class Meta: model = variation_price fields = ['price','product','variations','is_active'] def __init__(self, *args, **kwargs): super(variation_priceForm, self).__init__(*args, **kwargs) self.fields['variations'].queryset = Variation.objects.filter(product=self.instance.product) @admin.register(variation_price) class variation_priceAdmin(admin.ModelAdmin): form = variation_priceForm filter_horizontal = ('variations',) list_display = ('get_variations', 'price', 'stock','id','is_active') list_editable = ('is_active',) I'm getting an error saying: store.models.variation_price.product.RelatedObjectDoesNotExist: variation_price has no product Thanks. Any help is appreciated -
Beginner trying to run Django project using Dockerfile
I am new to Docker. I am trying to run a basic project that I have made in Django. My Dockerfile is: FROM python:3 COPY members /associate/ WORKDIR /associate RUN pip install Django WORKDIR /associate/forening EXPOSE 8000 CMD ["python", "manage.py", "runserver", "8000"] My django project is in a folder called members. What I am trying to do above is to install django to the virtual environment of the django project which has been copied to the folder associate. But I can’t find the server http://127.0.0.1:8000/ which exists on my computer locally when i run the django project. Also, where are my docker images and containers stored? When I run docker info it says that docker root directory is var/lib/docker but no such directory exists. Right now I am running docker images from the graphical user interface in docker desktop -
Multiple static files within separate Django templates (using block.super with multiple included files)
I don't necessarily have a problem, but I'm unsure if this is good practice. I'm working on a Django project. I've set up a base.html, navbar.html and sidenav.html and made separate .css and .js files for each. I have then included those static files separately in each .html file within separate blocks. Here's partial code, to explain what I've done: base.html {% load static %} ... <head> ... <!-- CSS import --> {% block css_import %} <link rel="stylesheet" href="{% static 'path/to/base.css' %}" /> {{ block.super }} {% endblock %} ... </head> <body> {% block navbar %} {% include 'navbar.html' %} {% endblock %} ... {% block sidenav %} {% include 'sidenav.html' %} {% endblock %} ... <!-- JS import --> {% block js_import %} {{ block.super }} {% endblock %} </body> ... navbar.html {% load static %} {% block css_import %} <link rel="stylesheet" href="{% static 'path/to/navbar.css' %}" /> {% endblock %} <!-- Navbar content --> {% block js_import %} <script src="{% static 'path/to/navbar.js' %}"></script> {% endblock %} sidenav.html looks structurally basically the same, also having css_import and a js_import blocks. Now, I can say that everything seems to work just fine as apparently block.super takes blocks from both included .html … -
Slow performance when order by field in foreign key
When a queryset is sorted by a field in a related model performance decreases drastically. I use mysql. For example, I have two models: class Event(models.Model): idEvent = models.BigAutoField(primary_key=True) created_at = models.DateTimeField(db_index=True, verbose_name=_('date')) processed_at = models.DateTimeField(auto_now_add=True, verbose_name=_('processed')) data = models.TextField() class Meta: ordering = ["-created_at"] # [1154519 rows] class AccessHistory(models.Model): event = models.ForeignKey(Event, on_delete=models.CASCADE, blank=True, null=True) result = models.TextField(verbose_name=_('result')) # [1130603 rows] If I do AccessHistory.objects.all().select_related('event').order_by('-event__created_at') the query delays over 5s, if I swap select_related with prefetch_related I get the same delay. When I do the query without ordering it responds in the expected time (<1s) -- AccessHistory.objects.all().select_related('event').order_by('-event__created_at') SELECT `history_accesshistory`.`id`, `history_accesshistory`.`event_id`, `history_accesshistory`.`result`, `history_event`.`idEvent`, `history_event`.`created_at`, `history_event`.`processed_at`, `history_event`.`data` FROM `history_accesshistory` LEFT OUTER JOIN `history_event` ON (`history_accesshistory`.`event_id` = `history_event`.`idEvent`) ORDER BY `history_event`.`created_at` DESC -- AccessHistory.objects.all().prefetch_related('event').order_by('-event__created_at') SELECT `history_accesshistory`.`id`, `history_accesshistory`.`event_id`, `history_accesshistory`.`result` FROM `history_accesshistory` LEFT OUTER JOIN `history_event` ON (`history_accesshistory`.`event_id` = `history_event`.`idEvent`) ORDER BY `history_event`.`created_at` DESC I tried with select_related, prefetch_related, indexing created_at field in Event model and setting a default order in Event model. Nothing of this improves the response time. How I can optimize this without moving/copying created_at field to AccessHistory model? -
Processing Model fields during the save process - Django
In my application, the user modifies their profile data and the data is POSTed to ProfileUpdateView upon save. The UI allows the user to modify each of their attributes individually (via AJAX calls) and hence I created multiple Form classes to represent this ability. If I had created a single Form class, the is_valid method would have failed or I would have to write complex validation logic to determine which field was being edited Some fields require pre and/or post-processing during the save operation. I was unable to find any examples on how to best do the same elegantly. So created a dictionary that maps modified field to pre-processing, form class and post-processing methods (instead of nested if-then-else within the post method). Then the view dynamically determines which to apply based on the input in the POST My approach considerations were Focusing, above all else, on code readability and maintainability Keeping custom logic as minimal as possible but this is hard when you are writing a custom application Questions to the community I would truly appreciate your constructive criticism of my design / approach. I am sure there are more elegant ways to accomplish what I am doing and I …