Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django does not recognize template_name
settings.py INSTALLED_APPS = [ ..., 'authentication_system_app', ] TEMPLATES = [ { ..., 'DIRS': ['authentication_system_app/templates/'], ..., }, ] authentication_system_app.urls from django.contrib.auth import views as auth_views path('account/reset-password/', auth_views.PasswordChangeView.as_view(template_name='reset_password.html'), name='reset_password'), I don't know why template_name is not working on my pet project, but when i watched video tutorial, it worked very well. I don't know why, can you guys help me. tysm! -
Django ForeignKey reverse relationship
I have 2 models, A parent and child model. I am trying to call the child model from the parent model class Parent(models.Model): name = models.CharField(...) class ChildClass(models.Model): name = models.CharField(...) parent = models.ForeignKey(Parent, on_delete=models.CASCADE, related_name=child_class) If i want to refer to the Parent class i know i can use child =ChildClass.objects.all then new.parent will give me parent name The problem comes when i want to call the child class through the ManyToOne relationship. I don't know how to build my queryset. I haven't tried anything cos i have never faced this problem and i couldn't find answer about it here -
Updated Django Application on aws ec2 and failed working
My aws ec2 substance with aws rds was working perfectly fine. Then I have made some changes to my django application by installing pymysql to make sure MySQLclient work and updates a upload function for my admin portal. I have checked everything using the local server, everything works fine. But when I git pull it through ssh ubuntu kernal. I could not access to my aws ec2 anymore, it says ERR_CONNECTION_REFUSED. What could be the potential problem? I tried accessing through local server and it works fine -
Railway requirements.txt installation failed
Hello everybody, I tried to deploy a django app on railway. So I've got the error below: ERROR: failed to solve: process "/bin/bash -ol pipefail -c python -m venv --copies /opt/venv && . /opt/venv/bin/activate && pip install -r requirements.txt" did not complete successfully: exit code: 1 The requirements file contains: aiofiles==22.1.0 aiosqlite==0.19.0 anyio==3.6.2 argon2-cffi==21.3.0 argon2-cffi-bindings==21.2.0 arrow==1.2.3 asgiref==3.7.2 asttokens==2.2.1 async-timeout==4.0.3 attrs==23.1.0 autobahn==23.6.2 Automat==22.10.0 Babel==2.12.1 backcall==0.2.0 backend==0.2.4.1 beautifulsoup4==4.12.2 bleach==6.0.0 Brotli==1.0.9 certifi==2022.12.7 cffi==1.15.1 channels==4.0.0 channels-redis==4.2.0 charset-normalizer==3.1.0 colorama==0.4.6 comm==0.1.3 comtypes==1.1.14 constantly==23.10.4 cryptography==41.0.7 cssselect2==0.7.0 daphne==4.0.0 debugpy==1.6.7 decorator==5.1.1 defusedxml==0.7.1 distlib==0.3.6 dj-database-url==1.0.0 Django==4.2 django-background-task==0.1.8 django-channels==0.7.0 django-ckeditor==6.5.1 django-crispy-forms==2.1 django-extensions==3.2.1 django-gunicorn==0.1.1 django-heroku==0.3.1 django-jazzmin==2.6.0 django-js-asset==2.0.0 django-renderpdf==4.0.0 Encoding==utf-8 executing==1.2.0 fastjsonschema==2.16.3 filelock==3.8.0 fonttools==4.39.3 fqdn==1.5.1 gunicorn==20.1.0 html5lib==1.1 hyperlink==21.0.0 idna==3.4 importlib-metadata==6.6.0 incremental==22.10.0 IPy==1.1 ipykernel==6.22.0 ipython==8.12.0 ipython-genutils==0.2.0 isoduration==20.11.0 jedi==0.18.2 Jinja2==3.1.2 json5==0.9.11 jsonpointer==2.3 jsonschema==4.17.3 jupyter-events==0.6.3 jupyter-ydoc==0.2.4 jupyter_client==8.2.0 jupyter_core==5.3.0 jupyter_server==2.5.0 jupyter_server_fileid==0.9.0 jupyter_server_terminals==0.4.4 jupyter_server_ydoc==0.8.0 jupyterlab==3.6.3 jupyterlab-pygments==0.2.2 jupyterlab_server==2.22.1 MarkupSafe==2.1.2 matplotlib-inline==0.1.6 mistune==2.0.5 MouseInfo==0.1.3 msgpack==1.0.7 nbclassic==0.5.5 nbclient==0.7.3 nbconvert==7.3.1 nbformat==5.8.0 nest-asyncio==1.5.6 notebook==6.5.4 notebook_shim==0.2.2 npm==0.1.1 numpy==1.26.2 oauthlib==3.2.2 opencv-python==4.8.1.78 optional-django==0.1.0 packaging==23.1 pandocfilters==1.5.0 parso==0.8.3 pickleshare==0.7.5 Pillow==9.4.0 platformdirs==2.5.2 prometheus-client==0.16.0 prompt-toolkit==3.0.38 psutil==5.9.5 psycopg2==2.9.4 pure-eval==0.2.2 pyasn1==0.5.1 pyasn1-modules==0.3.0 PyAutoGUI==0.9.54 pycparser==2.21 pydyf==0.6.0 PyGetWindow==0.0.9 Pygments==2.15.1 PyMsgBox==1.0.9 pyOpenSSL==23.3.0 pyperclip==1.8.2 pyphen==0.14.0 pypiwin32==223 PyRect==0.2.0 pyrsistent==0.19.3 PyScreeze==0.1.30 python-dateutil==2.8.2 python-decouple==3.6 python-json-logger==2.0.7 pyttsx3==2.88 pytweening==1.0.7 pytz==2022.7.1 pywin32==306 pywinpty==2.0.10 PyYAML==6.0 pyzmq==25.0.2 railway==0.0.4 redis==5.0.1 requests==2.28.2 requests-oauthlib==1.3.1 rfc3339-validator==0.1.4 rfc3986-validator==0.1.1 Send2Trash==1.8.0 service-identity==24.1.0 six==1.16.0 sniffio==1.3.0 soupsieve==2.4.1 sqlparse==0.4.3 stack-data==0.6.2 terminado==0.17.1 tinycss2==1.2.1 tomli==2.0.1 tornado==6.3.1 traitlets==5.9.0 … -
How can I execute an action after a model is created (.create & .bulk_create)
Is there a preferred way of executing an action after a model instance is created in the database? I know about signals. I know I can override the .save method. I know I can override the bulk one and atomically process each object in a transaction. Is there anything like signals which trigger on model instance creation whatever the way of creation (even on bulk)? Thanks! -
In Django get the localized date format string for date picker
In our django project we use a date picker with a specific date format like below: <script type="text/javascript"> $('#id_deliveryDate').datepicker({uiLibrary: 'bootstrap5', iconsLibrary: 'fontawesome', format: 'yyyy-mm-dd'}); </script> As our app uses localization we want to adapt the date format according to the language we use. This works for date fields - but not for the date picker - the date is displayed in the correct format but once you click on the date picker icon it is mangled. So the idea is to supply the correct date format according to the set language: Something like format: LOCALIZED_FORMAT Is this feasible? How can we achieve this? -
{% extends "" %} causing Django to ignore other code in file
I'm developing a website using the Django framework. I want to use one file (base.html) to establish a header and footer on every page. I have done this, but Django is now ignoring the code that's already in the other html files. This is the code for frontpage.html. I'm intending for the code below to use the code from both base.html and frontpage.html, but it's only using the code from base.html: {% extends "base.html" %} <!DOCTYPE html> <html> <head> </head> <body> <p>Example</p> <p>Example</p> <p>Example</p> <p>Example</p> </body> </html> -
null value in column "user_id" of relation "core_bedroomsummary" violates not-null constraint | DETAIL: Failing row contains (2, title, string, null)
I feel like this should be so easy to resolve but i cant seem to figure out why its not pulling the specific users uuid. The whole point is for the user to be able to have their own comments. views.py class BedroomSummaryViewSet(mixins.DestroyModelMixin, mixins.UpdateModelMixin, mixins.ListModelMixin, mixins.CreateModelMixin, viewsets.GenericViewSet): """Manage comments in the database.""" serializer_class = serializers.BedroomSummarySerializer queryset = BedroomSummary.objects.all() authentication_classes = [TokenAuthentication] permission_classes = [IsAuthenticated] def get_queryset(self): """Filter queryset to authenticated user.""" return self.queryset.filter(user=self.request.user).order_by('-title') serializers.py class BedroomSummarySerializer(serializers.ModelSerializer): """Serializer for interior summary.""" class Meta: model = BedroomSummary fields = ['id', 'title', 'comment'] read_only_field = ['id'] models.py class BedroomSummary(models.Model): """Bedroom Summary Model""" user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) title = models.CharField(max_length=55) comment = models.CharField(max_length=2000) -
Database schema for Student management system in Django
I Just want to ask if my way of creating database in Django for student management system is fine. I feel like there are some mistakes especcialy in Lesson. Schema: (https://i.stack.imgur.com/tYcth.png) I searched for some schema but i cannot find anything that can help me. Thanks for help. -
Django allauth custom social account provider doesn't activate
I've installed django allauth with social providers, and it works. Now I've created a custom social account provider based on Microsoft Graph, just creating a new app, added code from socialaccounts/providers/microsoft and changed adapter and provider classes names to my own, as well as the provider id. Now it shows on the login/signup pages but when I click on it to be redirected to microsoft's authentication page it doesn't work and goes back to login page, without errors. How to fix it to let my custom social account provider to be working? -
Error Broadcasting a Message Using Django-Channels in Elastic Beanstalk
Problem Description: I am attempting to create a websocket through a web application in an AWS environment (Beanstalk). The components involved are: Django Channels, Daphne, and Redis (Redis ElastiCache). We are using POSTMAN as a client (although we also use Python scripts), and this is our URL: wss://api.?????.com/ws/tunnel/group_test/. The client can connect to the socket without any issues and receives the welcome message. This is the consumer handler responsible for it: class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): try: self.room_name = self.scope['url_route']['kwargs']['comm_name'] self.room_group_name = f'chat_{self.room_name}' # Unirse a un grupo de chat await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() welcome_message_1 = f'Bienvenido al WebSocket 1. Tu canal es {self.channel_name}' await self.chat_message({'message': welcome_message_1}) As we mentioned, the client successfully connects, but when sending a message to an existing group (otherwise, it does not produce an error, which in itself is a clue), we receive the following error message from Daphne: 2024-01-16 03:46:40,053 No-IP daphne.server ERROR Exception inside application: unpack(b) received extra data. Traceback (most recent call last): (full log below) This is the consumer handler: async def receive(self, text_data): try: text_data_json = json.loads(text_data) message = text_data_json['message'] # Enviar mensaje al grupo de chat await self.channel_layer.group_send( self.room_group_name, { "type": "chat_message", "message": message } ) … -
ModuleNotFoundError: No module named 'webapp.urls'
I am working on a app using BeeWare (front-end python app framework) and Django. I'm using a cookie cutter template. My issue is with two files: settings.py and urls.py in the following repo structure. When I run python manage.py runserver inside the webapp dir, the server runs perfectly. But when I want to run the app development in the main app directory, named positron, I use briefcase dev. With this command, I get import errors that are fixed by changing the import statements in settings.py and urls.py from webapp.urls to webapp.webapp.urls and webapp.views to webapp.webapp.views respectively. I would like to not have to change these import statements based on whether I am developing my Django backend or my front end BeeWare code. What would standard practice be? Should I do a try statement or maybe some sort of custom package install? I'm not really sure what the most robust way to do it is. Thank you so much! repo structure -
Can't teardown django test database if async queries are used
I have a django project with postgres database configured. Here is the relevant part of requirements.txt: Django==5.0.1 psycopg2-binary==2.9.9 Here I have one model defined: class Item(models.Model): name = models.CharField(max_length=100) And a test case: class ItemTestCase(TestCase): def test_create(self): asyncio.run(Item.objects.acreate(name="Test")) self.assertEqual(Item.objects.count(), 1) Issue: When I'm running the tests using python manage.py test - tests are passed but at the end i see an exception that test runner can't destroy test database. 2024-01-18 19:05:03 django.db.utils.OperationalError: database "test_axpress" is being accessed by other users 2024-01-18 19:05:03 DETAIL: There is 1 other session using the database. Is there a way to ensure that all connections are closed before tearing down the database? -
How to disable a button with a certain value using jquery in Django
The json list contains the elements: [[45],[1]] Example of buttons with the "seat" class: <button class="seat" value="1"></button> ... <button class="seat" value="100"></button> When trying to run the code, it outputs an error: "Uncaught SyntaxError: Unexpected token '('". how to use jquery correctly in my case? I tried to do it like this. Code js: var pls = JSON.parse('{{ places_json|escapejs }}'); for(var el in pls){ $each.($('.seat'), function(){ if($(this).attr("value") == el){ $(this).prop("disabled",true); } }) } -
Determine languages per user in Django Admin using django-modeltranslation
I'm considering to use django-modeltranslation for my project. So far, seems very suitable. One question about it, I'd like to create a custom method to determine what languages should be displayed and editable in the Admin based on the logged in user. Simple example of the method below: def get_languages(user: User) -> list[str]: if user == Bert: return ['en'] elif user == Ernie: return ['en', 'nl'] return ['de'] Is this supported? -
Email test does not work in Django if django-allauth sends the email
I use the Django 5.0.1 with django-allauth. With real smtp email backend, email confirmation works. Django's email testing features are also working if django-allauth is not involved, like in the [example of the Django testing docs' email service][1]. As soon as I want to test the third party django-allauth confirmation email sending function, the mail.outbox does not have any item. My partial test code: class SignupProcessTest(TestCase): def setUp(self): # We setup base form data and we overwrite only test method specific ones self.data = {"email": "roland.szucs@booknwalk.com", "password1": "ajtoablak1", "newsletter": 1} def test_confirmEmailSent(self): self.client.post(reverse("account_signup"), self.data, secure=True, follow=True) # check email self.assertEqual(len(mail.outbox), 1, f"Email was not sent for confirmation:{len(mail.outbox)}") Based on the docs Django just replaces transparently the email backend settings and collects all emails to the mail.outbox array. Even Django-allauth should not be aware wich email backend serves its email sending request. When I try this in my local server, after signup I am redirected to another page and I get an email within seconds. Why does not it happen in test environment? Any idea? [1]: https://docs.djangoproject.com/en/5.0/topics/testing/tools/#email-services -
how to fix "TypeError: requires_system_checks must be a list or tuple." caused by "py manage.py grpcrunserver" command?
it's my first time aksing a question here so please take easy on me if I do it bad (or whatever) and help! Thanks. I have a project in which I need to use djangogrpcframework, and I've implemented the code but when I try to run the grpc server using "py manage.py grpcrunserver" I get the following error log: (.venv) D:\Programming-stuff\PythonProjects\notification>py manage.py grpcrunserver Traceback (most recent call last): File "D:\Programming-stuff\PythonProjects\notification\manage.py", line 22, in <module> main() File "D:\Programming-stuff\PythonProjects\notification\manage.py", line 18, in main execute_from_command_line(sys.argv) File "d:\Programming-stuff\PythonProjects\notification\.venv\Lib\site-packages\django\core\management\__init__.py", line 442, in execute_from_command_line utility.execute() File "d:\Programming-stuff\PythonProjects\notification\.venv\Lib\site-packages\django\core\management\__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "d:\Programming-stuff\PythonProjects\notification\.venv\Lib\site-packages\django\core\management\__init__.py", line 275, in fetch_command klass = load_command_class(app_name, subcommand) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "d:\Programming-stuff\PythonProjects\notification\.venv\Lib\site-packages\django\core\management\__init__.py", line 49, in load_command_class return module.Command() ^^^^^^^^^^^^^^^^ File "d:\Programming-stuff\PythonProjects\notification\.venv\Lib\site-packages\django\core\management\base.py", line 284, in __init__ raise TypeError("requires_system_checks must be a list or tuple.") TypeError: requires_system_checks must be a list or tuple. (versions:Python 3.12.0, Django 5.0.1, djangogrpcframework 0.2.1, grpcio-tools 1.60.0, grpcio 1.60.0) I've already tried to update django-extensions, but didn't resolve the issue. I also tried to use alternative ways like using "py services.py" to run my grpc server directly but it came up with troubles as well (like not loading apps, and it's not the only one for sure!). any help will … -
Making a field both foreign and primary key in Django
I have a database and in one of the tables, a field should both be a primary and a foreign key. I am new to Django, and I couldn't find an example implementation. I appreciate all the help, Didem I tried looking the documentation or some example repos but didn't see anything -
How to compare integer type and string type variable in Django using if template tag
I am trying to compare two variables using if template tag. If condition is not working as stock.id is integer and form.product_in_stock.value is string. {% if form.product_in_stock.value == stock.id %}selected{% endif %} Is there any way to type cast and then compare using if in django template. -
Django-Ninja CSRF Token & OpenAPI
I am using Django-Ninja and want to use authentication in it. Here is my authentication process : from ninja_extra import NinjaExtraAPI from ninja.security import django_auth api = NinjaExtraAPI(csrf=True) # AUTHENTICATION #////////////////////////////////////////////////////////////////////////////// @api.post("/login") def login_user(request, username: str, password: str): # Authentification de l'utilisateur user = authenticate(request, username=username, password=password) if user is not None: # Connexion de l'utilisateur login(request, user) return {"message": "Login successful"} else: return {"message": "Login failed"} @api.post("/logout", auth=django_auth) def logout_user(request): # Déconnexion de l'utilisateur logout(request) return {"message": "Logout successful"} #////////////////////////////////////////////////////////////////////////////// When I go to http://127.0.0.1:8000/api/docs, I can try the login route and it works. And the other hand, the logout route fails with a CSRF verification failed. Request aborted.. I then tried to look closer to the queries and here is what I found : 1. GET http://127.0.0.1:8000/api/docs ------------------------------------------------------------------- HTTP/1.1 200 OK Date: Thu, 18 Jan 2024 13:16:07 GMT Server: WSGIServer/0.2 CPython/3.10.9 Content-Type: text/html; charset=utf-8 X-Frame-Options: DENY Vary: Cookie Content-Length: 974 X-Content-Type-Options: nosniff Referrer-Policy: same-origin Cross-Origin-Opener-Policy: same-origin Set-Cookie: csrftoken=ZMn7RxrJl3fdnrMHGKNmlgB0GiB0Eyeq; expires=Thu, 16 Jan 2025 13:16:07 GMT; Max-Age=31449600; Path=/; SameSite=Lax <!DOCTYPE html> <html> <head> <link type="text/css" rel="stylesheet" href="https://cdn.jsdelivr.net/npm/swagger-ui-dist@4.15.5/swagger-ui.css"> <link rel="shortcut icon" href="https://django-ninja.rest-framework.com/img/favicon.png"> <title>NinjaExtraAPI</title> </head> <body> <div id="swagger-ui"> </div> <script src="https://cdn.jsdelivr.net/npm/swagger-ui-dist@4.15.5/swagger-ui-bundle.js"></script> <script> const ui = SwaggerUIBundle({ url: '/api/openapi.json', dom_id: '#swagger-ui', presets: [ … -
AttributeError: 'ManyRelatedManager' object has no attribute 'title'
I was trying to make some tests in an API Django with pytest, but find this error: Attribute error image Here's the code's test that failed: import pytest from core.orders.factories import * @pytest.fixture def order_created(): user1 = UserFactory(username='Lucas') category = CategoryFactory(title='teste') product1 = ProductFactory(title='teste_product') return OrderFactory(customer=user1) @pytest.mark.django_db def test_order_customer_name(order_created): assert order_created.customer.username == 'Lucas' @pytest.mark.django_db def test_order_product_name(order_created): assert order_created.product.title == 'teste_product' Searching into web I found this error is related to method ManyToManyField() from models. If helps, I'll also put my model's code here: from django.db import models from django.db import models from django.contrib.auth.models import User class Category(models.Model): title = models.CharField(max_length=200) slug = models.SlugField(unique=True) description = models.TextField(max_length=200, blank=True, null=True) active = models.BooleanField(default=True) def __str__(self): return self.title class Product(models.Model): title = models.CharField(max_length=200) description = models.TextField(max_length=500, blank=True, null=True) price = models.PositiveIntegerField(null=True) active = models.BooleanField(default=True) category = models.ManyToManyField(Category, blank=True) def __str__(self): return self.title class Order(models.Model): product = models.ManyToManyField(Product, blank=False) customer = models.ForeignKey(User, on_delete=models.CASCADE, null=False) def __str__(self): return self.customer.name I try to remove the lines of category1 and product1 delcaration from test code, but I really need find a way to verify the instances of a Order in terms of Product (that needs a category) and Customer(no problem whit that since I was trying to … -
Getting warnings while using django in vscode wsl
I'm using django in vscode in wsl. I'm getting continously warnings in importing packages like from django.contrib import admin, from django.db import models etc. I tried to import python extension and set interpreter to version 3.10.12 -
Architecture of basket in django
I want to create several baskets for ordering items. When i click on "add button" on item's page, i want it was added to my last basket. Baskets amount are several. I don't want select "basket" each time, when i want to add. I want it was selected and changed once somewhere (other page). How should it work? I click basket#1 and then i go add items to this basket. Then i go to basket#2 and add. And i cannot make a selection from the list. I need adding from the page of item. I'm a bit stuck in architecture. Please help. -
Celery ignores Django settings
I'm using Celery for managing async tasks in Django. I set up it using the official instruction. However, when I output app.conf on my worker instance - it outputs default settings. celery.py: os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myapp.settings") app = Celery("myapp") app.config_from_object("django.conf:settings", namespace="CELERY") @setup_logging.connect def config_loggers(*args: Any, **kwags: Any) -> None: from logging.config import dictConfig from django.conf import settings dictConfig(settings.LOGGING) app.autodiscover_tasks() @celery_bound_logged_task def debug_task(self: Any) -> None: logger = logging.getLogger(__name__) logger.debug(f"Heartbeat: {self.request.id}") logger.debug("Config: %s", app.conf) <------- Here I get default config, with broker_heartbeat: 120 and etc. settings.py # Celery # From https://www.cloudamqp.com/docs/celery.html CELERY_BROKER_URL = RABBITMQ_URL CELERY_BROKER_POOL_LIMIT = 1 CELERY_BROKER_HEARTBEAT = None CELERY_BROKER_CONNECTION_TIMEOUT = 30 CELERY_RESULT_BACKEND = None CELERY_EVENT_QUEUE_EXPIRES = 60 CELERY_WORKER_PREFETCH_MULTIPLIER = 1 CELERY_WORKER_CONCURRENCY = 1 # Never give up set up CELERY_TASK_ACKS_LATE = True CELERY_TASK_TIME_LIMIT = 30 * 60 # 30 minutes CELERY_TASK_REJECT_ON_WORKER_LOST = False CELERY_TASK_ACKS_ON_FAILURE_OR_TIMEOUT = False -
Slicing an unevaluated Django Queryset, has different results if not ordered
I'm trying to handle in memory data with slicing a unevaluated queryset 500 at a time and then processing it accordingly. What I can't seem to understand is that if I don't apply an order_by to my queryset filter queryset.objects.filter(id_in=[something]) the slicing will not give me all the rows but sometimes repeated rows compared to when I order the queryset queryset.objects.filter(id_in=[something]).order_by("id").