Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
query in many to many field order by first related object
in django i want to query in a many to many field that ordered by first related object. that means the queryset have to serach in the objects in the first location of many to many objects then others. as a simple incorrect sample i want to get objects like this: queryset = Practitioner.objects.filter(practices__0__city__slug='toronto') queryset += Practitioner.objects.filter(practices__other__except__0__city__slug='toronto') Note: practices is a ManyToManyField of Practice model in Practitioner model -
"GET / HTTP/1.1" 400 143 "-" "Render/1.0"
When I try to deploy Django to render, the following characters are displayed and I cannot deploy. ==> Detected service running on port 10000 ==> Docs on specifying a port: https://render.com/docs/web-services#port-detection 10.209.24.8 - - [04/Apr/2024:19:06:48 +0900] "GET / HTTP/1.1" 400 143 "-" "Render/1.0"[![enter image description here][1]][1] When I asked chatgpt, I was told that ALLOWED_HOSTS may not be set, but I think ALLOWED_HOSTS is set properly. from pathlib import Path from django.core.management.utils import get_random_secret_key import dj_database_url from dotenv import load_dotenv import os SECRET_KEY = os.environ.get('SECRET_KEY', 'xxxxxxxxxxxxxx') ALLOWED_HOSTS = ['10.209.25.170', 'django-render-xxx.onrender.com'] -
Django 'When' object is not iterable
I'm using django-filter to show work-hour of employs. models.py: ... class Attendance(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="Attendances") day = models.DateField() start_time = models.TimeField() end_time = models.TimeField() is_confirmed = models.BooleanField() task = models.ForeignKey(Tasks, on_delete=models.CASCADE) ... filter.py: class WorkhourFilter(django_filters.FilterSet): def __init__(self, *args, **kwargs): super(WorkhourFilter, self).__init__(*args, **kwargs) start_date = ... end_date = ... self.queryset = self.Meta.model.objects.filter(user=self.request.user, day__gte=start_date, day__lte=end_date).values('task__project__title', 'task__project').annotate( raw_work_hour=Sum(F('end_time') - F('start_time'), ), confirmed_work_hour=Sum(Case(When(is_verified=1, then=F('end_time') - F('start_time'))))).order_by('task__project') I get 'When' object is not iterable error. confirmed_work_hour has problem but the raw_work_hour alone is not a problem. This query is working well in get_queryset() of corresponding View but when I trying to apply filters it'll break. trace : Django Version: 4.2.5 Python Version: 3.9.13 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_extensions', 'crispy_forms', 'crispy_bootstrap5', 'django_tables2', 'django_htmx', 'django_filters', 'jalali_date', 'ckeditor', 'ckeditor_uploader', 'guardian', 'django_cascading_dropdown_widget', 'dashboard.apps.DashboardsConfig', 'auth.apps.AuthConfig'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django_htmx.middleware.HtmxMiddleware'] Traceback (most recent call last): File "D:\Python\DjangoTest\venv\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "D:\Python\DjangoTest\venv\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\Python\DjangoTest\venv\lib\site-packages\django\views\generic\base.py", line 104, in view return self.dispatch(request, *args, **kwargs) File "D:\Python\DjangoTest\venv\lib\site-packages\django\contrib\auth\mixins.py", line 73, in dispatch return super().dispatch(request, *args, **kwargs) File "D:\Python\DjangoTest\venv\lib\site-packages\braces\views\_access.py", line 438, in dispatch return super(StaffuserRequiredMixin, self).dispatch( File "D:\Python\DjangoTest\venv\lib\site-packages\braces\views\_access.py", line 375, in … -
How to display the uuid field of my serializer as a string in a get request with django restframework
Here is my serializer class AgenceSerializer(serializers.Serializer): uuid = serializers.UUIDField(format='hex',allow_null=True,required=False) <------- p1 = serializers.CharField(max_length=50,required=True) p2 = serializers.CharField(max_length=50,required=True) views.py @api_view(["POST"]) def details_agence(request): if request.method == "POST": serializer = AgenceUUIDSerializer(data=request.data) if serializer.is_valid(): agence_repr = serializer.agence_details(data=request.data) serializer = AgenceSerializer(agence_repr) print(serializer) return Response(serializer.data,status=status.HTTP_200_OK) <--------- ... a print on the serializer gives me the following: AgenceSerializer({'uudi': 'A75DF036-6C16-4311-9825-22B1295D8A26', 'p1': 'Ozangue', ...}): uuid = UUIDField(allow_null=True, format='hex', required=False) ... But when I display the data, in the response, the uuid field is always null How to solve this problem ? -
Deploy a django application that uses PostgreSQL into a cloud VM
I have a django web application which I would like to deploy in a cloud VM. As of now I am planning to deploy that into AWS EC2. Planning to use gunicorn as WSGIServer and NGINX as web server. I have gone through many documentations all of which explains in a way that the whole source code is present in the VM. Mainly I would like to know how can I package my application and deploy it? For example, in case of web applications using java, we normally creates a war file. How can we do similar thing with django? I am new to Django and Python. -
Django Static Files - CSS File loading problem
The error I am getting in the browser my project details what is the problem? How should I resolve this? every configuration is correct still not working. I am not able to upload my front in the django project. Thanks in advance -
Clearing cache when threre is change in model
I've model called Announcement and Announcement model has connected with reverse relationship with 20 another models. I cached my Announcement list API. I should clear cache, if I got changes in one of reverse related model. -
Celery Worker doesn't find the task
I use the worker in conjunction with beats and beats finds everything perfectly, but as soon as beat passes the task to the worker, an error pops up: KeyError: 'tasks.cache_popular_posts' all information: Did you remember to import the module containing this task? Or maybe you're using relative imports? Please see https://docs.celeryq.dev/en/latest/internals/protocol.html for more information. The full contents of the message body was: b'[[], {}, {"callbacks": null, "errbacks": null, "chain": null, "chord": null}]' (77b) The full contents of the message headers: {'lang': 'py', 'task': 'tasks.cache_popular_posts', 'id': 'bdaa8c59-8b84-4f79-af1c-7fe34468894d', 'shadow': None, 'eta': None, 'expires': None, 'group': None, 'group_index': None, 'retries': 0, 'timelimit': [None, None], 'root_id': 'bdaa8c59-8b84-4f79-af1c-7fe34468894d', 'parent_id': None, 'argsrepr': '()', 'kwargsrepr': '{}', 'origin': 'gen3644@WIN-7483UVBHTO4', 'ignore_result': False, 'replaced_task_nesting': 0, 'stamped_headers': None, 'stamps': {}} The delivery info for this task is: {'exchange': '', 'routing_key': 'celery'} Traceback (most recent call last): File "C:\Users\User\VsCodeProjects\Pastebin_hardEdition\venv\lib\site-packages\celery\worker\consumer\consumer.py", line 658, in on_task_received strategy = strategies[type_] KeyError: 'tasks.cache_popular_posts' this task #posts/tasks.py @app.task def cache_popular_posts(): try: popular_posts = Post.objects.filter(views__gt=10) for post in popular_posts: hash = post.postmeta.hash_id cache.add(key=hash, value=post) except Exception as ex: return ex #app/celery.py import os from celery import Celery os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Pastebin_hardEdition.settings") app = Celery("Pastebin_hardEdition") app.config_from_object("django.conf:settings", namespace="CELERY") app.autodiscover_tasks() #beats app.conf.beat_schedule = { 'cache-popular-post&Meta-every-30-seconds': { 'task': 'tasks.cache_popular_posts', 'schedule': 30.0, }, } app.conf.timezone = … -
Ckeditor styles not applying with my tailwind website
from django.db import models from ckeditor.fields import RichTextField class Project(models.Model): category = models.ForeignKey(ProjectCategory, on_delete=models.CASCADE) client = models.CharField(max_length=100) title = models.CharField(max_length=100) description = RichTextField(null=True) pdf = models.FileField(null=True, blank=True) def __str__(self): return self.title I am using tailwind css in my frontend and i am displaying the project description {{project.description}} but the styles i have added why i filled the description with ckeditor didn't apply when i displayed the description in my tailwind frontend how to fix that?? -
Why HTML Registration Form Data is not Received in django
I have below configurations of demo\urls.py, user\urls.py, views.py & HTML Form. Still when I press the submit button of HTML Form it says File Not Found. Taking help from ChatGPT which provided two Solutions as mentioned in attached file, even then I am getting Error. What to do demo\urls.py urlpatterns = [ path('admin/', admin.site.urls), path('user', views.register), ] user\urls.py urlpatterns = [ path('register', views.register), ] views.py def register(request): if request.method == 'POST': name = request.POST.get("name") email = request.POST.get("email") password = request.POST.get("password") created_at = request.POST.get("created_at") updated_at = request.POST.get("updated_at") I have following code in HTML Form ``` {% csrf_token %} ``` <label for="name">Name:</label><br> ``` <input name="name" type="text" id="name" name="name"><br> ``` <label for="email">Email:</label><br> ``` <input name="email" type="email" id="email" name="email"><br> ``` <label for="password">Password:</label><br> ``` <input name="password" type="password" id="password" name="password"><br> ``` <script> ``` // Generate current datetime for Hidden fields ``` var current_datetime = new Date().toISOString(); ``` document.getElementById('current_datetime').value = current_datetime; ``` </script> ``` <!-- Hidden fields for created_at and updated_at --> ``` <input type="hidden" name="created_at" value="{{ current_datetime }}"> ``` <input type="hidden" name="updated_at" value="{{ current_datetime }}"> ``` <button type="submit">Register</button> ```</form> ```</body> ```</html> When I press the submit button of HTML Form it says File Not Found. What is the Error & how to fix it I had … -
nginx for development server or connect manage.py runserver from local network
I have development environment (on mac) and access from the android in the same local network. For example my Mac IP is 192.168.0.5,then connecting from android http://192.168.0.5/ Now I have two choices uwsgi and python manage.py runserver When using uwsgi, I need to restart uwsgi for reflecting the code change. When using python manage.py runserver, It doesn't connected from the android. Is there a way to solve this? -
Error with PgBouncer on Heroku with Django and Docker
I'm currently running into database connection issues with my Django & Postgres app hosted on Heroku. Before upgrading my database plan, I wanted to try solving the issue with pgbouncer. According to this article by Heroku, the Procfile would need to be updated from something like web: gunicorn hellodjango.wsgi to web: bin/start-pgbouncer-stunnel gunicorn hellodjango.wsgi after provisioning the pgbouncer buildpack. The thing is, I don't use a Procfile but a heroku.yml. Currently, my yml file has this: run: web: command: - gunicorn --bind 0.0.0.0:$PORT --workers 1 --threads 8 --timeout 0 my_app.asgi:application -k uvicorn.workers.UvicornWorker I tried updating the web command to this: bin/start-pgbouncer-stunnel gunicorn --bind 0.0.0.0:$PORT --workers 1 --threads 8 --timeout 0 my_app.asgi:application -k uvicorn.workers.UvicornWorker but that gives me this error: bin/start-pgbouncer-stunnel: not found I tried this answer as well, but get an pgbouncer: unrecognized service error. Any ideas on how to solve this? -
Django doesnt update the translation
I am trying to add Translation to russian from english I tried clearing the cache, deleting locale folder, changing the translation. it all doesnt work #: core/templates/core/layout.html:59 core/templates/core/layout.html:112 msgid "Home" msgstr "Главная" But it displays "Начало" instead of "Главная". my settings.py: LANGUAGE_CODE = 'en' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True LANGUAGES = ( ("en", ('English')), ("ru", ('Russian')), ) LOCALE_PATHS = ( os.path.join(BASE_DIR, 'locale/'), ) -
Django test suite throws error on field that's not loaded: "could not convert string to float"
The following simple test throws the errors ValueError: could not convert string to float: '' The above exception was the direct cause of the following exception: ValueError: Field 'amount' expected a number but got ''. from django.test import TestCase from .models import Customer class TestSetup(TestCase): def setUp(self): self.testCustomer = Customer(firstname='Ron', street_name='Somestreet', street_suffix='Dr', street_number='1', phone='111-111-1111', city='Somecity', zipcode='87000') The field 'amount' does exist, but in a model that isn't loaded for any tests: class Appointment(models.Model): amount = models.FloatField(blank=True, default=0.0) But just in case it's instantiating that model in the process of creating the test database, I migrated "default=0.0" to "default='0.0' " (Single quotes around the value). Same error. I'm initiating the test with python manage.py test from the project directory. -
Django form is invalid and not submitting?
I have four main parts: The BaseJournal form, The JournalTemplate form, a model Journal and amy view which handles it. Here is the Journal Model: class Journal(models.Model): MOOD_CHOICES = [ ('happy', 'happy.png'), ('angry', 'angry.png'), ('neutral', 'neutral.png'), ('sad', 'sad.png'), ] user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) date = models.DateField(auto_now_add=True, editable=False) title = models.CharField(blank=False, max_length=50, default="default title") mood = models.CharField(max_length=20, choices=MOOD_CHOICES, default='neutral') custom_fields = JSONField(default=dict) field_order = JSONField(default=list) @property def attached_files(self): return AttachedFile.objects.filter(journal=self) Here is BaseJournal form: class BaseJournalForm(forms.ModelForm): def __init__(self, user=None, **kwargs): super().__init__(**kwargs) self.fields['mood'].label = '' files = MultipleFileField(required=False) class Meta: model = Journal fields = ['title', 'files', 'mood'] widgets = { "mood": forms.HiddenInput(), "files": MultipleFileInput(), } Here is my Journal Template form: class JournalEntryForm(BaseJournalForm): template = forms.ModelChoiceField( queryset=JournalTemplate.objects.all(), empty_label='No Template', # Set the placeholder text required=False, widget=forms.Select(attrs={'class': 'form-control'}) ) num_questions = forms.IntegerField(label='Number of Questions', required=False, widget=forms.NumberInput(attrs={'class': 'form-control'}), min_value=0) num_feelings = forms.IntegerField(label='Number of Feelings', required=False, widget=forms.NumberInput(attrs={'class': 'form-control'}), min_value=0) num_subheadings = forms.IntegerField(label='Number of Subheadings', required=False, widget=forms.NumberInput(attrs={'class': 'form-control'}), min_value=0) num_events = forms.IntegerField(label='Number of Events', required=False, widget=forms.NumberInput(attrs={'class': 'form-control'}), min_value=0) template_name = forms.CharField(label='Template Name', required=False, widget=forms.TextInput(attrs={'class': 'form-control'})) class Meta: model = Journal fields = BaseJournalForm.Meta.fields + ['template', 'num_questions', 'num_feelings', 'num_subheadings', 'num_events', 'template_name'] Here is my view which handles the form: def create_journal_entry(request): templates = JournalTemplate.objects.all() … -
Django's update_or_create failing although kwargs is specified
I have the following Django model: class Itens(models.Model): id = models.AutoField(primary_key=True) itempr_id = models.IntegerField(unique=True) # This is NOT a relationship cod_item = models.CharField(max_length=16, unique=True) # Other fields... As you can see, both itempr_id and cod_item are unique, so I specified update_and_create to take this into account: class CreateItensSerializer(serializers.ModelSerializer): class Meta: model = Itens fields = '__all__' def create(self, validated_data): item, created = Itens.objects.update_or_create( itempr_id=validated_data.get('itempr_id'), cod_item=validated_data.get('cod_item'), defaults=validated_data ) return item I call and save the serializer like this: serializer = CreateItensSerializer(data=itens, many=True) if serializer.is_valid(): serializer.save() However, whenever there is a duplicate, I get the following error: {'itempr_id': [ErrorDetail(string='itens with this itempr id already exists.', code='unique')], 'cod_item': [ErrorDetail(string='itens with this cod item already exists.', code='unique')]} I do not expect any uniqueness violation problems since the fields were already specified to be unique in the function call How can I fix this? EDIT: just to make it clear, this works if the DB's table is empty, there's no problem in the itens argument in serializer = CreateItensSerializer(data=itens, many=True) -
How to access Django session using class-based views? (with Angular) The self.request.session.get('key') returning None
I am currently developing a Django/Angular application. Within the frontend component, several methods are called upon initialization (ngOnInit), and these methods all rely on the same base query (and then they do other things with that data). What i'm trying to do is to create a single method that retrieves the base data used by these other methods. What I'm currently doing here is to query this base data once, store it in the Django session and then access it from the other views as needed (I would appreciate any alternative points of view if you think this aint a good solution). The issue is that I can't access the Django session beyond the view where is being created. Whenever I try to access it from the other views I get 'None'. Here is a simplified version of my Angular code: export class AnalysisComponent { fieldID = 4; constructor(private _service: Service) {} async ngOnInit() { await this.getBaseData(this.fieldID); // I used async/await so the other methods do not execute until this one is over. this.testOne(this.fieldID); this.testTwo(this.fieldID); this.testThree(this.fieldID); } async getBaseData(field_id){ try { const result = await this._service.getBaseData(field_id).toPromise(); } catch (error) { console.error(error); } } testOne(field_id) { this._service.testOneView(field_id).subscribe( (data: any) => { … -
How to search through multiple tables using Postgres Full Text Search and GIN index in Django
models.py from django.contrib.postgres.indexes import GinIndex from django.db import models from django.contrib.postgres.search import SearchVectorField class FilmTag(models.Model): name = models.CharField(max_length=255) class Film(models.Model): film_id = models.AutoField(primary_key=True) title = models.CharField(max_length=255) description = models.TextField(blank=True, null=True) tags = models.ManyToManyField(FilmTag, null=True, blank=True) vector_column = SearchVectorField(null=True) # new field def __str__(self): return ', '.join(['film_id=' + str(self.film_id), 'title=' + self.title, 'description=' + self.description]) class Meta: indexes = (GinIndex(fields=["vector_column"]),) # add index 0002_migration # Generated by Django 5.0.4 on 2024-04-03 19:41 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ("app", "0002_film_vector_column_film_app_film_vector__2213d6_gin"), ] operations = [ migrations.RunSQL( sql=''' CREATE TRIGGER vector_column_trigger BEFORE INSERT OR UPDATE OF title, description, vector_column ON app_film FOR EACH ROW EXECUTE PROCEDURE tsvector_update_trigger( vector_column, 'pg_catalog.english', title, description ); UPDATE app_film SET vector_column = NULL; ''', reverse_sql=''' DROP TRIGGER IF EXISTS vector_column_trigger ON film; ''' ), ] I'd like to enhance my film search functionality by incorporating tags using Postgres Full Text Search. How can I go about implementing this? Currently, the search is limited to the film's text and description. -
How to pass request object for dynamic form in django-formtools form wizzard?
Probably there is someone who's tried to make multistep form wizzard, but the goal is to make them dynamic. By dynamic i mean that after submiting one form, this form remains in its position and data from this form is sent in ajax and if it's valid a server sent html with second form. Seems to be easy, but i'm really strugling how to render csrf_token in dynamic forms. So, i have main.html like: <div class="col-xxl-6" id="testId"> {{ wizard.form }} </div> and partial htmls with forms, like first_form.html: {% load static %} <form action="{% url 'app:url' %}" method="post" novalidate> {% csrf_token %} {{ wizard.management_form }} {{ first_form.field }} </form> and the second_form.html is the same, let's say so, obviously, i have to pass a request and it's completely possible to do that with render_to_string if form is supposed to be sent with AJAX. But in case with regular rendering (without AJAX) render_to_string is not the appropriate way. Another best place i find: __init__ in my form i looked at the render() method in class RenderableMixin, which is parent for forms.Form and wanted to do something like this: class MyForm: template_name = "app/templates/forms/first_form.html" def __init__(self, request=None, *args, **kwargs): self.request = request … -
How to upload files with Django and Python
I want to let the user upload some excel files, and first im trying to save them in the media/uploaded/int:projectid (that i want to create if its not created already). But when i try to upload it, in the /admin it says: Error in field "template_file": This field is required. Error in field "title": This field is required. this is my views.py: @csrf_protect @login_required(login_url='login') def uploadTemplate(request, proyecto_id): proyecto = get_object_or_404(Project, id=proyecto_id) if request.method == 'POST': form = UploadTemplateForm(request.POST, request.FILES) if form.is_valid(): template_file = request.FILES.get('template_file') if template_file: try: create_project_folder(proyecto) # Crear la carpeta del proyecto si no existe handle_uploaded_file(template_file, proyecto) messages.success(request, 'File uploaded successfully.') return redirect('success') except Exception as e: messages.error(request, f'Error handling the file: {e}') else: messages.error(request, 'No file provided in the form.') else: for field, errors in form.errors.items(): for error in errors: messages.error(request, f'Error in field "{field}": {error}') else: form = UploadTemplateForm() return render(request, 'uploadFileBox.html', {'form': form, 'project': proyecto}) def create_project_folder(proyecto): base_folder = 'media/uploaded' project_folder = os.path.join(base_folder, str(proyecto.id)) if not os.path.exists(project_folder): os.makedirs(project_folder) def handle_uploaded_file(f, proyecto): try: base_folder = 'media/uploaded' project_folder = os.path.join(base_folder, str(proyecto.id)) file_path = os.path.join(project_folder, f.name) with open(file_path, 'wb+') as destination: for chunk in f.chunks(): destination.write(chunk) print("Archivo guardado correctamente.") except Exception as e: print("Error al manejar el archivo:", … -
django channels took to long to shut down and was killed error in backend
I used django channels in this project and created a consumer in the following code: class WSConsumer(WebsocketConsumer): def connect(self): self.room_name = self.scope["url_route"]["kwargs"]["room_name"] self.stid=self.scope["url_route"]["kwargs"]["stid"] self.types=self.scope["url_route"]["kwargs"]["types"] self.room_group_name = f"station_{self.room_name}" if (self.types=="student"): try: workclass=WorkClass.objects.get(workclass_id=self.room_name) st=Station.objects.get(id=self.stid) if st in workclass.stations.all(): st.state=True st.save() async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() else: self.disconnect(10) except WorkClass.DoesNotExist: self.disconnect(10) elif(self.types=="teacher"): async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() except WorkClass.DoesNotExist: raise StopConsumer() else: raise StopConsumer() def disconnect(self, close_code): async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) if(self.types=="student"): st=Station.objects.get(id=self.stid) st.state=False st.save() async_to_sync(self.channel_layer.group_send)( self.room_group_name, {"type":"list_stations","message":self.room_name,"roles":"stations"} ) async def websocket_disconnect(self, message): await self.channel_layer.group_send( self.room_group_name, {"type":"list_stations","message":self.room_name,"role":"stations"} ) await super().websocket_disconnect(message) def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json["message"] role=text_data_json['roles'] types=text_data_json['type'] async_to_sync(self.channel_layer.group_send)( self.room_group_name, {"type":types,"message":message,"role":role} ) # Receive message from room group #list of method... in settings i used this configuration: INSTALLED_APPS = [ 'daphne', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', #apps ] ASGI_APPLICATION = "backend.asgi.application" CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [("127.0.0.1", 6379)], }, }, } The problem is that after some time in the server terminal it shows the error "took to long to shut down and was killed", this time is variable. In the meantime, I run it on the front-end by accessing through the IP address on another computer No matter how much I googled and … -
Is nodejs better than django for real time backend system development
Is nodejs better than django for real time backend system development a comprehensive guide will helpIs nodejs better than django for real time backend system development a comprehensive guide will helpIs nodejs better than django for real time backend system development a comprehensive guide will helpIs nodejs better than django for real time backend system development a comprehensive guide will helpIs nodejs better than django for real time backend system development a comprehensive guide will helpIs nodejs better than django for real time backend system development a comprehensive guide will helpIs nodejs better than django for real time backend system development a comprehensive guide will helpIs nodejs better than django for real time backend system development a comprehensive guide will helpIs nodejs better than django for real time backend system development a comprehensive guide will helpIs nodejs better than django for real time backend system development a comprehensive guide will helpIs nodejs better than django for real time backend system development a comprehensive guide will helpIs nodejs better than django for real time backend system development a comprehensive guide will helpIs nodejs better than django for real time backend system development a comprehensive guide will help -
django Channels / django restframework Pending task
I have a django channels projeto to handle a websocket connections, but some http request are blocking the app, and im receiving this error: Application instance <Task pending name='Task-3739' coro=<ProtocolTypeRouter.call() running at /usr/local/lib/python3.10/site-packages/channels/routing.py:62> wait_for=<Future pending cb=[shield.._outer_done_callback() at /usr/local/lib/python3.10/asyncio/tasks.py:864, Task.task_wakeup()]>> for connection <WebRequest at 0x7efc603c8250 method=POST uri=/charger_api/heartbeat/ clientproto=HTTP/1.1> took too long to shut down and was killed. the entire comsumer are async and the rest part of django app is sync this is my Comsumer class ChargerSessionConsumer(AsyncJsonWebsocketConsumer): def __init__(self, *args, **kwargs): super().__init__(args, kwargs) self.client_id = None self.group_name = None async def connect(self): self.client_id = self.scope["url_route"]["kwargs"]["client_id"] await self.channel_layer.group_add( self.group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): await self.channel_layer.group_discard(self.group_name, self.channel_name) raise StopConsumer() I try to raise to raise the stodComsumer ocording the documentation but the error percists -
App Runner Django Deployment Error Python Version3.11
I'm trying to deploy my Django backend to AppRunner. My apprunner.yml is this; version: 1.0 runtime: python311 build: commands: build: - pip3 install pipenv - pipenv install post-build: - python3 manage.py test env: - name: DEBUG value: "on" - name: SECRET_KEY value: "django-insecure-a=0f%a$+p$cyb)xobnaa42@gypz3q&f-!n&03&_t$t#_bn2+h4" - name: ALLOWED_HOSTS value: "*" run: runtime-version: 3.11 pre-run: - pip3 install pipenv - pipenv install command: pipenv run gunicorn django_apprunner.wsgi --log-file - network: port: 8000 env: 8000 env: - name: DEBUG value: "on" - name: SECRET_KEY value: "django-insecure-a=0f%a$+p$cyb)xobnaa42@gypz3q&f-!n&03&_t$t#_bn2+h4" - name: ALLOWED_HOSTS value: "*" In the Application Log File this error comes; raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? I tried to deploy my Django Backend via AppRunner but I got this error. -
How do I display the main category?
I need the main category to be displayed once, and below it its characteristics {% load static %} <div class="characteristics"> <h2>Характеристики</h2> {% for values in specs %} {{ values.category.gl_category }} <br> {% endfor %} {% for char in specs %} <div class="uk-grid-small s-char-2" uk-grid> <div class="uk-width-expand" uk-leader="media: @m">{{ char.category }}</div> <div>{{ char.description }}</div> </div> {% endfor %} </div> That's what's going on, and that's what it takes.