Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
error: PermissionError(13, 'Access is denied', None, 5, None)
I have this error while working with celery [2024-10-06 14:38:15,464: ERROR/SpawnPoolWorker-3] Pool process <billiard.pool.Worker object at 0x0000016C0BBF5A00> error: PermissionError(13, 'Access is denied', None, 5, None) Traceback (most recent call last): File "D:\study\learning-python\back-end\ecommerce\venv\Lib\site-packages\billiard\pool.py", line 473, in receive ready, req = _receive(1.0) ^^^^^^^^^^^^^ File "D:\study\learning-python\back-end\ecommerce\venv\Lib\site-packages\billiard\pool.py", line 445, in _recv return True, loads(get_payload()) ^^^^^^^^^^^^^ File "D:\study\learning-python\back-end\ecommerce\venv\Lib\site-packages\billiard\queues.py", line 394, in get_payload with self._rlock: File "D:\study\learning-python\back-end\ecommerce\venv\Lib\site-packages\billiard\synchronize.py", line 115, in __enter__ return self._semlock.__enter__() ^^^^^^^^^^^^^^^^^^^^^^^^^ PermissionError: [WinError 5] Access is denied During handling of the above exception, another exception occurred: Traceback (most recent call last): File "D:\study\learning-python\back-end\ecommerce\venv\Lib\site-packages\billiard\pool.py", line 351, in workloop req = wait_for_job() ^^^^^^^^^^^^^^ File "D:\study\learning-python\back-end\ecommerce\venv\Lib\site-packages\billiard\pool.py", line 480, in receive raise SystemExit(EX_FAILURE) SystemExit: 1 During handling of the above exception, another exception occurred: Traceback (most recent call last): File "D:\study\learning-python\back-end\ecommerce\venv\Lib\site-packages\billiard\pool.py", line 292, in __call__ sys.exit(self.workloop(pid=pid)) ^^^^^^^^^^^^^^^^^^^^^^ File "D:\study\learning-python\back-end\ecommerce\venv\Lib\site-packages\billiard\pool.py", line 396, in workloop self._ensure_messages_consumed(completed=completed) File "D:\study\learning-python\back-end\ecommerce\venv\Lib\site-packages\billiard\pool.py", line 406, in _ensure_messages_consumed if self.on_ready_counter.value >= completed: ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<string>", line 3, in getvalue PermissionError: [WinError 5] Access is denied [2024-10-06 14:38:15,464: ERROR/SpawnPoolWorker-3] Pool process <billiard.pool.Worker object at 0x0000016C0BBF5A00> error: PermissionError(13, 'Access is denied', None, 5, None) Traceback (most recent call last): File "D:\study\learning-python\back-end\ecommerce\venv\Lib\site-packages\billiard\pool.py", line 473, in receive ready, req = _receive(1.0) ^^^^^^^^^^^^^ File "D:\study\learning-python\back-end\ecommerce\venv\Lib\site-packages\billiard\pool.py", line 445, in _recv return … -
How are emails set up for employees in an organization?
I'm pretty new to the SMTP aspect... I have been trying to understand how setting up an email account for each user (employee) in an enterprise application works. For example, let's say I am using Brevo (SendinBlue) as my SMTP service and I want to create for each lecturer that I have in my application, say john.smith@havard.org Do I create another sender on Brevo for each of the accounts I want to create and would the user be able to login to his email and view emails sent to him? And I would be able to send a dynamic email from my backend using from his email Just, how does it work? -
CommandError: Unknown command:
I created a custom command and want to run it automatically on start My command file # project/parser_app/management/commands/create_schedules.py class Command(loaddata.Command): def handle(self, *args, **options): # some code Added command to wsgi.py import os from django.core.wsgi import get_wsgi_application from django.core.management import call_command os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core_app.settings') application = get_wsgi_application() call_command("makemigrations") call_command("migrate") call_command("collectstatic", interactive=False) call_command("create_schedules parser_app/management/commands/schedule_fixtures.json") I can run in console command python manage.py "create_schedules parser_app/management/commands/schedule_fixtures.json" and everything is working but when I added command to wsgi.py (to run on start) import os from django.core.wsgi import get_wsgi_application from django.core.management import call_command os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core_app.settings') application = get_wsgi_application() call_command("makemigrations") call_command("migrate") call_command("collectstatic", interactive=False) call_command("create_schedules parser_app/management/commands/schedule_fixtures.json") I have an error raise CommandError("Unknown command: %r" % command_name) django_1 | django.core.management.base.CommandError: Unknown command: 'create_schedules parser_app/management/commands/schedule_fixtures.json' -
In Django, how to retrieve an id to use in a dynamic link?
I have a Django app. In my sidebar I have a navigation link that goes to a list of reports. That link needs an id to get the correct list of reports. The <li> element in base.html that links to the ga_reports page is below. This link needs the app_config.id to resolve correctly. With this element {{ app_config.id }} does not exist because {{ app_config }} does not exist. I will add that on the Reports page, this link works as {{ app_config }} gets created. Why does {{ app_config }} exist on the Reports page but not on the parent page? <li class="relative px-12 py-3"> <a class="inline-flex items-center w-full text-sm font-semibold transition-colors duration-150 hover:text-gray-800 dark:hover:text-gray-200 " href="/base/ga_reports/{{ app_config.id }}"> <span class="ml-4">Reports</span> </a> </li> These are entries from base/urls.py path('app_config', app_config_views.app_config, name='app_config'), ... path('ga_reports/<int:app_config_id>', ga_views.ga_reports, name='ga_reports'), The AppConfiguration model is included on base/views.py from .models import AppConfiguration This is base/ga_views.py @login_required def ga_reports(request, app_config_id): app_config = AppConfiguration.objects.filter(id = app_config_id).first() if not app_config: messages.error(request, "Invalid Configuration") return redirect('app_config') return render(request, 'base/ga_reports.html', {'app_config': app_config}) This is app_config_views.py. @login_required def app_config(request): app_configs = [] for app_type in APP_TYPE: app_type_subscription = UserSubscription.objects.filter(user_id = request.user.id, app_type = app_type[0], is_active = True, is_expired = False).first() app_configuration … -
What is the best way to sanitize uploaded filenames in Django?
I tried using slugify however it made too many changes to the original filename, such as removing spaces joining the file extension to the rest of the name. I'd like to simply ensure that names are safe: 1. Not too long and 2. Prevent any attacks that can be carried out using the file's name(such as path traversal). My app allows users to upload files(files are uploaded to DigitalOcean Spaces via my app) and filenames are stored using models.py/ -
How to get the estimated remaining time of an already started Celery task?
I am using django with Celery and redis. I would like that when a user initiates a Celery task my app estimates the amount of time left until the task is completed(so that I can, for example, represent this data to the frontend as a progress bar). For example, given this polling function: views.py: @csrf_protect def initiate_task(request): task = new_celery_task.delay(parmeter_1, parametr_2) @csrf_protect def poll_task_status(request, task_id): #task_id provided by frontend import base64 task_result = AsyncResult(task_id) if task_result.ready(): try: ... response_data = { 'status': 'completed', } except Task.DoesNotExist: return JsonResponse({'status': 'error', 'message': 'There has been an error'}, status=404) elif task_result.state == 'REVOKED': return JsonResponse({'status': 'terminated', 'message': 'Task was terminated'}) else: #add code to calculate estimated remaining time here remaining_time_est = estimate_remaining_time() #estimate task by id return JsonResponse({'status': 'pending' #add code to return estimated remaining time here 'est_remaining_time':remaining_time_est }) and task: task.py: app = Celery('myapp')# @app.task def new_celery_task(arg_1, arg_2): #complete task How would I estimate the remaining time left on an initiated task? -
My django project shows no error in terminal using vs code it got right request but on browser it not showing what i expected the output, not updated
I am facing some problem in VS code in django project. After saving the code in vs code, even after running the server in the terminal, I am not getting the output of the code in the browser normally. pylance - does not show any errors. The update of get request in terminal comes every time after running server but still doesn't show data in browser. Despite not giving pylance error, I check the code 5-6 times by myself. There is no error. I have not installed pylint as I am still in medium level pylint asks to follow the actual code structure of pep8 which is a bit tough now so I did not install it, still why is this happening. Tried a simple project for 2 hours yesterday and couldn't figure out the error, I was sure the code was fine. Running the same project this morning, everything is running fine. I am reading the same problem again today. Even after browser reload/hard reload, browser change, even port number change, the same problem is happening again and again. I want a solution, can someone tell me where the problem is? Point to be noted, the terminal shows no … -
Best approach for showing custom data in the Volt template dashboard for Django
I am currently building a personal app and would like to use the Volt template for Django. The link to the template is here: https://tb-volt-dashboard-django.appseed-srv1.com/dashboard.html I want to update the chart in the dashboard to use custom generated data from the view. What's the best approach/ recommended approach to do that? I see currently that the data is being hard-coded in the volt.js file in the Volt directories. -
How to Separate Django Channels WebSockets into a Scalable Microservice for a Multiplayer Game?
I have a Django web application that includes a multiplayer game feature, using Django Channels for real-time communication over WebSockets. Currently, the WebSockets functionality (real-time game updates, player interactions, etc.) is handled directly within the main Django application. As the project grows, I'm considering separating the WebSockets/game logic into its own microservice for scalability and maintainability. My goals are to have a dedicated microservice that handles all real-time communication and game logic, and to be able to scale this service independently of the main Django web app. Here are the specific details of my setup: Backend Framework: Django (with Django Channels for WebSockets) Current Architecture: Monolithic Django app with WebSockets handled directly in the same codebase - as the rest of the application Desired Architecture: Separate microservice dedicated to handling WebSocket connections and game logic, which can be scaled independently Questions: What are the best practices for separating WebSocket real-time communication into a dedicated microservice? What tools or technologies can be useful for building this scalable WebSocket-based microservice? I'd like not to use another django services but something lighter How should communication between the main Django app and the WebSocket microservice be handled (e.g., API, message queues, etc.)? How should … -
Django (DRF): How can I apply authentication on this class-based view?
In my Django project I have two User Groups: Manager Employee Now I'm trying to build a class-based view that returns all managers. However, it's only supposed to be accessible to managers. If an employee or an anonymous user attempts to access it, it's supposed to return a 403-HTTP-Status code. I've built the class-based view so far and for simplicity it extends generics.ListAPIView. But I can't find a way to apply the desired authentication. I have removed the "Can view group" and "Can view user" permissions from the Employee group, so no employee can view the managers. I've tried several permission_classes, but everytime I sent a GET-request containing an employee's token via Insomnia, it returned the managers instead of a 403-Status code. Help is greatly appreciated. Here's the code of the view: class ViewManager(generics.ListAPIView): permission_classes = [DjangoModelPermissions] group = Group.objects.get(name='Manager') users = group.user_set.all() queryset = users serializer_class = ManagerSerializer -
Celery polling Redis every second
I have a Django application with two celery tasks set up. Both the tasks need to run only once at one minute after midnight (12:01 AM). This is just to update some statuses which change from "ACTIVE" to "INACTIVE" at 12:01 AM. My goal is to reduce the number of times Celery polls Redis. Currently, it polls every second which is problematic. I took two steps I tried to change the settings in Django for Celery inlcuding using paramters such as CELERY_IGNORE_RESULT, CELERY_WORKER_CONCURRENCY, CELERY_BROKER_HEARTBEAT and lastly CELERY_BEAT_MAX_LOOP_INTERVAL CELERY_RESULT_BACKEND = None CELERY_IGNORE_RESULT = True # Ignore task results to reduce Redis usage CELERY_ACCEPT_CONTENT = ["json"] CELERY_TASK_SERIALIZER = "json" CELERYD_PREFETCH_MULTIPLIER = 1 # Fetch only 1 task at a time CELERY_ACKS_LATE = True # Acknowledge tasks after completion to avoid re-execution on failure # Celery transport options CELERY_BROKER_TRANSPORT_OPTIONS = { 'ssl': { 'ssl_cert_reqs': ssl.CERT_NONE # Suggestion: CERT_REQUIRED for stronger security }, 'visibility_timeout': 3600, # Timeout for long-running tasks 'polling_interval': 30 # Poll every 30 seconds } CELERY_RESULT_BACKEND_TRANSPORT_OPTIONS = { 'ssl': { 'ssl_cert_reqs': ssl.CERT_NONE # Same as broker for consistency } } # Reduce the number of threads/processes CELERY_WORKER_CONCURRENCY = 1 # Disable sending task events CELERY_WORKER_SEND_TASK_EVENTS = False # Disable remote control … -
In my browser console window.crossOriginIsolated is false despite of adding all proper COOP COEP CORP headers in my React Js and Django app
when i access cmd to express-> node server.js with coop and coep and corp headers and access directly the locahost:8080/ everything is working fine and even window.crossOriginIsolated is true. but when i integrate it to my existing react js and django and i add custom middleware.py for coop and coep. but still no use... even the pages of any of my reactjs and django itself is not showing window.crossOriginIsolated true despite of adding all required headers. kindly help me. i dont have any cors error at all my app works fine with api's transaction between react js and django working fine. this is custom middleware for cors `from django.http import HttpResponse class CrossOriginIsolationMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): # Handle OPTIONS preflight request (for CORS) if request.method == 'OPTIONS': response = HttpResponse() response['Access-Control-Allow-Origin'] = 'http://localhost:3000' # Specify the frontend origin response['Access-Control-Allow-Credentials'] = 'true' response['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept, Authorization' response['Access-Control-Allow-Methods'] = 'GET, POST, OPTIONS, PUT, DELETE' return response response = self.get_response(request) response['Access-Control-Allow-Origin'] = 'http://localhost:3000' response['Access-Control-Allow-Credentials'] = 'true' response['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept, Authorization' response['Access-Control-Allow-Methods'] = 'GET, POST, OPTIONS, PUT, DELETE' if request.path.startswith('/dicomweb/'): response['Cross-Origin-Opener-Policy'] = 'same-origin' response['Cross-Origin-Embedder-Policy'] = 'require-corp' response['Cross-Origin-Resource-Policy'] = 'cross-origin' # Changed to … -
Django forms.py and Join.html not rendering form errors
I have seen many tutorials on this, (I am new to Django) and the only issue I could find was raise form.Validation("...") was not rendering on my HTML template and did not stop the form from submitting. I tried many options including AI yet I was still running into the same problems. If I have made a silly mistake please point it out so I know for next time, this code is just a project of mine so I can learn how to code Django. HTML: <form id="form" action="" method="post" name="form"> {% csrf_token %} <div class="input-control"> {% if form.non_field_errors %} <div class="error">{{ form.non_field_errors }}</div> {% endif %} {% if form.errors %} <div class="error">{{ form.errors }}</div> {% endif %} <div class="username"> <label for="{{ form.username.id_for_label }}" class="label">{{ form.username.label }}</label> {{ form.username }} <!-- Render the input field --> {% for error in form.username.errors %} <div class="error">{{ error }}</div> {% endfor %} </div> <div class="email"> <label for="{{ form.email.id_for_label }}" class="lemail">{{ form.email.label }}</label> {{ form.email }} {% for error in form.email.errors %} <div class="error">{{ error }}</div> {% endfor %} </div> <div class="password"> <label for="{{ form.password.id_for_label }}" class="label">{{ form.password.label }}</label> {{ form.password }} {% for error in form.password.errors %} <div class="error">{{ error }}</div> {% endfor … -
How Can I Setup Celery in my Flask Project (Beginner)
So I've been working on a project for a couple months now and I've been trying to implement Celery into my flask project and it has not gone well. I thought maybe it's my computer or windows or something like, and all the responses I've seen are from a couple years ago and I don't think that they would still work because those were the ones I tried using. So thank you for any responses in advance. I tried using the celery config from the documentation and some chat gpt tutorials but they haven't been of help. And I'm running redis as the broker and result backend on the localhost -
UnicodeDecodeError: 'UTF-8' codec can't decode byte 0xff in position 0: invalid start byte. DRF
There is a backend on django and a postgres DB that stores data about the item, including pictures. And there is a problem with getting a picture from the database, i've looked at enough solutions, but none of them work. serializers.py import base64 import uuid import imghdr class Base64ImageField(serializers.ImageField): def to_internal_value(self, data): if isinstance(data, str) and 'data:' in data and ';base64,' in data: header, data = data.split(';base64,') try: decoded_file = base64.b64decode(data) except (TypeError, ValueError): self.fail('invalid_image') file_name = str(uuid.uuid4())[:12] file_extension = self.get_file_extension(file_name, decoded_file) complete_file_name = f"{file_name}.{file_extension}" data = ContentFile(decoded_file, name=complete_file_name) return super(Base64ImageField, self).to_internal_value(data) def get_file_extension(self, file_name, decoded_file): extension = imghdr.what(file_name, decoded_file) return extension or 'jpg' class CreateItemSerializer(serializers.ModelSerializer): owner = serializers.ReadOnlyField(source='owner.username') photo = Base64ImageField(required=True) class Meta: model = CreateItem fields = '__all__' def create(self, validated_data): items = CreateItem.object.create_item( name = validated_data.get('name'), price = validated_data.get('price'), description = validated_data.get('description'), type_item = validated_data.get('type_item'), photo=validated_data.get('photo') ) return items views.py class GetItemView(APIView): serializer_class = CreateItemSerializer def get(self, request): items = CreateItem.object.all() response_data = { 'items': [ { 'photo': item.photo, 'name': item.name, 'description': item.description, 'type_item': item.type_item, 'price': item.price, } for item in items ] } return Response(response_data, status=status.HTTP_200_OK) full error traceback Internal Server Error: /api/v1/item/items-get/ Traceback (most recent call last): File "/home/anton/Documents/e-m/e-market/backend/my_backend/venv_em/lib/python3.12/site-packages/django/core/handlers/exception.py", line 55, in inner response = … -
Using React in existing Django Project
I have an existing Django project. Its a website that displays a map with leaflet. Markers and everything is loaded dynamically from django. Now I want to enhance that with React. In a sense that when you click a marker on the map, react will render based on marker_id the specific marker-details in a sidebar or something. I am not sure how to do that. In the django template I have a onclick event to get the marker-details: marker.uri = `/map/api/marker_details/?marker_id=${marker.marker_id}&marker_type=${marker.marker_type}` marker.on('click', function (e) { jQuery.get(this.uri); }); Since this is all in django template and not in React, the result is probably not accessible via react to render the details. Do I have to implement the map with the marker and everything in React to then be able to render the details via API? What am I missing? -
Graphql Apollo client
I want to send some data to my graphql python django that stores the data to mysql database. The data are week of planting, the block planted and images,videos. Using react as fronted, I have used dropzone in my react. But it just sending empty objects for image and video fields Sending and storing images to mysql db⁷ -
Iframe of the main page without authorization for an authorized user
Django. There was a problem while creating the website page. A user who is registered and authorized on the site should see the main page in an iframe, but as an unregistered user. Is this possible? -
Django /media/ files not served in production on hosting
I really feel like i am stuck, and hosting support doesn't include configuration help so maybe someone here would know i have django server with model: class Video(models.Model): thumbnail = models.ImageField(upload_to='thumbnails/', blank=True, null=True) saved here in folder thumbnails: MEDIA_URL = '/media/' MEDIA_ROOT = '/home/username/domains/domain.com/djangoapp/media' when i later want to use uploaded image in html: <img src="{{ video.thumbnail.url }}" alt="{{ video.title }}" class="video-thumbnail"> it it not served in production (works on debug=True), file not found 404 File is correctly uploaded, but not served I did python3 manage.py collectstatic enter image description here with no result Here's .htaccess file in the domain folder: enter image description here # DO NOT REMOVE. CLOUDLINUX PASSENGER CONFIGURATION BEGIN PassengerAppRoot "/home/username/domains/domain.com/djangoapp" PassengerBaseURI "/" PassengerPython "/home/username/virtualenv/domains/domain.com/djangoapp/3.7/bin/python" # DO NOT REMOVE. CLOUDLINUX PASSENGER CONFIGURATION END <IfModule mod_rewrite.c> RewriteEngine On RewriteCond %{REQUEST_URI} ^/media/ RewriteRule ^media/(.*)$ /home/username/domains/domain.com/djangoapp/media/$1 [L] </IfModule> that i tried adding this rule to, with no result. Any ideas on what could i try? Or anybody who had simillar problem? I tried to clear database and migrate it from zero. Tried collecting static. I tried changing rule in .htaccess. I tried running in debug and it worked. -
Mixing gzip & brotli in Django
I have django-brotli installed and use it's middleware. I would like Django to also serve gzipped content in case the client doesn't support brotli. Is it as easy as just adding GZipMiddleware to the middlewares list? I don't want them to potentially mix with eachother. -
We're sorry, but something went wrong. The issue has been logged for investigation. Please try again later [closed]
J'ai un problème actuellement sur mon application. Je l'ai héberger sur LWS et j'ai fait toutes les configuration possible mais j'ai toujours un problème voici se qui est écrit: We're sorry, but something went wrong. The issue has been logged for investigation. Please try again later. Technical details for the administrator of this website Error ID: 04580f7c Details: Web application could not be started by the Phusion Passenger(R) application server. Please read the Passenger log file (search for the Error ID) to find the details of the error. You can also get a detailed report to appear directly on this page, but for security reasons it is only provided if Phusion Passenger(R) is run with environment set to development and/or with the friendly error pages option set to on. For more information about configuring environment and friendly error pages, see: Nginx integration mode Apache integration mode Standalone mode This website is powered by Phusion Passenger(R)®, the smart application server built by Phusion®. I have a problem currently on my application. I hosted it on LWS and I did all the possible configuration but I still have a problem here is what is written: We're sorry, but something went wrong. The … -
TypeError at / cannot unpack non-iterable NoneType object (Django)
I'm trying to set up a system on my Django project where users can comment on individual posts on the main (index) page. However, I'm having an issue when it comes to trying to make it so the comment is automatically connected to the post. This is the code I tried in views.py: from django.core import paginator from django.shortcuts import render, redirect, get_object_or_404 from django.http import HttpResponse from .models import * from django.views.generic import ListView, CreateView, UpdateView from django.views.generic.detail import DetailView from .forms import * from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import login from django.core.paginator import Paginator from django.views import View import random def index(request, pk=None, *args, **kwargs): postdata = Post_Data.objects.all() profiledata = ProfileData.objects.all() likedata = Like.objects.all() dislikedata = Dislike.objects.all() comment = PostComment.objects.all() postid = Post_Data.objects.get(pk) # Initialize the comment form if request.method == 'POST': comment_form = PostCommentForm(request.POST) if comment_form.is_valid(): post = comment_form.save(commit=False) post.user = request.user post.save() return redirect('/') else: comment_form = PostCommentForm() # Create an empty form # Pass the comment form to the template context return render(request, 'index.html', { 'title': 'RoamTrip', 'postdata': postdata, 'profiledata': profiledata, 'likedata': likedata, 'dislikedata': dislikedata, 'comment': comment, 'comment_form': comment_form # Make sure this is included }) models.py: from django.contrib import admin from django.db import … -
Django serializer to convert list of dictionary keys to model fields
I am using pandas openpyxl to read excel file in my project. After reading the excel file I end up with list of dictionaries. These dictionaries have keys such as "Year 2024", "Range", "Main Point", and etc. I have a field in my Django app that has these fields such as "year", "range", "main_point". My question is how can I write a serializer to convert dictionary keys to fields in my model? I want to do this in serializer because I also want to validate dictionary data. So I have this list: my_data = [ {"Year 2024": "5", "Range":"2", "Main Point": "OK"}, {"Year 2024": "6", "Range":"3", "Main Point": "OK"}, {"Year 2024": "7", "Range":"4", "Main Point": "OK"}, ... ] and my model class MyModel(models.Model): year = models.IntegerField(...) range = models.IntegerField(...) main_pont = models.CharField(...) Thanks -
How to load chat messages in batches in Django using StreamingHttpResponse?
I'm working on a Django project that streams chat messages between two users using StreamingHttpResponse and async functions. I want to load messages in batches (e.g 20 at a time) instead of loading all the messages at once to optimize performance and reduce initial load time. Here’s my current view code: async def stream_chat_messages(request, recipient_id: int) -> StreamingHttpResponse: """View used to stream chat messages between the authenticated user and a specified recipient.""" recipient = await sync_to_async(get_object_or_404)(User, id=recipient_id) async def event_stream(): async for message in get_existing_messages(request.user, recipient): yield message last_id = await get_last_message_id(request.user, recipient) while True: new_messages = ( ChatMessage.objects.filter( Q(sender=request.user, recipient=recipient) | Q(sender=recipient, recipient=request.user), id__gt=last_id, ) .annotate( profile_picture_url=Concat( Value(settings.MEDIA_URL), F("sender__userprofile__profile_picture"), output_field=CharField(), ), is_pinned=Q(pinned_by__in=[request.user]), ) .order_by("created_at") .values( "id", "created_at", "content", "profile_picture_url", "sender__id", "edited", "file", "file_size", "is_pinned", ) ) async for message in new_messages: message["created_at"] = message["created_at"].isoformat() message["content"] = escape(message["content"]) json_message = json.dumps(message, cls=DjangoJSONEncoder) yield f"data: {json_message}\n\n" last_id = message["id"] await asyncio.sleep(0.1) async def get_existing_messages(user, recipient) -> AsyncGenerator: messages = ( ChatMessage.objects.filter( Q(sender=user, recipient=recipient) | Q(sender=recipient, recipient=user) ) .filter( (Q(sender=user) & Q(sender_hidden=False)) | (Q(recipient=user) & Q(recipient_hidden=False)) ) .annotate( profile_picture_url=Concat( Value(settings.MEDIA_URL), F("sender__userprofile__profile_picture"), output_field=CharField(), ), is_pinned=Q(pinned_by__in=[user]), ) .order_by("created_at") .values( "id", "created_at", "content", "profile_picture_url", "sender__id", "edited", "file", "file_size", "is_pinned", ) ) async for message in … -
__str__ returned non-string (type NoneType). In template /app/test/templates/test/init.html, error at line 0
Получаю следующую ошибку: str returned non-string (type NoneType) In template /app/test/templates/test/init.html, error at line 0 str returned non-string (type NoneType) Шаблон init.html - это базовый шаблон Ошибка происходит на уровне рендеринга шаблона. Из-за чего это может быть? Пробовал отладить, комментировал все места в шаблоне, где могли быть объекты None. Например для: book.author.name проверял, есть ли book.author и т.д. Но это не помогло. Я в django новичок, возможно нужно больше информации?