Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
msgstr is not a valid Python brace format string due to '�'
I have a Django i18n entry like: #: mycode.py:2323 #, python-brace-format msgid "Linked alias <a href=\"{alias_url}\" target=\"blank\">{alias}</a> to record <a href=\"{record_url}\" target=\"blank\">{record}</a>." msgstr "<a href=\"{alias_url}\" target=\"blank\">エイリアス{エイリアス}</a>を会社<a href=\"{record_url}\" target=\"blank\">{会社}に</a>リンクしました。" Yet when I run django-admin compilemessages I get the error: Execution of msgfmt failed: /path/to/django.po:222: 'msgstr' is not a valid Python brace format string, unlike 'msgid'. Reason: In the directive number 1, '�' cannot start a field name. Why is it complaining about the non-existent character '�' in my msgstr? -
How do I pull the current user onto the page for this practice project? I am struggling with the backend Django Rest Framework
I cant seem to pull any data whatsoever onto my page from the backend. Any guidance or resources would be helpful. Right now, im just trying to display whoever is logged in. I can add users to the backend through a table called customuser, but I dont know how to retrieve any data such as the current logged in user from rest_framework_simplejwt.serializers import TokenObtainPairSerializer from rest_framework import serializers from .models import * from django.shortcuts import render from django.http import HttpResponse, JsonResponse import requests import json class CustomUserSerializer(serializers.ModelSerializer): email = serializers.EmailField( required=True ) username = serializers.CharField() password = serializers.CharField(min_length=8, write_only=True) class Meta: model = CustomUser fields = ('email', 'password', 'first_name', 'last_name', 'username') extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): password = validated_data.pop('password', None) instance = self.Meta.model(**validated_data) if password is not None: instance.set_password(password) instance.save() return instance class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' import React, { useState, useEffect } from 'react'; import { useGlobalState } from '../context/GlobalState'; import authService from '../services/auth.service'; import jwtDecode from 'jwt-decode'; import Link from 'next/link'; import axios from 'axios'; import Layout from './layout'; import { useRouter } from 'next/router'; const ProfilePage = () => { const router = useRouter(); const [postData, setPostData] = useState({ … -
Django Group migrations don't persist on db even when using --reuse-db
My Django app creates some Groups via migrations. I'm having issues with pytest not finding the Groups when using the --reuse-db flag. My understanding was: migrations get applied before pytest runs, and although the tests get executed in a transaction to roll back any database changes, the db gets cached and those migrations persist (if using the --reuse-db flag). But that's not happening here. To repro my problem: if I run a test with the --create-db flag, it has no problem with any Group it needs to access if I switch to --reuse-db flag, and run the test twice, the second time fails with a Group.DoesNotExist error: ====================================================================================== short test summary info ====================================================================================== FAILED /test/something.py::test_defaults - django.contrib.auth.models.Group.DoesNotExist: Group matching query does not exist. FAILED /test/something.py::test_create - django.contrib.auth.models.Group.DoesNotExist: Group matching query does not exist. FAILED /test/something.py::test_get - django.contrib.auth.models.Group.DoesNotExist: Group matching query does not exist. ============================================================================= 3 failed, 1 passed, 116 warnings in 2.57s =================================================================== -
Add element to user attribute with foreign key
Each user has a groups-attribute as a list of groups. These are foreign keys of a groups table. Now I want to programmatically add some groups to a users groups attribute. I tried: user.groups = [] getting me Direct assignment to the forward side of a many-to-many set is prohibited. Use emails_for_help.set() instead How do I do this instead? And how do I set the groups which is a default feature of django? How do I know the id's. Thanks! -
In Django i can't populate a dropdown, it appears empty. Values are valid if i try to print them in the console
In Django I can't populate a dropdown. I have three dropdowns and they are all dependent. The first two dropdowns work fine, while the third dropdown doesn't work: it's empty with nothing inside. The first dropdown is called trip_selector and it correctly returns for example Spain. If I select Spain, then the second dropdown called trip it returns correctly Madrid-Bilbao, Seville-Barcelona. PROBLEM: The problem is the third dropdown called trip_selector in views.py. I wish that when I select in the second dropdown (called trips) for example Madrid-Barcelona then the third dropdown should be populated with Madrid and Barcelona. I tried to print x and y and print the Madrid and Barcelona values correctly, but I can't populate them in the dropdown. What am I doing wrong? Am I doing something wrong in views.py, something in the html page or something in HTMX? P.S: I know I could use options = [trip.team_home, trip.team_away] directly, but I need to create two separate variables like x and y seleziona_soggetto.html <select name="seleziona_soggetto" id="id_seleziona_soggetto" style="width:200px;" hx-get="{% url 'seleziona_soggetto' %}" hx-indicator=".htmx-indicator" hx-trigger="change" hx-swap="none"> <option value="">Please select</option> {% for i in options %} <option value="{{ i }}">{{ i }}</option> {% endfor %} </select> views.py #FIRST DROPDOWN (WORKS … -
django admin styles messed up after update to 4.2.4
I just updated from django 4.1.10 to 4.2.4 and the admin pages styles are messed up. The top of every page looks like this: I see many posts here and at https://forum.djangoproject.com/ about this same thing, and all the answers are to run collectstatic --clean and clear your browser cache. I have done both of these but no joy. I get the same in an incognito window. One interesting data point is that this issue does not occur using runserver only when using nginx/gunicorn. I have verified that all the static files that it's loading are being found. Anyone know how to fix this? -
Seeking guidance on integrating FCM and Firebase with Django 2.2 for Flutter app notifications
** I'm working on a project where I need to integrate Firebase Cloud Messaging (FCM) with Django 2.2 for sending push notifications to a Flutter app. However I am not familiar with Django 2.2 and the client has explicitly requested that we do not update their project at this time. I'm seeking guidance on how to achieve this integration while keeping the project on Django 2.2. I have the following questions:** Is it possible to integrate FCM and Firebase with Django 2.2 to send push notifications to a Flutter app? Are there any recommended libraries or packages that are compatible with Django 2.2 for FCM integration? Since I'm not familiar with Django REST Framework, can someone explain how to handle FCM requests and extract the FCM token in Django 2.2? It would be really helpful if you could provide some code examples or guidance. How can I generate the necessary notification code to activate notifications in the Flutter app without relying on Django REST Framework? Are there any recommended practices or methods for dynamically generating the code or payload using the FCM token within the context of Django 2.2? I haven't started the implementation yet, but I'm aware that websockets … -
python, django, validate username with ajax
I use ajax for authorization and I need to constantly check the username for validity. And also I have profile pages that look like "my_site/username" in the url. So I need to create a list of forbidden names like: "sign_in", "home" and so on. So I wanted to ask if there are any ready-made functions (possibly from external packages) that perform full validation of the user name (including maximum length, forbidden characters). -
Pipenv not cloning a repo from a branch correctly
I'm currently experiencing the following issue: When is being ran from docker-compose, Django fails to migrate due to unexistant migration which comes from a package installed from Github django-ai = {ref = "tradero", git = "https://github.com/math-a3k/django-ai.git"} When it succeeds installing, I get the following error when migrating: django.db.migrations.exceptions.NodeNotFoundError: Migration base.0001_initial dependencies reference nonexistent parent node ('supervised_learning', '0013_alter_oneclasssvc_nu') When checking the repo, that file exists in it, and when I inspect the container, I find the directory is empty: (tradero) [bot@femputadora tradero]$ docker exec -it tradero-instance-1 /bin/bash root@instance:/home/tradero# ls .venv/lib/python3.11/site-packages/django_ai/supervised_learning/migrations/ __init__.py __pycache__ root@instance:/home/tradero# ls .venv/lib/python3.11/site-packages/django_ai/ai_base/migrations/ 0001_initial.py 0002_learningtechnique_cift_is_enabled.py 0003_engineobjectmodel_default_metadata.py 0004_alter_learningtechnique_id.py 0005_alter_learningtechnique_learning_fields.py __init__.py __pycache__ I tried cleaning all the Docker cache, rebuilding, etc. without success and any clue about what may be the problem or how to fix it. This error was previously spotten on Github's CI, I thought it was due to outdated dependencies or because of random timeout errors you may get when installing with Pipenv, because the commit when the action begins to fail does not introduces any relevant changes from my POV, but the error is reproduced locally with Docker now, and I can't find any reason for that directory to be empty. Seems to be a problem with … -
I'm looking for free Python APIs for processing PDFs, images, videos, etc
I've created a web application using the Django framework, which is https://tool-images.com. It's a completely free application that processes PDFs, images, videos, and other utilities. I would like to know what interesting free APIs are available for Python that can be used for this type of file processing. Thank you very much. -
GDAL Library not downloading
Dockerfile has FROM python:3.8.1-slim-buster RUN apt-get update \ && apt-get install -y binutils libproj-dev gdal-bin python-gdal \ python3-gdal am trying to utilize the Postgis database "ENGINE": "django.contrib.gis.db.backends.postgis", however when I run the command docker-compose up --build -d --remove-orphans I get the failure code django.core.exceptions.ImproperlyConfigured: Could not find the GDAL library (tried "gdal", "GDAL", "gdal3.6.0", "gdal3.5.0", "gdal3.4.0", "gdal3.3.0", "gdal3.2.0", "gdal3.1.0", "gdal3.0.0", "gdal2.4.0", "gdal2.3.0", "gdal2.2.0"). Is GDAL installed? If it is, try setting GDAL_LIBRARY_PATH in your settings. What can I do to properly configure my GDAL library -
How to use a JavaScript variable as a variable in Django templating language?
I have the following code in a template ("home.html") in my Django project function deleteData(toBeDeleted) { $.ajax({ type: "GET", url: "{% url 'delete_data' **[Replace me]** 'all' %}", success: function (data) { alert(data) } }) } I need to reach the url 'delete_data' with 2 arguments where the 2nd argument is 'all' and the 1st argument is a javascript variable called "toBeDeleted" (Passed in as a function argument) A work around i have thought about is... url: `/delete_data/$(toBeDeleted)/all`, But in that case i will have to change that as well when changing the url for deleting data other than just changing the urls.py file Is there a way to make this work or do i have to give up on using {% url ... %}? -
Django TrigramSimilarity error for searches
I'm trying to use TrigramSimilarity for my django project to query it for search results but it's giving me an error like this: function similarity(text, unknown) does not exist LINE 1: ... COUNT(*) AS "__count" FROM "blog_blogpost" WHERE SIMILARITY... Here is my code query = request.GET['query'] if len(query) > 70: posts = BlogPost.objects.none() else: search = BlogPost.objects.annotate(similarity=TrigramSimilarity("body", query),).filter(similarity__gt=0.3).order_by("-similarity") paginate_search = Paginator(search, 12) page_search = request.GET.get("page") As it says that the function similarity is not defined. Is there a way to import similarity? As per my knowledge there are no such imports in django. -
Passing Data for Each User from one Django app to another?
In my Django application, users can log in using their username and password. Once logged in, the user makes a selection through a dropdown menu in an app.py created with dash-plotly. I want to retain this selection made by the user in memory and use it as an input for another app.py. I attempted to use an API, but it didn't provide a user-specific solution. Do you have any suggestions regarding this matter? Should I try using Models? I tried API and DjangoDashConsumer and I could not reach the solution. -
Why am I getting a NoneType for Allowed Host in Django-Environ when I set allowed host?
The settings code is import os import environ BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) env = environ.Env(DEBUG=(bool, False)) environ.Env.read_env(os.path.join(BASE_DIR, '.env')) the allowed host is written as ALLOWED_HOSTS = os.environ.get("ALLOWED_HOSTS").split(',') the .env file has ALLOWED_HOSTS as ALLOWED_HOSTS=localhost 127.0.0.1 [::1] why am I getting the fail code AttributeError: 'NoneType' object has no attribute 'split' when I run the command docker-compose up --build -d --remove-orphans -
Django - Fake Class representation in Django Admin
Sorry in advance for the complexity of my explanation. Assuming two classes ClassA and ClassB: class ClassA: # ... complexJoinKey=models.CharField(max_length=255) class ClassB: # ... complexJoinKey=models.CharField(max_length=255) The complexJointKey is a string handling complex values. It's in the shape: foo;a;*;b. There is an inclusion function (e.g. the previous example includes foo;a;bar;b), it's used to make some matches between ClassA and ClassB ; There should be a tree view ("foo", then "a", then "bar", then "b") to allow filtering which ClassA and ClassB share common filtering ; and every ClassA and ClassB has almost different complexJointKey ; I started by creating a simple foreign Key with a JointKey(Models.model) class, but this is bloaty in database: I get one object for each ClassX generated and I can't perform a nice filtering by tree.. Do you have a good implementation of this scheme? I thought about having a non-stored, virtual class with a ModelAdmin implementing the proper tree filtering, but following current Stakoverflow examples are to complex for my entry-level of Django. Thank you, -
Why i cant get the second components the other page with include
This is 'urunler.html' in my page {% extends "base.html" %} {% block site-title %} Ürünlerimiz {% endblock site-title %} {% block site-icerik %} {% include "./Components/_arts.html" %} {% endblock site-icerik %} include doesnt working. but in the index.html working {% extends "base.html" %} {% block site-title %} Anasayfa {% endblock site-title %} {% block site-icerik %} <!-- Swipper Slider --> <div class="container"> <div class="row justify-content-center"> <div class="col-md-6 mt-5"> {% include "./Components/_swipper.html" %} </div> </div> </div> <!-- Swipper Slider End --> <!-- Hakkımızda Section --> <section id="Hakkımızda"> <div class="container mt-5"> <div class="row justify-content-center"> <div class="col-md-5"> <hr> </div> <div class="col-md-2"> <p class="text-center mx-0 my-0 m-0">Yeni Çalışmalar</p> </div> <div class="col-md-5"> <hr> </div> </div> <!-- Yeni Çalışmalar Col ve Row Start --> {% include "./Components/_arts.html" %} <!-- Yeni Çalışmalar Col ve Row End --> </div> </section> <!-- Hakkımızda Section End --> {% endblock site-icerik %} why this components not working different pages ? also maybe want the see view.py from django.db.models import Q from django.shortcuts import render, redirect from .models import Tasarim, Hakkimizda # djangonun user modelini dahil et from django.contrib.auth.models import User from django.contrib.auth import authenticate, login, logout # Create your views here. def index(request): context = {} urunler = Tasarim.objects.all() context['urunler'] = … -
Excluding DJStripe Logs in Django
Im trying to exclude the djstripe logs from my django and prevent them being printed to the console. I have this config in my settings.py but when i perform Stripe operations I still see them on the console. LOGGING = { "version": 1, "disable_existing_loggers": False, "handlers": { "file": { "level": "DEBUG", "class": "logging.FileHandler", "filename": BASE_DIR / "web_debug.log", }, "console": { "level": "INFO", "class": "logging.StreamHandler", }, "djstripe_file": { # File handler specifically for djstripe "level": "DEBUG", "class": "logging.FileHandler", "filename": BASE_DIR / "djstripe.log", }, }, "loggers": { "djstripe": { # Logger specifically for djstripe "handlers": ["djstripe_file"], # Using the djstripe_file handler "level": "WARNING", "propagate": False, }, }, "root": { # Correctly defining the root logger outside the "loggers" dictionary "handlers": ["console"], "level": "INFO", }, } Any ideas? -
`dir()` doesn't show the cache object attributes in Django
I can use these cache methods set(), get(), touch(), incr(), decr(), incr_version(), decr_version(), delete(), delete_many(), clear() and close() as shown below: from django.core.cache import cache cache.set("first_name", "John") cache.set("last_name", "Smith") cache.set_many({"age": 36, "gender": "Male"}) cache.get("first_name") cache.get_or_set("last_name", "Doesn't exist") cache.get_many(["age", "gender"]) cache.touch("first_name", 60) cache.incr("age") cache.decr("age") cache.incr_version("first_name") cache.decr_version("last_name") cache.delete("first_name") cache.delete_many(["last_name", "age"]) cache.clear() cache.close() But, dir() doesn't show these cache methods as shown below: from django.core.cache import cache print(dir(cache)) # Here [ '__class__', '__contains__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattr__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_alias', '_connections' ] So, how can I show these cache methods? -
AppRegistryNotReady("Apps aren't loaded yet.")
I call a method clienting from another file in the admin.py @admin.register(Currency) class CurrencyAdmin(admin.ModelAdmin): list_display = ('name', 'symbol', 'position') change_list_template = "currency_changelist.html" def get_urls(self): urls = super().get_urls() my_urls = [path('getCurrency/', self.getCurrency), ] return my_urls + urls def getCurrency(self, request): clientWork = Process(target=clienting) clientWork.start() return HttpResponseRedirect("../") There are only 2 lines in this file, but if I add from screener.db_request import get_keys there, I get this error. What could be the problem? #from screener.db_request import get_keys def clienting(): print("Good") Error : Traceback (most recent call last): File "<string>", line 1, in <module> File "C:\Users\fr3st\AppData\Local\Programs\Python\Python311\Lib\multiprocessing\spawn.py", line 120, in spawn_main exitcode = _main(fd, parent_sentinel) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\fr3st\AppData\Local\Programs\Python\Python311\Lib\multiprocessing\spawn.py", line 130, in _main self = reduction.pickle.load(from_parent) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\fr3st\Desktop\Python\screener\clientWork.py", line 1, in <module> from screener.db_request import get_keys File "C:\Users\fr3st\Desktop\Python\screener\db_request.py", line 1, in <module> from .models import BinanceKey File "C:\Users\fr3st\Desktop\Python\screener\models.py", line 4, in <module> class BinanceKey(models.Model): File "C:\Users\fr3st\Desktop\Python\.venv\Lib\site-packages\django\db\models\base.py", line 127, in __new__ app_config = apps.get_containing_app_config(module) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\fr3st\Desktop\Python\.venv\Lib\site-packages\django\apps\registry.py", line 260, in get_containing_app_config self.check_apps_ready() File "C:\Users\fr3st\Desktop\Python\.venv\Lib\site-packages\django\apps\registry.py", line 138, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. -
Matching query does not existt
I have this error 'Product matching query does not exist.' , i didn't have this error until I deleted the categories and items from my db.sqlite3 , after i created new categories and items for each category the error occurred. enter image description here enter image description here Thank you for any help. -
Django master template doesn't display title block
I'm a bit of a noob regarding django framework. I started learning it today and I already have an issue with what I've done and I couldn't figure out why. I wanted to setup a master template, called master.html and use 2 other pages: all_members.html and details.html Here is the exact code: master.html <!DOCTYPE html> <html> <head> <title>{% block title %}{% endblock %}</title> </head> <body> {% block content %} {% endblock %} </body> </html> all_members.html {% extends "master.html" %} {% block title %} My Tennis Club - List of all members {% endblock %} {% block content %} <h1>Members</h1> <ul> {% for x in mymembers %} <li><a href="details/{{ x.id }}">{{ x.firstname }} {{ x.lastname }}</a></li> {% endfor %} </ul> {% endblock %} details.html {% extends "master.html" %} {% block title %} Details about {{ mymember.firstname }} {{ mymember.lastname }} {% endblock %} {% block content %} <h1>{{ mymember.firstname }} {{ mymember.lastname }}</h1> <p>Phone {{ mymember.phone }}</p> <p>Member since: {{ mymember.joined_date }}</p> <p>Back to <a href="/dev">Members</a></p> {% endblock %} Here is what the page looks like: To be sure, the title "My Tennis Club" should be displayed, right ? I can't figure out why it could not... Thank you for your … -
Optimising Django .count() function
Is there a way to optimise the .count() function on a queryset in Django? I have a large table, which I have indexed, however the count function is still incredibly slow. I am using the Django Rest Framework Datatables package, which uses the count function, so I have no way of avoiding using the function - I was hoping there would be a way to utilise the index for the count or something along those lines? Thanks for any help anyone can offer! -
download file from url in django
I want to download a file from a URL. Actually, I want to get the file from a URL and return it when the user requests to get that file for download. I am using this codes: def download(request): file = 'example.com/video.mp4'' name = 'file name' response = HttpResponse(file) response['Content-Disposition'] = f'attachment; filename={name}' return response but it cant return file for download. These codes return a file, but the file is not in the URL. how can I fix it? -
Handle file downloads in Flutter and InAppWebView?
I have a Django server with an endpoint to generate a PDF with some information entered by the user which returns a FileResponse (everything with a buffer, no file is created in the server, it is generated on demand), so the PDF is returned as attachment in the response. The endpoint is called in a HTML form submit button (in a Django template) and it works perfectly in all browsers. On the other hand, I did an app with Flutter (Android and iOS) using the InAppWebView library which opens my webpage. The problem comes when I try to download the PDF using the app. I have not found any way of handling the download file when it is returned as an attachment, for all methods I found I need the URL (which I can not call as I need the form information and the file is generated on demand). Summarizing: I have a Django server and a template with a basic form. On the form submit, it calls a python function that generates and returns a FileResponse with a PDF as an attachment and doesn't save any file in the server. On the other hand I have a Flutter WebView …