Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I display a PDF file from a REST API in a PDF format in a React interface?
I am fetching a PDF file from a REST API using Axios and displaying it in a React interface with FileViewer. However, the content of the PDF file is displayed directly. How can I make it open the PDF file externally when clicking a button? -
Can anyone suggest me a tool to convert HTML to PDF in Python?
I'm seeking a reliable method to convert HTML to PDF. Although I've experimented with tools like pdfkit and wkhtmltopdf, I've encountered an issue with inconsistent styling. As more data is added, the styling becomes disrupted. Therefore, I am in need of a comprehensive solution that ensures consistent styling throughout and can automatically adjust if additional data is introduced. Tech stack I am using - Python, Django Here is a link for the sample PDF generated by pdfkit. The footer is appropriate and if the address is too big to the product is too big the issue starts popping Link - https://shorturl.at/sxL06 -
TypeError: ForeignKey.__init__() got multiple values for argument 'on_delete'
I am trying to define a foreign_key in a model in Django. But I am getting the error "TypeError: ForeignKey.init() got multiple values for argument 'on_delete'" The way I define the field is like this: class School(BaseModel): student_number = models.ForeignKey(Student,_("student_number"), max_length=200,on_delete=models.CASCADE) I don't really see why I am getting this error, because I have exact same implementation in other classes, and they do not raise an error. -
django - display the units of the selected item
Items model has units which is foreign to Units model. Now when we select the item in stock form, how to display the units of the selected item? models.py: class Units(models.Model): name = models.CharField(max_length=255, unique=True) class Items(models.Model): name = models.CharField(max_length=255, unique=True) units = models.ForeignKey(Units, on_delete=models.CASCADE, null=True, blank=True, related_name='units_items') class Stock(models.Model): item = models.ForeignKey(Items, on_delete=models.CASCADE, null=False, blank=False, related_name='item_stock') - - - - - - - - - - - - - - - - - - - - - - - - - - - - forms.py: class StockForm(forms.ModelForm): class Meta: model = Stock fields = ['item'] template: <div class="col-md-4 pl-0"> {{ formsingle.item|as_crispy_field }} </div> <div class="col-md-1 p-0"> <span></span> //here how to show related units when any item is selected </div> -
Django: Unknown command: 'collectstatic' when using call_command
I have a Django project with "django.contrib.staticfiles" in INSTALLED_APPS. Therefore, I can run ./manage.py collectstatic. But I need to use call_command. Running python -c 'from django.core.management import call_command; call_command("collectstatic")' results in django.core.management.base.CommandError: Unknown command: 'collectstatic' What am I doing wrong? Shouldn't the 2 commands be absolutely identical? Obviously, environments, paths, etc are correct in both cases. I am running both commands from the same shell in a docker container. -
Passing user's local timezone to celery in django app
I have a requirement where i want to show date time in user's local datetime. For which I have added a middleware code in django which gets the local date time from user's session through browser and activate that session. In my django settings.py I have added the timezone which is by default 'America/New york' Now I have celery where the database operations are performed asynchronously. But in celery the timezone which I am activating in middleware is not getting through. It is always picking it up from django settings.py file. If i remove the default timezone setting then it is taking the timezone as 'America/Chicago'. Below is my code for Middleware # middleware.py from django.utils import timezone class TimezoneMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): user_timezone = request.GET.get('user_timezone', 'America/New_York') request.session['user_timezone'] = user_timezone response = self.get_response(request) return response And here is my code for celery task # tasks.py from celery import Celery, Task from django.contrib.sessions.models import Session from django.utils import timezone app = Celery('yourapp', broker='pyamqp://guest@localhost//') class TimezoneAwareTask(Task): def __call__(self, *args, **kwargs): # Get user timezone from session or use a default user_timezone = self.get_user_timezone(kwargs.get('session_key')) # Set the timezone for the task execution timezone.activate(user_timezone) try: result = super(TimezoneAwareTask, … -
im working on a django project as a total beginner . block content end block is not working and the browser renders raw code
here is my directoryworkspace base.html : frontpage.html : output im getting :enter image description here i tryed removing spaces within block tags ..but nothing works , the raw django code is displayed in the browser. what am i missing? . can someone please help me with this. -
DRF If there is a way how to save a fieldset in serializer?
I encountered a problem when trying to save fieldset data in the serializer. serializer.py class MyModelSerializer(serializers.ModelSerializer): class Meta: model = MyModel fields = ( 'field_1', 'field_2', ) views.py class MyAPIView(generics.GenericAPIView): def post(self, request, *args, **kwargs): my_serializer = MyModelSerializer(data=request.data, many=True) # return [] One solution is to use many=True. However, the issue is that the serializer requires data in the format of data={'field_name': 'value', ...}, while request.data returns 'field_1': ['value_1', 'value_2']. Is there a way to work with fieldsets via serializer? -
python dango excel file open webserver
enter image description hereenter image description hereenter image description hereenter image description here 제가 파이썬 django로 작성한 파일인데 runserver하면 글자는 나오는데 csv로 된 엑셀파일이 띄우기가 안돼네요ㅜㅜ 왜 그런것일까요? 혹시 제 생각에는 view파일에 csv define이 구체적으로 정의가 안내려 그런것인가요? 근데 인터넷과 gtp 활용해보니 csvTomain함수로 엑셀 불러오기가 가능하다고 저는 그렇게 이해 하고 있습니다. -
In Django, where does the "data" field come from in the Serializer class?
I see in a bunch of django code, especially in viewsets, that when serializer is initialized like the following: class UserViewSet(viewsets.ModelViewSet): """ A viewset that provides the standard actions """ queryset = User.objects.all() serializer_class = UserSerializer @action(detail=True, methods=['post']) def set_password(self, request, pk=None): user = self.get_object() **serializer = PasswordSerializer(data=request.data)** the data argument is always being passed in the instantiation of a Serializer instance. But I feel like I have been researching django documentation everywhere and I can't seem to find a reference to this data argument. I really want to know what exactly is data doing here, where does it come from, why is information about it so hidden? I tried researching the official django rest framework documentation, as well as scoured several Medium articles to no avail. -
Javascript function not loading in Django template
I have a HTML tag that is supposed to run a function in my javascript file (app.js) when it gets clicked (this is implemented using the onclick tag property) but instead I get the following error: Uncaught ReferenceError: summon_chat is not defined at HTMLLIElement.onclick But when in my javascript file I code something like this: const list-item = document.querySelector('#listId') list-item.onclick = function () { my_function()} Then the onclick event works, what am I doing wrong? My base.html file is located at templates/layouts/ and my index.html is located at templates/ This is my index.html fragment that calls the function: <li onclick="console.log('CLICKED'); summon_chat(this);" class="list-group-item p-3"> This is my base.html: {% load static %} <!DOCTYPE html> <html lang="en" data-bs-theme="light"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>{% block title %}{% endblock title %}</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous"> <link rel="stylesheet" href="{% static 'styles.css' %}"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL" crossorigin="anonymous"></script> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css"> <script src="https://unpkg.com/htmx.org@1.9.10" integrity="sha384-D1Kt99CQMDuVetoL1lrYwg5t+9QdHe7NLX/SoJYkXDFfX37iInKRy5xLSi8nO7UC" crossorigin="anonymous"></script> <script src="{% static 'app.js' %}" type="module"></script> {% block script %}{% endblock script %} </head> <body> <div class="container-fluid"> <main>{% block content %}{% endblock content %}</main> </div> </body> </html> I already checked the dev console in my browser and the javascript file is loading correctly, I even added a console.log … -
Django - Redis Sessions not being recognized by downstream microservices from user_service
I am writing a Django framework based on Django Rest Framework with Redis enabled for authenticated sessions. That way my downstream micro-sevices can use the same session / cookie information and jwt token from the user_service. Basically i'm trying to have a single microservice that controls user authentication with jwt tokens so my react app can authenticate against the user service and use the token/ session for all downstream services. I have three services: user_service - contains all the user information and sets the authenticated session friend_service - uses user_service session and jwt for authentication tracking_service - uses user_service session and jwt token for authentication The Problem: The downstream services even via the Django Rest Framework UI the session isn't shared. What I've Discovered: Redis has the session token: :1:django.contrib.sessions.cached3bq2jfv2r88hcdqezlfmgng1hbyauzf The web browser cookie for webapp is set to: 3bq2jfv2r88hcdqezlfmgng1hbyauzf The settings files, and Django secret key are identical between the services This was working originally with just one downstream microservice but when I added the second microservice tracking_service it stopped working for all microservices. Everything I've read says you just have to make sure the cache setup is correct. Which I've done redis is getting the information but the … -
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?