Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Entries not showing on page
Cant seem to figure out why my entries from my database are not appearing on my page but my topics name on the entry page is I'm trying to show show entries from my database on a page, the link to the page works and the Topic name from the database appearing but the entries from the database is not. views.py from django.shortcuts import render from .models import Topic # Create your views here. def index(request): """The home page for learning log.""" return render(request, 'learning_logs/index.html') def topics(request): """Show all topics""" topics = Topic.objects.order_by('date_added') context = {'topics': topics} return render(request, 'learning_logs/topics.html', context) def topic(request, topic_id): """Show a single topic and all its entries""" topic = Topic.objects.get(id=topic_id) entries = topic.entry_set.order_by('-date_added') context = {'topic': topic, 'entries': entries} return render(request, 'learning_logs/topic.html', context) topic.html {% extends 'learning_logs/base.html' %} {% block content %} <p>Topic: {{ topic.text }}</p> <p>Entries:</p> <ul> {% for topic in topics %} <li> <p>{{ entry.date_added|date:'M d, Y H:i' }}</p> <p>{{ entry.text|linebreaks }}</p> </li> {% empty %} <li>There are no entries for this topic yet.</li> {% endfor %} </ul> {% endblock content %} models.py from django.db import models # Create your models here. class Topic(models.Model): """A topic the user is learning about.""" text = … -
Celery Beat sends to workers tasks that do not exist
I saw a lot of similar questions but nothing helped. Every now and then I am receiving the following error: 'app.tasks.do_some_work'. When I check inside the Django container, Celery Beat container, or Celery Worker container's app.tasks module, I don’t see any task with that name. I define the schedule for periodic tasks using celery_app.conf.beat_schedule, and everything appears to be correctly set up. I suspect that there might have been a task with this name in the past, but it was deleted or renamed. Maybe somehow it persists Here is the code inside the containers: from proj.celery import celery_app @celery_app.task def do_some_work(): DoSomeWorkUseCase.execute() return True Tried to use: Define CELERY_IMPORTS in settings -
Issue with Token Authorization in Django that uses djang_auth_adfs (Azure) as authentication backend
I am working on a django project which uses django_auth_adfs (Azure Active Directory) as its authentication backend. I have set up its API service using rest_framework. In the browsable views of the rest_framework, I am able to authorize using the session authentication which requires my settings.py to have such a thing: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'django_auth_adfs.rest_framework.AdfsAccessTokenAuthentication', 'rest_framework.authentication.SessionAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), } With this, I am able to send post requests which requires the user to be authorized. But as soon as I change it to (deleting session authentication): REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'django_auth_adfs.rest_framework.AdfsAccessTokenAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), } I get the http 401 unauthorized error which means it is not able to authorize using the token. This, further causes me not being able to send requests with postman. Does anyone know how I can use the API using adfs tokens? Here is an overall look of how my settings.py look: """ Django settings for core project. Generated by 'django-admin startproject' using Django 5.0.4. For more information on this file, see https://docs.djangoproject.com/en/5.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/5.0/ref/settings/ """ from pathlib import Path import os from dotenv import load_dotenv load_dotenv() # … -
when logging out, it shows white blank page - django 5
so when I want to log the user out it shows a white blank page at 'http://127.0.0.1:8000/accounts/logout/ I'm using the shortcut way to redirect to next page in settings.py and I tested to logout with admin panel and it works fine settings.py ... LOGIN_REDIRECT_URL = 'index' LOGOUT_REDIRECT_URL = 'index' ... this is my urls.py: from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('',include('post.urls')), path('accounts/', include('django.contrib.auth.urls') ), ] this is how I login: login.html: {% extends "base.html" %} {% block content %} <div class="container"> <h1> LOGIN FORM </h1> <form method="post"> {% csrf_token %} {{form.as_p}} <button type="submit" class= "btn btn-success">Log In</button> </form> </div> <br> {% endblock content %} base.html: ... <ul> <li><a class="active " href="{% url 'index' %}">Home</a></li> <li><a class="active " href="{% url 'about' %}">About</a></li> {% if user.is_authenticated %} <li><a class="active " href="{% url 'logout' %}">Log Out</a></li> {% else %} <li><a class="active " href="{% url 'login' %}">Log In</a></li> {% endif %} </ul> ... and for log out all I did was the 'href="{% url 'logout' %}"' in base.html as far as I learned there is no code needed in views.py. .what am I missing? -
Filtering across multiple fields from a subquery where there is no related field
I'm trying to find a portable way to express the following record filtering query using the Django ORM. The intention is to: take a subquery of FilterSpec (eg. with a common FilterGroup) find all instances of Record where Record.text1 = FilterSpec.r_text1 AND Record.text2 = FilterSpec.r_text2 for at least one of the instances of FilterSpec in the subquery. include the matching FilterSpec.filter_name in the returned instances of Record. Record will have high cardinality, >100,000, after filtering typically <1000. The subquery of FilterSpec will have low cardinality, typically <10. Here is a gist of the models: class RecordGroup(Model): name = CharField(unique=True) # further data fields class Record(Model): text1 = CharField() text2 = CharField() group = ForeignKey(RecordGroup) # further data fields class FilterGroup(Model): name = CharField(unique=True) class FilterSpec(Model): r_text1 = CharField() r_text2 = CharField() filter_name = CharField() group = ForeignKey(FilterGroup) The challenge is that there is no formal relation between the record fields and the filter fields. There will be lots of repeated values in Record.text1 and Record.text2. I've found or developed examples where: there is one field being compared there are two fields being compared by concatenating the two fields into one (but I expect this will be slow at scale) there … -
ValueError:The field admin.LogEntry.user was declared with a lazy reference to 'recipes.customuser',but app'recipes'doesn't provide model 'customuser'
This is the Custom user model I also declared in settings AUTH_USER_MODEL="recipes.CustomUser" still I face this error ValueError:The field admin.LogEntry.user was declared with a lazy reference to 'recipes.customuser',but app'recipes'doesn't provide model 'customuser'` from django.db import models from django.http import HttpResponse from django.contrib.auth.models import AbstractUser, Permission from django.conf import settings from django.contrib.auth import get_user_model import secrets class CustomUser(AbstractUser): email=models.EmailField(unique=True) USERNAME_FIELD="email" REQUIRED_FIELDS=["username"] def __str__(self) -> str: return self.email -
What is the configuration for Apache Airflow, Django, PySpark together in Systemd services?
We are using Apache airflow, Django (python), and Spark (pySpark) in our project. Our DAGs are running fine when run 'airflow scheduler' is run from command line. However, these DAGs are not working when 'airflow scheduler' is run from systemd (systemctl). Note: We are using virtual environment to run airflow scheduler (and many python apps). Initially, we faced issues related to Virtual Environment. Later, Django Setup. We resolved the same. However, we are now facing the pyspark related issues. We have tried this for the scheduler. [Unit] Description=Airflow scheduler daemon After=network.target postgresql.service mysql.service redis.service rabbitmq-server.service Wants=postgresql.service mysql.service redis.service rabbitmq-server.service [Service] PIDFile=/home/datauser/Documents/airflow_workspace/airflow_env/bin/scheduler.pid Environment="PATH=/home/datauser/Documents/airflow_workspace/airflow_env/bin:/home/datauser/airflow_workspace/airflow_env/airnet/aqdms:/home/datauser/Downloads/spark-3.5.1-bin-hadoop3/bin:/home/datauser/Downloads/spark-3.5.1-bin-hadoop3/sbin" Environment="PYTHONPATH=/home/datauser/Documents/airflow_workspace/airflow_env" Environment="JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64/jre" Environment="SPARK_HOME=/home/datauser/Downloads/spark-3.5.1-bin-hadoop3" Environment="PYSPARK_DRIVER_PYTHON=python3" Environment="PYTHONSTARTUP=/home/datauser/Downloads/spark-3.5.1-bin-hadoop3/python/pyspark/shell.py" Environment="PYSPARK_PYTHON=python3" Environment="SPARK_CONF_DIR=/home/datauser/Downloads/spark-3.5.1-bin-hadoop3/conf" Environment="PYSPARK_SUBMIT_ARGS=--master local[2] pyspark-shell" User=datauser Group=datauser Type=simple ExecStart=/usr/bin/bash -c 'source /home/datauser/Documents/airflow_workspace/airflow_env/bin/activate ; /home/datauser/Documents/airflow_workspace/airflow_env/bin/airflow scheduler --pid /home/datauser/Documents/airflow_workspace/airflow_env/bin/scheduler.pid' Restart=on-failure RestartSec=5s PrivateTmp=true [Install] WantedBy=multi-user.target What should be the configuration to use Apache airflow, Django, PySpark and virtual environment in Systemd? -
What is causing Unexpected Keyword 500 error when trying to pass data from URL as a variable using Django?
I am taking an online course and replicate the instructor's code on my Mac in VS Code to help me learn how it works; and this is not a homework problem. The instructor was showing how to dynamically create responses based on the URL by sending the last part of the url as a variable to a function that then generates the response. However , when I try it I get a 500 error. I have reviewed my code and it looks identical to the instructors, with only added comments. Fixed paths work fine, i.e. path("brian", views.brian, name = "brian"), works fine, but this fails: path("<str:name>", views.greet, name = "greet") the error is: [18/Jul/2024 20:50:39] "GET /hello/jim HTTP/1.1" 500 59430 [18/Jul/2024 20:50:41] "GET /hello/ HTTP/1.1" 200 5 Internal Server Error: /hello/jim Traceback (most recent call last): File "/Users/XXX/Documents/Work/Python Projects/Dashboard/.venv/lib/python3.12/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "/Users/XXX/Documents/Work/Python Projects/Dashboard/.venv/lib/python3.12/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ TypeError: greet() got an unexpected keyword argument 'Name' I created several bits of code: (comments are mine so when I go back to the code later I can understand it) Created app called hello and added to installed apps in … -
Django prefetch_related not being helpful in diminishing queries
myList = [] qs = MyModel.objects.all().prefetch_related('m2m_model_set') for model in qs: k = model.m2m_model_set.all().values_list('field') myList.extend(k) This code represents what I am doing. Why is the line k = model.m2m_model_set.all().values_list('field') causing many queries? How can I fix this problem and do the same without making so many queries? -
How can I log variables based on database configuration?
Backend: Python 3.11 and Django 5.0.6 Database: PostgreSQL 15.6 We are shifting to deploying a Python executable file for the backend. Consequently, we will be unable to modify the code directly on the server. We do use a logger to save important information or errors from the server. However, sometimes we need to debug the code in production. How can we achieve this considering we can't modify the executable? Can we log/print variables at a specific line number configured in the database, without restarting the backend service? For example, if I want to log a variable report_name1 at line number 40 in the file portal/reports/report.py, how should this be set up? I am considering importing a class or function at the top of the file once, with all configurations being handled from the database. Here's the proposed structure for a LogVariables table: path_name = 'portal/reports/report.py' line_number = 40 variable_name = 'report_name1' is_active = True is_deleted = False -
Optimized way to handle user graded items?
I'm working on website that allows users to grade items, e.g. books. The grade should be displayed on the book page, but also on the collective page containing all books. The grades should be possible to modify: class BookUserGrade: user = foreign_key_to_user book = foreign_key_to_book grade = ... However the operation of requesting the grades each time a user access the booklist (or to lesser degree single book page) seems expensive. I'm pondering about making an additional two fields on the book itself, number_of_grades and cumulative_grade which are going to be updated only on user grading a book. Maybe also calculated_grade (is it worthy to add this field instead of calculating cumulative_grade / number_of_grades on the fly? Or perhaps there's another proper way to do so? -
A local variable seemingly breaking scope in Django
I have introduced this function in a file storage.py that is imported from models.py: def uuid_file_name(kind): def file_name(instance, filename): h = str(uuid.uuid4()) basename, ext = os.path.splitext(filename) return os.path.join(f'{kind}_files', h[0:1], h[1:2], h + ext.lower()) return file_name The intention of the function is to dynamically generate file names in a field declaration, such as: class Thingy(models.Model): widget = FileField(upload_to=uuid_file_name("widget")) Now when I makemigrations, I get an odd error: ValueError: Could not find function file_name in <app>.storage. There is no other mention of file_name in my project, and if I change the identifier, the error message changes accordingly, so the error is definitely from this. However, without some metaprogramming, I can't see how file_name can leak from within this function. I thought I could avoid whatever magic was happening by from .storage import uuid_file_name as _uuid_file_name, hoping Django wouldn't act on a private module member, but the same error occurs. So, a two-fold question: Why is this happening, and how do I prevent it? Is there another way to write the equivalent code to circumvent the error? Full traceback: Traceback (most recent call last): File "<project>/./manage.py", line 22, in <module> main() File "<project>/./manage.py", line 18, in main execute_from_command_line(sys.argv) File "<project>/<venv>/lib/python3.12/site-packages/django/core/management/__init__.py", line 442, in … -
How to restrict available InlinePanel instances that can be choosen in wagtail admin
Let's say we Course and Lesson Wagtail Page models, where Lesson page instances are sub-pages of Course page instance. E.g. "Web Development Course > HTML Lesson". Implemented as: class Course(Page): description = models.TextField(null=True, blank=True) content_panels = Page.content_panels + [ FieldPanel('description'), ] class Lesson(Page): description = models.TextField(null=True, blank=True) content_panels = Page.content_panels + [ FieldPanel('description'), ] parent_page_types = ['app.Course'] Now we add an orderable many2many relationship to Course using InlinePanel(), so we can set each course's lessons and order them in Wagtail Admin. implementation: class Course(Page): description = models.TextField(null=True, blank=True) content_panels = Page.content_panels + [ FieldPanel('description'), InlinePanel('course_lessons', label='Lessons'), ] class CourseLessons(Orderable): page = ParentalKey('Course', on_delete=models.CASCADE, related_name='course_lessons') lesson = models.ForeignKey('Lesson', on_delete=models.CASCADE) panels = [ FieldPanel('lesson'), ] class Lesson(Page): description = models.TextField(null=True, blank=True) content_panels = Page.content_panels + [ FieldPanel('description'), ] parent_page_types = ['course.Course'] Question: How can we limit the inline page choices to specific parent page's sub-pages? E.g. When selecting lessons for a course, only that course's lessons(sub-pages) are available. I thing this can be achieved either by limiting Page -
How to run on_success in Celery ONLY on the last worker process in a group?
I have been scratching my head about this for days now. I have a a background running task, which takes around 1 hour. I am processing 5000 images. I create a group of celery tasks and each task processes 1000 images each. I have an on_success method where I create a 'Finished' database record, and remove the 'inProgress' record. The problem however is, that even while having tons of checks in the on_success method, it still somehow generates 2 'Finished' database records. It sounds confusing, see the code below: def on_success(self, retval, task_id, *args, **kwargs): self.image_job.refresh_from_db() total_nr_of_images = self.image_job.total_nr_of_images stored_results = ImageJobResults.objects.filter(job=self.image_job).count() if stored_results == total_nr_of_images: #It means all the workers have completed processing images # for this job, and we need to create a csv file, and a Finished BC Job with transaction.atomic(using='my_db'): image_job = ImageJob.objects.select_for_update().get(id=self.image_job.id) if not ImageJobFinished.objects.filter(job=image_job).exists(): job_in_progress = ImageJobInProgress.objects.get(job=image_job) started_at = job_in_progress.started_at image_job.generate_results(started_at=started_at,completed_at=now(),csv_rds_handle_job_id=self.image_job.pk) #Now that a ImageJobFinished is created. # We delete the ImageJobInProgress instance job_in_progress.delete() return super().on_success(retval, task_id, *args, **kwargs) Now theoretically, the stored_results should be equal to total_nr_of_images only in the last worker. But both the workers somehow finish on the same time, and they get the same values here. Both of them then … -
How to register voice for TTS in windows 11?
I have some troubles to use 2 additional voices, in my case i try to use Pablo (Spanish - Spain) and George (English - GB). I develop a app in python/Django, from the front i sent a JSON with the language (in this case with what voice i want to read the text), and the text, the back received and process it calling the proper voice reading the text. here is part of the code: import win32com.client, pythoncom from .translator import translate_text def check_voices(): pythoncom.CoInitialize() try: speaker = win32com.client.Dispatch('SAPI.SpVoice') voices = speaker.GetVoices() for voice in voices: print(f"Voice: {voice.GetDescription()}, Id: {voice.Id}") finally: # Finalizar COM pythoncom.CoUninitialize() def sound_rate(speaker): speaker.Rate = -1 # rango -10(lento) - 10(rapido) def sound_volume(speaker): speaker.Volume = 100 # rango 0(bajo) - 100(alto) def text_to_speech(language, text): pythoncom.CoInitialize() try: speaker = win32com.client.Dispatch('SAPI.SpVoice') voices = speaker.GetVoices() check_voices() if language.startswith('en-'): text = translate_text(text, from_code='es', to_code='en') language_map = { 'es-ES-female': 'Microsoft Helena Desktop - Spanish (Spain)', 'es-ES-male': 'Microsoft Pablo Desktop - Spanish (Spain)', 'en-UK-female': 'Microsoft Hazel Desktop - English (Great Britain)', 'en-UK-male': 'Microsoft George Desktop - English (Great Britain)', } voice_name = language_map.get(language) for voice in voices: if voice.GetDescription() == voice_name: speaker.Voice = voice break speaker.Speak(text) except Exception as e: print(f"An error … -
Optimizing Django Application Performance
I'm currently dealing with performance issues in a Django application that's structured as follows: User - Social Network - Post - Tag/Label Each entity is represented by its own table. The number of tags is growing exponentially, even after filtering out less significant ones (tags are assigned by an AI, not humans). Here's what I'm considering to optimize performance: Separate Tables for Insignificant Tags: Move less significant tags to a different table or even a different database. For instance, having 100k rows in MediaTags table and 10M rows in SmallMediaTags. Would this improve the performance of the main tables? Denormalization: Currently, each post is linked to 2-5 primary tags, meaning the number of tags equals 2-5 times the number of posts, with occasional outliers having 6+ tags. This puts a massive load on MediaTags, complicates searches, and incurs additional costs for converting MediaTags into objects. However, if we store top-N tags directly with the posts (e.g., top-10 tags), it could result in nearly a 1:1 ratio. This way, all required tags would be part of the posts themselves, eliminating the need for additional table queries. We have recently started displaying lists of posts with specific tags, which has become a … -
How do I pass request to a form in test
I am trying to pass request to a Django form in unittest. This is my test: def test_AddPairedStudyForm(self): self.client.force_login(self.user) request = RequestFactory().get(reverse("researcher_ui:console")) request.user = self.user study_group = 'StudyGroup' payload = { "study_group": study_group, "paired_studies": [self.study.id, self.study1.id], 'request': request } form = AddPairedStudyForm(data=payload) self.assertTrue(form.is_valid()) This generates a key error in the form: KeyError: 'request' Within the form itself, this error occurs during the __init__ function def __init__(self, *args, **kwargs): self.request = kwargs.pop("request") super(AddPairedStudyForm, self).__init__(*args, **kwargs) Within the CBV I add the request using the get_form_kwargs function: def get_form_kwargs(self): kwargs = super().get_form_kwargs() kwargs["request"] = self.request return kwargs How can I pass the request to the form in unittest? -
How to retrieve the mobile number linked to an any user Aadhaar card in python django
How to retrieve the mobile number linked to an any users Aadhaar card. I want to validate user aadhaar card so I'll send OTP on aadhaar mobile number to validate, that's my approach. So Any builtin API or any Doc suggestion anyone can refer. -
import class in admin.py from package that in site-packages
I used django-comment-system I want import classadmin from admin.py (that in my app project) at admin.py (that in LIB/site-packages/comment) from kernel.blog import models #here is LIB/site-packages/comment/admin.py i tried with that code but give me error: No module named 'kernel.blog' kernel is base and blog is a app in kernel -
Resize readonly fields in Django Admi
In my Django admin im currently displaying JSONField as readonly, the JSON data is quite large and takes up about 80-90% of the page. I was able to find an answer for how one might resize a not readonly field here but other then that I am lost. My ideal outcome would have the large JSON data in a scrollable text box like so: Ideal outcome How can I control the size of a readonly field without truncating the data? -
Database is locked when acreate operation is handled
I'm writting tests for my project. I tried to add some async things to it. And that things worked but when I run tests it fails: django.db.utils.OperationalError: database is locked await UserBill.objects.acreate(user_id=user_id, bill=total_cost, duration=rent_range) Test is: @pytest.mark.django_db @override_settings( CELERY_TASK_EAGER_PROPAGATES=True, CELERY_TASK_ALWAYS_EAGER=True, CELERY_BROKER_URL='memory://', CELERY_RESULT_BACKEND='cache+memory://', ) def test_finish_rent(django_db_blocker, django_db_setup): with django_db_blocker.unblock(): user = User.objects.get(email='test2@example.com') bicycle = Bicycle.objects.get(name='Bicycle 2') finish_rent(bicycle, user) assert BicycleUser.objects.filter(bicycle=bicycle, user=user).exists() is False conftest.py is: @pytest.fixture(scope='session') def django_db_setup(delete_db, django_db_blocker): with django_db_blocker.unblock(): call_command('sqlflush') with django_db_blocker.unblock(): call_command('migrate', '--noinput') yield finish_rent: def finish_rent(bicycle, user): bicycle_user = BicycleUser.objects.get(bicycle=bicycle, user=user) start_rent = bicycle_user.rent_start bicycle_user.delete() add_bill.delay(bicycle.id, user.id, start_rent) async task: async def add_bill_task(bicycle_id, user_id, start_rent): now = timezone.now() rent_range = (now - start_rent).total_seconds() rent_range = rent_range // 60 bicycle = await Bicycle.objects.aget(id=bicycle_id) total_cost = bicycle.cost_per_minute * rent_range await UserBill.objects.acreate(user_id=user_id, bill=total_cost, duration=rent_range) @shared_task def add_bill(bicycle_id, user_id, start_rent): asyncio.run(add_bill_task(bicycle_id, user_id, start_rent)) What's wrong with my code guys? -
Datatables causes table element to disappear, only when deployed
I have a Django web app which I'm hosting on Heroku, and I'm using the Datatables JQuery library to add extra features to a table. When I run my app locally, it works beautifully. When I deploy on Heroku, the JQuery function that loads the Datatable instead causes the table to disappear. There are no errors in the console and nothing different in the Network tab than when I run locally. I'm thinking that it might be some kind of configuration problem with Heroku, even though Datatables is client-side? Any advice would be appreciated. I know that the JS script is running because I can print things to the console. I also know that it's specifically the creation of the Datatable that causes the problem, because if I include a setTimeout call, the table appears (in default HTML format) until the timeout ends and the function gets called. Some excerpts - from table.js: $('#ads').DataTable( { autoWidth: false, tabIndex: -1, pageLength: 100, stateSave: true, order: [[3, 'desc']], columnDefs: [{ orderable: false, targets: 2 }, { render: $.fn.dataTable.render.number(',', '.', 0, '$', ''), targets: 3 }, { searchPanes: { show: true }, targets: $(location).attr('pathname')=='/review/all' ? [0, 1, 4] : [0, 1] }, { … -
how to make every posts equal in size when respond to screen size?
Inside the post div, there will be multiple post rows. Each row contains maximum 4 posts. So when there are 5 posts there comes the problem with responsiveness. First 4 posts (first row) will respond to the screen size but the 5th post (second row) does nothing because there are space left for the 5th post. <div class="posts"> {% if post %} {% for media in post %} {% if forloop.counter0|divisibleby:"4" %} <div class="post-row"> {% endif %} <a id="post-wrapper" href="{% url 'sh-media' %}?pid={{media.pid}}"> <div class="thumbnail-container"> <img src="{{ media.media_thumbnail.url }}" class="post-thumbnail"> <div class="gradient-overlay"> <h2 class="video-caption">{{ media.caption}}</h2> <p class="video-description">{{ media.descr }}</p> </div> </div> </a> {% if forloop.counter0|add:"1"|divisibleby:"4" or forloop.last %} </div> {% endif %} {% endfor %} {% endif %} </div> <style> .posts{ display: flex; flex-direction: column; color: #fff; padding-top: 15px; justify-content: flex-start; } .post-row{ display: flex: } #post-wrapper{ margin: 20px 10px; } </style> Is there any way to make all the posts will maintain the same size when it respond to the screen size? Output HTML: <div class="posts"> <div class="post-row"> <a id="post-wrapper" href="/watch-profile%23ed-media?pid=060"> <div class="thumbnail-container"> <img src="/static/images/9_16%20Video.png" class="post-thumbnail"> <div class="gradient-overlay"> <h2 class="video-caption">sea breeze</h2> <p class="video-description">Winter morning sweet music</p> </div> </div> </a> <a id="post-wrapper" href="/watch-profile%23ed-media?pid=bea"> <div class="thumbnail-container"> <img src="/static/images/9_16%20Audio.png" class="post-thumbnail" > <div … -
Django Topic dropdown displays Topic object(1) but not the name of the object
Django Topic dropdown displays Topic object(1) but not the name of the object class Topic(models.Model): """A topic the user is learning about.""" text = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) class Entry(models.Model): """Something specific learned about a topic""" topic = models.ForeignKey(Topic, on_delete=models.CASCADE) text = models.TextField() date_added = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural = 'entries' def __str__(self): """Return a simple string representation of the entry.""" return f"{self.text[:50]}..." Above is the code in the models.py, I'm very knew to django but I an alright understanding of python. Cant really seem to figure out why when I navigate to the website the topics name doesnt appear but instead it says topic object(1) --> topic object(2) -
How to write a Case() SQL expression with an aggregated field (Sum) using Django's query builder
I am trying to recreate this SQL statement using Django's query builder: CASE WHEN sum(imps) = 0 THEN NULL ELSE SUM(total_expenses) / (sum(imps) / 1000) END as "cpm" I have tried: MyModel.objects.annotate( cpm=Case( When( Sum("imps")>0, then=Sum("total_expenses") / Sum("imps"), ), default=0, output_field=FloatField(), ) ) However it doesn't work because of this TypeError '>' not supported between instances of 'Sum' and 'int'. If there was a field lookup that enabled me to do total_imps__sum__gt=0, I am sure that would solve the problem. Note: Adding Sum("imps") as an annotation (total_imps=Sum("imps")) and doing total_imps__gt=0 works but it is not an ideal solution as I would have to create multiple annotations for fields I won't need.