Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
in static file in django the background_image not work
I tried using a code to change the background color and it worked fine. But when I used the background_image code, the code did not work and gave me (Failed to load resource: the server responded with a status of 404 (Not Found)) Although the path is correct This is the path to the image inside the app D:\Todos\Todosproject\static\images\svitlana-j7Ssk0Km8Jo-unsplash.jpg static/styles body { background-image: url('/Todos/Todosproject/static/images/svitlana-j7Ssk0Km8Jo-unsplash.jpg'); } base.html <!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <link rel="stylesheet" type="text/css" href="{% static 'css/styles.css' %}"/> <title> {% block title %} {% endblock title %} </title> </head> <body> {% block body %} {% endblock body %} </body> </html> settings.py in django STATIC_URL = 'static/' STATICFILES_DIRS = [BASE_DIR / "static"] -
How to save OneToMany in Django Admin
This is my models class Author(models.Model): full_name = models.CharField(max_length=100) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.full_name class Book(models.Model): title = models.CharField(max_length=100) author = models.ForeignKey(Author, on_delete=models.CASCADE, db_column='author_id',related_name='authors',null=True,blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.title My admin setup @admin.register(Author) class AuthorAdmin(admin.ModelAdmin): list_display = ('id', 'full_name', 'created_at', 'updated_at') search_fields = ['full_name'] ordering = ['-created_at'] @admin.register(Book) class BookAdmin(admin.ModelAdmin): list_display = ('id', 'title', 'author', 'created_at', 'updated_at') search_fields = ['title'] list_filter = ['author__full_name'] ordering = ['-created_at'] I want from create Author page. I can select multiple Book with author_id = Null. And when i save it, it will update author_id for all selected Book Please help me -
Resize Tables with css
3v and Django 5.1 for my Forms I created a file css but I don't know how to use it, my CSS is still empty. settings.py enter image description here tipomaterial.html {% extends 'base.html' %} {% block content %} <main class="container py-5"> <table class="table table-bordered"> <thead> <tr> <th style="text-align: center;"> <strong> <h2>Tipo de Material</h2> </strong> </th> <th> <a class="btn btn-success" role="button" href="{% url 'creartipomaterial' %}"> <i class="bi bi-plus-square-fill"> Agregar </i> </a> </th> </tr> <tr style="text-align: center;"> <th scope="col">Nombre del material</th> <th scope="col" colspan="2">Acciones</th> </tr> </thead> <tbody class="table-group-divider"> {% for datos in tipomaterial %} <tr> <td> <li class="list-group-item" href="{% url 'detalle_tipomaterial' datos.id %}"> <strong>{{datos.nombre}}</strong> </li> </td> <td> <a class="btn btn-primary" href="{% url 'detalle_tipomaterial' datos.id %}" role="button"> <i class="bi bi-pencil-fill"> Editar </i> </a> <a class="btn btn-danger" href="{% url 'eliminar_tipomaterial' datos.id %}" role="button"> <i class="bi bi-trash3-fill"> Eliminar </i> </a> </td> </tr> {% endfor%} </tbody> </table> </main> {% endblock %} design enter image description here I wish my table was smaller. Any idea please -
403 Forbidden POST Request when trying to log out using React front end with Axios and Django with rest-framework
I keep getting an 403 Forbidden error when trying to log out of the user account. I am able to log in fine, I see in the cookies that there is a sessionID and a csrf token. However every single time without fail I get a 403 forbidden error when trying to log out. I have withCredentials:true and include the csrf token in the header. I have my middleware in the right order, I have all the correct cors-headers configuration and allowed hosts. When inspecting the network details using F12 I can see that the sessionID cookie is not being sent along with the csrf token. Not sure why? I am at my wits end. Here is my code for the login and logout front end as well as relevant settings.py code and views.py for logout. Axios: import axios from "axios"; axios.defaults.xsrfCookieName = 'csrftoken'; axios.defaults.xsrfHeaderName = 'X-CSRFToken'; const client = axios.create({ baseURL: "http://127.0.0.1:8000", withCredentials: true, }); export default client; Login: function submitLogin(e) { e.preventDefault(); client.post("/api/login/", { username, password }, { withCredentials: true, }) .then(function(res) { if (res.data.redirect_url) { navigate(res.data.redirect_url); } else { console.error("No redirect URL provided."); } }) Logout: function logout(e) { e.preventDefault(); const csrftoken = document.cookie.split('; ').find(row => row.startsWith('csrftoken='))?.split('=')[1]; … -
How to handle prefixed UUIDs in Django Admin for querying and displaying objects?
I am working on a Django project with a custom UUIDField with a prefix (e.g., ft_) to represent IDs. The raw UUID is stored in the database, but I want the prefixed value (e.g., ft_) to be shown in API responses, admin interfaces, and elsewhere. However, this creates issues when querying objects in Django Admin because the URLs include the prefixed ID, and Django tries to query the database directly using this prefixed value. Here is my custom field implementation: import uuid from django.db import models class PrefixedUUIDField(models.UUIDField): def __init__(self, prefix, *args, **kwargs): self.prefix = prefix super().__init__(*args, **kwargs) def from_db_value(self, value, expression, connection): if value is None: return value return f"{self.prefix}_{value}" def get_prep_value(self, value): if isinstance(value, str) and value.startswith(f"{self.prefix}_"): value = value.split(f"{self.prefix}_")[1] return super().get_prep_value(value) def to_python(self, value): if isinstance(value, uuid.UUID): return f"{self.prefix}_{value.hex}" if isinstance(value, str) and not value.startswith(f"{self.prefix}_"): return f"{self.prefix}_{value}" return value The model: class FamilyTree(models.Model): id = PrefixedUUIDField(prefix="ft", primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=255) In Django Admin, the URL for editing an object looks like this: http://admin.localhost:8000/family_tree/familytree/ft_5F5479ca65374d401d9466d57fc95e4072/change/ However, this causes the following error: invalid input syntax for type uuid: "ft_5F5479ca65374d401d9466d57fc95e4072" I understand this happens because Django Admin tries to query the database using the prefixed id, but the database … -
Column 'tbl1.id' is not the same data type as referencing column 'tbl2.field_id' in foreign key 'tb1_field_id_tbl2_id'
I have a problem with migrations. I'm using database which was created with old Django version 1.4 in new application with Django version >5. The problem is that old Django is using different data type for primary key field (AutoField - int in database). So in database datatype of old django's primary key is "int" and in the new Django datatype is "bigint". I've created new model with Foreign Key to old model and now I'm facing an error: Column 'tbl1.id' is not the same data type as referencing column 'tbl2.field_id' in foreign key 'tb1_field_id_tbl2_id' How can I solve this problem? Only thing that help is to assign db_constraint=True in the models.ForeignKey field. But I don't want have this risk. -
Suggestion of Django "email queue" package for current versions?
I found the django-mail-queue and django-email-queue packages, which are several years old yet appear to be well-used. But, as recently discussed here moments ago, I ran into unexpected migration issues. (And, with help, I think solved them.) But I'd like to ask if anyone has a better suggestion – for current Django, current MySQL and so-on. "I just want: 'It Just Works.™'" No migration quibbles, and so on. I want to simply be able to queue email-only messages and then send them with a periodically-scheduled 'manage' subcommand. That's it, that's all. The above-cited packages will work for me, but the migration issue startled me. -
Why do I have to create a new thread for updating a database record? (Django Rest Framework)
I'm using Django Rest Framework for creating an API. The idea is that the user uploads some data using a POST request. This data is uploaded to a database. Once uploaded, a new Python thread is created, running some operations on said data. Then when operations have finished, the result is written to the original database record. Using this approach the API remains accessible, while also working on the operations in the background. The user can check the operations status using a GET request. For some reason, when trying to update the record with the operation results, I got the following error: SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async It was confusing, since the operation and updating function was already running using a thread. I would not get the error when substituting the operations with some simple mock-up test results (strings). Not even when using time.sleep() for a longer period than the actual operations would take. So I suspect the problem has something to do with the operations I'm running, even though they do not interact with Django whatsoever. I fixed the problem by creating new threads specifically for saving the updated … -
Django alterfield migration to textfield fails
The migration for Django package django-mail-queue contains the following in relevant part: migrations.AlterField( model_name='mailermessage', name='to_address', field=models.TextField(db_index=True, verbose_name='To'), ), But it fails on MySQL 9.0.1 (Django 5.1.5) with the following error: django.db.utils.OperationalError: (1170, "BLOB/TEXT column 'to_address' used in key specification without a key length") Any idea why? I found a closed bug-report for Django (from some years ago) in which this kind of AlterField request had problems, but it appears to be unrelated. -
django_apscheduler calls my job many times
I have a scheduler python package with this main file: from apscheduler.schedulers.background import BackgroundScheduler from django_apscheduler.jobstores import DjangoJobStore, register_events from django.utils import timezone from django_apscheduler.models import DjangoJobExecution import sys # This is the function you want to schedule - add as many as you want and then register them in the start() function below def scheduled_function(): print("my function is running as scheduled") def start(): scheduler = BackgroundScheduler() scheduler.add_jobstore(DjangoJobStore(), "default") scheduler.remove_all_jobs() scheduler.add_job(scheduled_function, 'interval', seconds=10, name='scheduled_function', jobstore='default') scheduler.start() scheduler.print_jobs() I call it from my apps.py like this: from django.apps import AppConfig import os class MyAppConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'my_server_app' def ready(self): if os.environ["RUN_MAIN"]: from my_app.scheduler import scheduler scheduler.start() Despite calling remove_all_jobs, my function is called many times. For example, the output of my print_jobs call looks like this after I've restarted django a few times: Jobstore default: scheduled_function (trigger: interval[0:00:10], next run at: 2025-01-16 11:43:56 UTC) scheduled_function (trigger: interval[0:00:10], next run at: 2025-01-16 11:43:56 UTC) scheduled_function (trigger: interval[0:00:10], next run at: 2025-01-16 11:43:56 UTC) scheduled_function (trigger: interval[0:00:10], next run at: 2025-01-16 11:44:01 UTC) scheduled_function (trigger: interval[0:00:10], next run at: 2025-01-16 11:44:02 UTC) scheduled_function (trigger: interval[0:00:10], next run at: 2025-01-16 11:44:03 UTC) scheduled_function (trigger: interval[0:00:10], next run at: 2025-01-16 11:44:04 UTC) … -
How do I hot reload a Django reusable app?
I am creating a Django reusable app. I can build the package using python -m pip install build which creates *.tar.gz file which i can install. But how do i make the main Django app auto reload on changes in the child app. I have wasted many hours looking for something to do this but couldn't find anything. -
Adding the user I created in Django to the server with ldap
I want to add the user created in Django to my server via LDAP. Even if I get the message that the connection is successful, it does not continue and gives this warning: LDAP connection successfully. Error occurred during LDAP connection: ('unable to open socket', [(LDAPSocketOpenError('socket connection error while opening: [WinError 10060] I can attract users to my database with the connection I made. def create_user_in_ldap(request, django_user): """ Adds the user created in Django to the LDAP server. """ try: ldap_config = get_object_or_404(LdapConfig,company=request.user.company) ldap_server = ldap_config.ldap_server ldap_username = ldap_config.bind_username ldap_password = ldap_config.bind_password ldap_domain = ldap_config.bind_dn server = Server(ldap_server, get_info=ALL) connection = Connection( server, user=f"{ldap_domain}\\{ldap_username}", password=ldap_password, authentication=NTLM, auto_bind=True ) if not connection.bind(): print(f"LDAP connection unsuccessful: {connection.result}") return False print("LDAP connection succesfully") user_dn = f"cn={django_user.username},ou=Users,dc=example,dc=com" attributes = { "objectClass": ["top", "person", "organizationalPerson", "user"], "cn": django_user.username, "sn": django_user.last_name or "NoLastName", "givenName": django_user.first_name or "NoFirstName", "displayName": f"{django_user.first_name} {django_user.last_name}", "mail": django_user.email, "userPassword": "default_password", } connection.add(user_dn, attributes=attributes) print("User add result:", connection.result) if connection.result["description"] == "success": print(f"User successfully added to LDAP server {django_user.username}") return True else: print(f"Error adding user: {connection.result['description']}") return False except Exception as e: print(f"Error occurred during LDAP connection: {str(e)}") return False -
Set-cookie isn't working with React and Django
I am trying to make a simple session-based authentication with Django and React, but the browser won't set cookies LoginView: class LoginView(APIView): def post(self, request): username = request.data.get("username") password = request.data.get("password") user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return Response( {"message": "Login successful", "username": user.username}, status=status.HTTP_200_OK, ) else: return Response( {"error": "Invalid credentials"}, status=status.HTTP_401_UNAUTHORIZED ) Front-end logic: const getData = () => { fetch("http://127.0.0.1:8000/me/").then( (res) => { return res.json() } ).then( (data) => { setUsername(data.username) } ) } const login = () => { fetch("http://127.0.0.1:8000/login", { method: "POST", body: JSON.stringify({ "username": "user", "password": "password" }), headers: { "Content-Type": "application/json", } }).then(function(response){ return response.json(); }).then((data) => console.log(data)); getData() } Note: Backend actually sends back Set-Cookie header: set-cookie: csrftoken=OHi2iTT8vDvnn7pAzbb705zrj3gFkFLK; expires=Thu, 15 Jan 2026 08:31:49 GMT; Max-Age=31449600; Path=/ set-cookie: sessionid=jna0kbgo4k8x8spoyzyyxch2d24bz2li; expires=Thu, 30 Jan 2025 08:31:49 GMT; HttpOnly; Max-Age=1209600; Path=/ -
Django DRF API endpoint can be called via Postman but gives back 404 not found in pytest
I'm currently rewriting our Django unit tests (written with django.unittest library) in pytest, and I'm encountering an issue. I use a separate conftest.py file where I store my pytest fixtures and also load my JSON fixtures to fill the database with test data. One of my pytest fixture methods creates a user, and another one creates an authorized client. The user fixture also takes db as an argument. That's basically the base setup. The test method calls an endpoint that includes the user_id in the URL. The call looks something like: response = authorized_client.get(path=f"/user/{user_id}", headers=header) Testing the endpoint manually in Postman gives back the user data and a 200 status code. However, pytest returns a 404 status code. User.objects.exists(id=user_id) This confirmed that the user exists in the database. I investigated further and called the endpoint that retrieves all users. The user_id I used in the call to the endpoint was not included in the response. I suppose that's why I get a 404 back. The Question Why do I get User.objects.exists(id=user_id) but the user with that ID is not actually there when I call the endpoint? Does pytest handle test database isolation differently than django.unittest so that the viewset can't … -
ModuleNotFoundError at /api/v1/account/users/1/
I have a django rest framework project with this kind of treeroot in the accounts model I have a User model like bellow : class User(AbstractUser): phone_number = models.CharField(max_length=11, unique=True) then I have a simple serializer and ModelViewSet for this model the apps.py in accounts is as bellow : from django.apps import AppConfig class AccountsConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'api.accounts' and in the api directory apps.py is like this : from django.apps import AppConfig class ApiConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'api' and at the end this is my settings.py """ Django settings for listings project. Generated by 'django-admin startproject' using Django 3.2.4. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ import environ import os from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ env = environ.Env() DEBUG = True BASE_URL_V1 = 'api/v1/' # reading the EVN file environ.Env.read_env(BASE_DIR.__str__() + '/../.env') # Raises django's ImproperlyConfigured exception if SECRET_KEY not in os.environ SECRET_KEY = env('SECRET_KEY') AUTH_USER_MODEL = "accounts.User" INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'drf_spectacular', … -
Issue with Django CheckConstraint
I'm trying to add some new fields to an existing model and also a constraint related to those new fields: class User(models.Model): username = models.CharField(max_length=32) # New fields ################################## has_garden = models.BooleanField(default=False) garden_description = models.CharField( max_length=32, null=True, blank=True, ) class Meta: constraints = [ models.CheckConstraint( check=Q(has_garden=models.Value(True)) & Q(garden_description__isnull=True), name="garden_description_if_has_garden", ) ] The problem is that when I run my migrations I get the following error: django.db.utils.IntegrityError: check constraint "garden_description_if_has_garden" is violated by some row But I don't understand how the constraint is being violated if no User has a has_garden, the field is just being created and also its default value is False 🤔. I'm using django 3.2 with postgresql. What is the proper way to add this constraint? If it's of any use here's the autogenerated migration: # Generated by Django 3.2.25 on 2025-01-15 23:52 import django.db.models.expressions from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("some_app", "0066_gardenuser"), ] operations = [ migrations.AddField( model_name="user", name="garden_description", field=models.CharField(blank=True, max_length=32, null=True), ), migrations.AddField( model_name="user", name="has_garden", field=models.BooleanField(default=False), ), migrations.AddConstraint( model_name="user", constraint=models.CheckConstraint( check=models.Q( ("has_garden", django.db.models.expressions.Value(True)), ("garden_description__isnull", True), ), name="garden_description_if_has_garden", ), ), ] -
How to display multiple self-related foreign key data in Django/HTML?
I am trying to create a django web app for displaying various data (a question and some additional data).My data consists of a question body and industry guidance, which contains several bullet points. Each bullet point may contain additional sub options itself as well, etc. Example data: Question body: Was everyone familiar with the location, purpose, testing and oepration of fire doors? Industry Guidance: Operational readiness Maintenance and testing Regular inspections Regular maintenance Weekly Monthly ... Below are my models: class BaseGuidance(models.model): text = models.CharField(max_length=2000) parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name="sub_options") class Meta: abstract = True def __str__(self): return self.text class IndustryGuidance(BaseGuidance): pass class Question(models.model): body = models.CharField(max_length=400) industry_guidance = models.ForeignKey(IndustryGuidance, on_delete=models.CASCADE, null=True, blank=True) Here is my view, which is rendering the HTML: def index(request): questions = Question.objects.all() industry_guidance = IndustryGuidance.objects.prefetch_related( 'sub_options', ).all() return render(request, "sire/index.html",{ "questions": questions, "industry_guidance": industry_guidance }) Below is my HTML: <td scope="col"> <ul class="list-group"> {% for guidance in industry_guidance %} <li>{{ guidance.text }} </li> <ul> {% for sub_option in guidance.sub_options.all %} <li>{{ sub_option.text }}</li> {% endfor %} </ul> {% endfor %} </ul> </td> I am really confused on to how exactly I should approach this problem in order to fetch all data and display … -
Cant upload media from Django app to R2 Cloudflare or Digital Ocean Spaces
im having some issues uploading media to R2 Cloudflare or Digital Ocean Spaces , the app is hosted in Digital Ocean, i guess something is blocking the app, and I dont know where start looking. Django + Nginx + Gunicorn. Local server is doing well. Any ideas? Thank you! -
Error importing serializers from rest_framework in Django project
I am facing an issue while trying to import serializers from the rest_framework module in my Django project. When I use the following line of code: from rest_framework import serializers I receive the following error message: ImportError: cannot import name 'serializers' from 'rest_framework' I have ensured that Django REST Framework is installed correctly, but I am still encountering this problem. Can someone help me figure out what might be causing this issue? Any suggestions for troubleshooting this error would be appreciated! I have already tried selecting the correct interpreter, and I have verified that both pip and django are installed. I also confirmed that Python is set up correctly, but I am still encountering this issue. I have also added it in the settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'api', 'rest_framework', ] -
The view stock.views.eliminar_tipomaterial didn't return an HttpResponse object. It returned None instead
I am doing a CRUD with Django 5.1 I want to delete the data when I press on the delete button it stays in the same but it shows this error: views.py def eliminar_tipomaterial(request, tipomaterial_id): tipomaterial = get_object_or_404(TipoMaterial, pk=tipomaterial_id) if request.method == 'POST': tipomaterial.delete() return redirect('tipomaterial.html') Tipomaterial.html <main class="container"> <div class="table-responsive"> <table class="table table-bordered"> <thead> <tr style="text-align: center;"> <th scope="col">Nombre del material</th> <th scope="col" colspan="2">Acciones</th> </tr> </thead> <tbody class="table-group-divider"> {% for datos in tipomaterial %} <tr> <td> <li class="list-group-item" href="{% url 'detalle_tipomaterial' datos.id %}"> <strong>{{datos.nombre}}</strong> </li> </td> <td> <a class="btn btn-primary" href="{% url 'detalle_tipomaterial' datos.id %}" role="button"> <i class="bi bi-pencil-fill"> Editar </i> </a> <a class="btn btn-danger" href="{% url 'eliminar_tipomaterial' datos.id %}" role="button"> <i class="bi bi-trash3-fill"> Eliminar </i> </a> </td> </tr> {% endfor%} </tbody> </table> </div> </main> enter image description here -
Can you make sortable.js work with boostrap 5 modal?
I'm building a checklist app for fun and I'm trying to use sortable.js with python django. I can make a sortable list work in this example with the html as follows {% extends 'BJJApp/base.html' %} {% load static %} {%load crispy_forms_tags %} {% block content %} <br><br> <div id="standalone-items-container"> {% for item, formset, links in standalone_items_formsets_links %} <div class="modal fade" id="exampleModalToggle-{{ item.id }}" aria-hidden="true" aria-labelledby="exampleModalToggleLabel-{{ item.id }}" data-item-id="{{ item.id }}" tabindex="-1"> <div class="modal-dialog modal-dialog-centered"> <div class="modal-content"> <div class="modal-header"> <h1 class="modal-title fs-5" id="exampleModalToggleLabel-{{ item.id }}" style="color: {% if item.important %}red{% else %}inherit{% endif %};">{{ item.title }}</h1> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> <form method="POST" id="main-form-{{ item.id }}" action="{% url 'viewitem' item.id %}"> {% csrf_token %} <div class="form-group"> <label for="title">Title</label> <input type="text" name="title" class="form-control" id="title-{{ item.id }}" value="{{ item.title }}" required disabled> </div> <div class="form-group"> <label for="memo">Memo</label> <textarea name="memo" rows="5" class="form-control" id="memo-{{ item.id }}" disabled>{{ item.memo }}</textarea> </div> <div class="form-group form-check"> <input type="checkbox" name="important" class="form-check-input" id="important-{{ item.id }}" {% if item.important %}checked{% endif %} disabled> <label class="form-check-label" for="important">Important</label> </div> </form> </div> <div id="links-{{ item.id }}"> {% if links %} <ul> {% for link in links %} <li><a href="{{ link.url }}" target="_blank">{{ link.url|urlizetrunc:50 }}</a></li> {% endfor %} </ul> {% else %} … -
Expensive django calculation needs to run on model change
I am working on a django application that has a model with a field that needs to be calculated when the model changes. The calculation itself is relatively expensive (1+ seconds) especially if/when this field is recalculated for a large queryset. It is important that this field is recalculated immediately following the model change because it determines the workflow which the user needs to follow and the field value is propagated to the UI for the user to see. At a minimum the calculation needs to be guaranteed to run after update or some way to indicate the calculation is stale. The current implementation which was not an issue because the calculation was previously less complicated/expensive (before requested changes by the client) is as follows: user makes edit in UI and model is updated API receives changes and applies changes to model model .save() is overridden so the field is calculated and set With this implementation we also disabled the queryset manager on the model to prevent the use of .update() to ensure that field is always recalculated on .save(). I am curious on how others would implement something like this to be as efficient as possible and not relying … -
How to implement thumbnail images into Wagtail’s ModelViewSet?
Is it still possible to implement a thumbnail image in a ModelViewSet listing view? Here is an example for a NewsPost model. class NewsPostViewSet(ModelViewSet): model = NewsPost list_display = ["title", "category", "date_start", "date_end", "live"] add_to_admin_menu = True icon = "calendar-alt" menu_label = "News" The PageListingViewSet has columns with all kinds of columns for different model types. But also no "ImageColumn" to display a thumbnail image. I miss the ThumbnailMixin that the Wagtail ModelAdmin app provided, which is now deprecated. Does anybody know a workaround? -
Django image not showing on webpage
I am following the w3schools tutorial w3schoools-img and trying to display a img on my Django webpage but I am getting a small green icon instead: this is my template: {% extends "book/base.html" %} {% block content %} <h1>Books</h1> <h2>Genre: {{ genre }}</h2> <p>Books: </p> {% load static %} <img src="{% static '71wdAPcG-PL._SY466_.jpg' %}"> {% for i in titles %} <li> {{ i.text }} </li> {%empty%} {%endfor%} {% endblock content %} Is there something I am doing wrong? I have created a static folder with the image in my template folder. Much appreciation! -
django_filters.Filterset with context data from FilterView
I've a LearnerInstance model: class LearnerInstance(models.Model): learner = models.ForeignKey(Learner, on_delete=models.CASCADE) aim = models.ForeignKey(Aim, on_delete=models.CASCADE) ... class Meta: unique_together = ("learner", "aim") def __int__(self): return self.learner def name(self): return f"{self.learner.firstname} {self.learner.surname}" views.py class GroupDetailView(FilterView): model = LearnerInstance template_name = "group_detail.html" table = LearnerGroupTable filterset_class = LearnerInstanceFilter def get_context_data(self, **kwargs): context = super(GroupDetailView, self).get_context_data(**kwargs) queryset = LearnerInstance.objects.filter( learner__group__short_name=self.kwargs["pk"]) f = LearnerInstanceFilter( self.request.GET, queryset=queryset.filter(aim=self.request.GET.get("aim"))) context["table"] = LearnerGroupTable(f.queryset) context["group"] = Group.objects.filter(short_name=self.kwargs["pk"]).values() return super().get_context_data(**context) filters.py class LearnerInstanceFilter(django_filters.FilterSet): class Meta: model = LearnerInstance fields = ["aim"] Question: How do I change the filter to show only the distinct aim options returned by the queryset (all learner instances related to a selected group) within the get_context_data? The database contains all possible aims which are offered through the filter (I know this is due to the filter being linked to the model and aim field), I want to be presented with only a list of aims that are unique to the learners within the current context.