Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AttributeError: 'ManyToOneRel' object has no attribute 'get_transform' updating to Django 3.2.18
I'm trying to update to Django 3.2.18 but get this error. Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/django/db/models/options.py", line 608, in get_field return self.fields_map[field_name] KeyError: 'first' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/django/db/models/base.py", line 1838, in _check_ordering fld = _cls._meta.get_field(part) File "/usr/local/lib/python3.9/site-packages/django/db/models/options.py", line 610, in get_field raise FieldDoesNotExist("%s has no field named '%s'" % (self.object_name, field_name)) django.core.exceptions.FieldDoesNotExist: InteractiveSessionEvent has no field named 'first' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/lib/python3.9/threading.py", line 980, in _bootstrap_inner self.run() File "/usr/local/lib/python3.9/threading.py", line 917, in run self._target(*self._args, **self._kwargs) File "/usr/local/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 419, in check all_issues = checks.run_checks( File "/usr/local/lib/python3.9/site-packages/django/core/checks/registry.py", line 76, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/usr/local/lib/python3.9/site-packages/django/core/checks/model_checks.py", line 34, in check_all_models errors.extend(model.check(**kwargs)) File "/usr/local/lib/python3.9/site-packages/django/db/models/base.py", line 1304, in check *cls._check_ordering(), File "/usr/local/lib/python3.9/site-packages/django/db/models/base.py", line 1845, in _check_ordering fld.get_transform(part) is None and fld.get_lookup(part) is None AttributeError: 'ManyToOneRel' object has no attribute 'get_transform' I have upgraded all requirements to last version but the error still. Any idea ? Somebody could help me ? -
Get Name of Parent ChoiceField Django
I have an array of choices which are implemented in my Field model like so: CULTIVATIONS = [ ('Apples', ( ('willow', 'Willow'), ('devil', 'Devil'), )), ('Cherries', ( ('samba', 'Samba'), ('rita', 'Rita'), )), ('Peaches', ( ('zodiac', 'Zodiac'), ('astoria', 'Astoria'), )), ('Nectarines', ( ('patagonia', 'Patagonia'), ('garcima', 'Garcima'), )), ] class Field(models.Model): class Meta: verbose_name_plural = "Fields" ... cultivation = models.CharField(max_length=128, choices=CULTIVATIONS, blank=True) If i have a Field model I can access cultivation like field.cultivation . Question is how do I access the parent name? How to get the Apples choice instead of willow for example? -
How to get the limited result from Django query when filtering with a list of IDs.?
https://docs.djangoproject.com/en/4.2/topics/db/queries/#the-pk-lookup-shortcut Above is the link I am taking reference, Following is my query which contains two values in a list with which I want to filter that data. ans = Answer.objects.filter(question=1) ans.values('id') which gives the output <QuerySet [{'id': 2}, {'id': 42}]> and when I try to use it in the query below, Comment.objects.filter(answer_id__in=ans.values('id'))[0:5] it gives me out of just 5 elements. i.e., <QuerySet [<Comment: 4>, <Comment: 5>, <Comment: 26>, <Comment: 27>, <Comment: 28>]> What I want to do is, I want my output which will give me 5 elements of each ID. (Not just total 5 elements.) -
Django ModeViewSet: SerializerMethodField not getting called
I try to use SerializerMethodField to customize url of FileField in my API (url should return absolute url with site domain). Currently, it return "http://[IP]/media/[my-file-name] which is not a valid url. I have followed DRF documentation of ModelViewSet and SerializerMethodField. But audio_url and pictogramme_url are not displayed when calling my API via Postman (GET http://[my-site-domain]/api/risk/2/). It seems that get_audio_url and get_pictogramme_url methods are not called. More surprisingly, if I change fields attribute in RiskSerializer to control fields rendered (for example fields = ['id', 'label', 'created_at', 'created_by']), it doesn't seems to have any impact. I have found many post on SO but can't find any answer to solve my problem. api/views.py class RiskViewSet(viewsets.ModelViewSet): queryset = Risk.objects.all() serializer_class = RiskSerializer def get_serializer_context(self): context = super().get_serializer_context() context.update({'request': self.request}) return context api/serializers.py class RiskSerializer(serializers.ModelSerializer): """ A class to create a Risk serializer instance. """ audio_url = serializers.SerializerMethodField() pictogramme_url = serializers.SerializerMethodField() class Meta(): model = Risk fields = ['id', 'label', 'activated', 'audio_url', 'pictogramme_url', 'created_at', 'created_by'] # fields = '__all__' def get_audio_url(self, risk): request = self.context.get('request') audio_url = risk.audio.url return request.build_absolute_uri(audio_url) def get_pictogramme_url(self, risk): request = self.context.get('request') pictogramme_url = risk.pictogramme.url return request.build_absolute_uri(pictogramme_url) api/urls.py router = routers.DefaultRouter() router.register("risk", RiskViewSet, basename='risk') app_name="api" urlpatterns = [ # API path('',include(router.urls)), … -
Django doesn't keep connections alive, even though CONN_MAX_AGE is set to non-zero
I am using Django 4.2 + PostgreSQL 15 and it has 4 Gunicorn workers. CONN_MAX_AGE = 60 CONN_HEALTH_CHECKS = True So, from what I understand, if I run a request that uses the database, Django will keep the connection alive somehow. But that doesn't seem to happen: SELECT * FROM pg_stat_activity ORDER BY backend_start DESC; Doesn't show any open connections. None at all. Only logical, replication launcher, autovacuum launcher, walwriter, background writer, checkpointer which are not created by Django. How do I keep connections alive? I've thoroughly read the documentation and every related thread on SO. Another thing that I don't understand is, even if my connections were kept alive (which they are not), what process would keep connections alive? Is it WSGI loop? -
Command # 1 (DEL defender:failed:ip:127.0.0.1) of pipeline caused error: MISCONF Redis is configured to save RDB snapshots
I have a Django website where I use django-defender. Running it at localhost/development is not a problem but in AWS/deployment it is since a few days not possible to login to the admin site anymore. It did work a few days ago. I now get the following error-code. "Command # 1 (DEL defender:failed:ip:127.0.0.1) of pipeline caused error: MISCONF Redis is configured to save RDB snapshots, but it's currently unable to persist to disk. Commands that may modify the data set are disabled, because this instance is configured to report errors during writes if RDB snapshotting fails (stop-writes-on-bgsave-error option). Please check the Redis logs for details about the RDB error." I have looked at similar cases, but have not been able to find a solution that works. The redis log seems to be empty. The access log is stored in the PostrgreSQL database. In AWS I use a lightsail ubuntu environment with a PostgreSQL database. Any good tips for what to do? -
Switching the OneOnOne related instances between two model instances
I have these two models: class Item(models.model): space = models.OneToOneField(Space, null=False, on_delete=models.PROTECT) class Space(models.Model): ... An Item is linked to a single Space. A Space can only contain one Item. I want to switch Items: item_1 = Item.objects.get(id=1) item_2 = Item.objects.get(id=2) space_1 = Item.objects.get(id=1) space_2 = Item.objects.get(id=2) assert(item_1.space == space_1) # True assert(item_2.space == space_2) # True # Switching spaces results in an IntegrityError (of course) item_1.space = item_2.space item_2.space = item_1.space item_1.save() # IntegrityError Item.objects.bulk_update([item_1, item_2], ['space']) # IntegrityError I am now using a temporary Space that I create to switch the Items and that I delete afterwards. I was wondering if there's a more efficient way of switching these Items Spaces without running into an IntegrityError. -
Django relation different models to one
I use django 4.2 and want to relate some document models to a few other models. If I use only once model I do it like this class MyModel(models.Model): ... class Document(models.Model): name = models.CharField() file = models.FileField() my_model = models.ForeignKey(MyModel, related_name='documents') And I can get all docs for MyModel instance. instance = MyModel.objects.get() docs = instance.documents What is the best practice to do it with a few models? Ex: class MyModel(models.Model): ... class MySecondModel(models.Model): ... class MyThirdModel(models.Model): ... class Document(models.Model): name = models.CharField() file = models.FileField() my_model = models.ForeignKey(MyModel, related_name='documents', null=True) my_second_model = models.ForeignKey(MySecondModel, related_name='documents', null=True) my_third_model = models.ForeignKey(MyThirdModel, related_name='documents', null=True) It looks overhead. Besides Document instance will be relate to only once of these models and other will be null. Of course I can create 3 different models for Documents like MyModelDocument, MySecondModelDocument, MyThirdModelDocument. But it also looks like overhead because we will have 3 the same models to store files in 3 different tables in DB. -
Django Inline for m2m field
I've a Page model with m2m field to model called content I created an inline page but when testing the performance with django silk, I saw 11 queries mostly because of language field that's being fetched at least 4 times here's my code: models.py class Page(models.Model): created_at = models.DateTimeField(auto_now_add=True) name = models.ManyToManyField('content.Content', blank=True, related_name="as_page_names_set") description = models.ManyToManyField('content.Content', blank=True, related_name="as_page_description_set") slug = models.SlugField() class Language(models.Model): language_name = models.CharField(max_length=16, unique=True) iso_code = models.CharField(max_length=6, unique=True) class Content(models.Model): language = models.ForeignKey(Language, models.CASCADE) content = RichTextUploadingField(max_length=2048) admin: class PageNameAdmin(admin.StackedInline): extra = 1 model = Page.name.through verbose_name = "Page Name" form = PageContentForm class PageDescriptionAdmin(admin.StackedInline): extra = 1 model = Page.description.through form = PageContentForm verbose_name = "Page Description" @admin.register(Page) class PageAdmin(admin.ModelAdmin): inlines = [PageNameAdmin] exclude = ('name', 'description') def get_queryset(self, request: HttpRequest) -> QuerySet[Any]: return super().get_queryset(request).prefetch_related('name', 'description') forms.py: class PageContentForm(forms.ModelForm): language = forms.ModelChoiceField(queryset=Language.objects.all(), required=True) content = RichTextFormField(required=True) FIELDS = ['content', 'language'] class Meta: model = Page.name.through fields = ('page', 'content', 'language') def get_initial_for_field(self, field: Field, field_name: str) -> Any: if self.instance.pk and field_name in self.FIELDS: return getattr(self.instance.content, field_name) return super().get_initial_for_field(field, field_name) def clean(self) -> Dict[str, Any]: if self.instance.pk is None: self.cleaned_data['content'] = self.create_content_obj(**self.cleaned_data) self.cleaned_data.pop('language') else: self.cleaned_data['content'] = self.get_content_obj(**self.cleaned_data) return super().clean() def create_content_obj(self, content = None, language … -
NoReverseMatch at / Reverse for 'product_detail' with keyword arguments '{'slug': ''}' not found
Model class Product(models.Model): total_quantity = models.IntegerField() availability = models.IntegerField() product_name = models.CharField(max_length=100) featured_image = models.CharField(max_length=100) price = models.IntegerField() discount = models.IntegerField() product_information = RichTextField() model_name = models.CharField(max_length=100) categories = models.ForeignKey(Category, on_delete=models.CASCADE) tags = models.CharField(max_length=100) description = RichTextField() section = models.ForeignKey(Section, on_delete=models.DO_NOTHING) slug = models.SlugField(default='', max_length=500, null=True, blank=True) def __str__(self) : return self.product_name def get_absolute_url(self): from django.urls import reverse return reverse("product_detail", kwargs={'slug': self.slug}) class Meta: db_table = "core_Product" def create_slug(instance, new_slug=None): slug = slugify(instance.product_name) if new_slug is not None: slug = new_slug qs = Product.objects.filter(slug=slug).order_by('-id') exists = qs.exists() if exists: new_slug = "%s-%s" % (slug, qs.first().id) return create_slug(instance, new_slug=new_slug) return slug def pre_save_post_receiver(sender, instance, *args, **kwargs): if not instance.slug: instance.slug = create_slug(instance) pre_save.connect(pre_save_post_receiver, Product) View def ProductDetail(request, slug): return render(request, 'product/product_detail.html') HTML file i didnot add full html code <div class="product-image w-img"> <a href="{{i.get_absolute_url}}"> <img src="{{ i.featured_image }}" alt="product" style="height: 280px;"> </a> </div> Error during template rendering Reverse for 'product_detail' with keyword arguments '{'slug': ''}' not found. 1 pattern(s) tried: ['product/(?P[-a-zA-Z0-9_]+)\Z'] url path('product/<slug:slug>',ProductDetail, name='product_detail') Error during template rendering, Please help me to solve this bug -
soft delete in django
I am trying to implement soft delete, In my project where admin is creating clinic and clinic is creating patient I need to implement the soft delete here my model class Registered_user(AbstractUser): is_clinic = models.BooleanField(default=False) is_patient = models.BooleanField(default=False) is_delete = models.BooleanField(default=False) token = models.CharField(max_length=120, default=None, null= True) forgot_token = models.CharField(default=None, max_length=120, null=True), #clinic class Clinic(models.Model): register_clinic_user = models.OneToOneField(Registered_user, on_delete=models.CASCADE, primary_key=True) clnc_name = models.CharField(max_length=255) clinic_username = models.CharField(max_length=255) clnc_phone = models.BigIntegerField(null= True) clinic_email = models.CharField(max_length=50) clnc_contact_name = models.CharField(max_length=255) clnc_Job_Title = models.CharField(max_length=255) clnc_address_line1 = models.CharField(max_length=255) clnc_address_line2 = models.CharField(max_length=255) clnc_county = models.CharField(max_length=255) clnc_postcode = models.CharField(max_length=255) clnc_town_city = models.CharField(max_length=255) clnc_trade = models.CharField(max_length=255) clnc_website = models.CharField(max_length=255) clnc_register_office = models.CharField(max_length=255) clnc_telephone_number = models.BigIntegerField(null= True) clnc_created_at = models.DateTimeField(auto_now_add=True) clnc_status = models.BooleanField(default=False) updated = models.DateTimeField(auto_now=True) is_delete = models.BooleanField(default=False) published = models.DateTimeField(default=django.utils.timezone.now) view.py **this in my list view code** title = "Clinic List" request_url = request.get_full_path() clinic_list = Clinic.objects.filter(is_delete=True) return render(request, 'clinic_list.html', {'title': title,'clinic_list':clinic_list, 'requesturl':request_url, }) **this is my delete code** def delete(request, pk): clinic = Clinic.objects.get(register_clinic_user=pk) clinic.is_delete = True clinic.save() I am able to delete them but I want that when i delete this it see this clinic should not be able to login again and will have an error account deleted Please help thank's for your help in … -
How to implement case-insensitive in SlugRelatedField in drf serializers?
I'm using SlugRelatedField in my serializer. I want to validate it on a case-insensitive basis, so I add postfix "__iexact" to the "slug_field" attr. And validation works as I need (case-insensitive). class MySerializer(ModelSerializer): customer = serializers.SlugRelatedField(queryset=Customer.objects.all(), required=False, allow_null=True, slug_field='name__iexact') But when I try to get serializer.data, the following error occurs: * {AttributeError}'Customer' object has no attribute 'name__iexact' How can it be solved? -
Django REST Framework 401 error with Vue3
I am trying to get data from Django REST framework. However it returned 401, unless I refresh the entire page. The code is retrieved from a components, embed in a main Vue page. Here is how the page looks like. When I click the Menu it will show the component page. Vue3 Code mounted() { this.getUserInfo(); }, methods: { getUserInfo() { axios .get("/api/v2/user_info/") .then((response) => { this.users = response.data; }) .catch((error) => { console.log(error); }); }, Code from DJANGO Views.py class User_Info_List(generics.ListCreateAPIView): queryset = User_Info.objects.all() serializer_class = User_InfoSerializer Thanks in advance! -
How to make dashboard for json field values in django admin?
If I have json field in my models and I already input some fields Is this possible to make a dashboard in admin panel just to change the values of the keys in this json and making this keys only readable and can’t be changed? Also is there any code how to make a table in the admin panel main page? This one is related to make a table that will be shown in the admin panel to change the values of the json field Thanks in advance! Making form table that can change the values of this json field in my models based on the keys got returned in the table column as index and the values in the column fields and the row title should be an integar range -
Why my django localhost server does not restart after modification in my code in Visual Studio Code?
In all my django projects on Visual Studio Code, the server localhost django refreshes automatically after modification in my code. I'm using a venv with python 3.10.8 and I'm using autosave. I don't know if it's because of external libraries. I haven't found any other solutions. I tried: -m pip install django-browser-reload python manage.py collectstatic solve the problems in the "Problems" tab by updating the interpreter of my venv Despite this, each python code modify, add, delete, stop the server and restart it not like the behavior before. -
Django ReportLab 'list' object has no attribute 'getKeepWithNext'
I am trying to generate a pdf that will look like this: Here is my code: doc = doc = SimpleDocTemplate(invoice_name) flowable = [] flowable.append(Paragraph(invoice_name) flowable.append(Paragraph(invoice_number) flowable.append(Paragraph(invoice_date) flowable.append(Spacer(1,4)) t = Table(table_data) flowable.append(t) flowable.append(Spacer(1,4)) flowable.append(Paragraph(comment_and_amount) doc.build(flowable) But I get this error: 'list' object has no attribute 'getKeepWithNext' -
Docker configuration working in one machine(Ubuntu) but not in other(Mac M1)
I have setup Django with MySQL in docker compose in my mac M1. Everytime I do docker-compose up I get error for django application "Error: File "/usr/local/lib/python3.6/site-packages/MySQLdb/connections.py", line 166, in __init__ web_1 | super(Connection, self).__init__(*args, **kwargs2) web_1 | django.db.utils.OperationalError: (2002, "Can't connect to MySQL server on 'db' (115)") I have another machine (ubuntu) with same docker configuration there I don't get any issue. version: '3.2' services: web: restart: always expose: - "5000" build: context: . dockerfile: Dockerfile command: python manage.py runserver 0.0.0.0:5000 ports: - "9000:5000" environment: - MYSQL_HOST=db - MYSQL_USER=me - MYSQL_PASSWORD=me - MYSQL_DB=my_db depends_on: - db volumes: - ".:/code/google" db: image: mysql:5.7 restart: always expose: - "9306" ports: - "9306:3306" environment: - MYSQL_DATABASE=my_db - MYSQL_USER=me - MYSQL_PASSWORD=me - MYSQL_ROOT_PASSWORD=me volumes: - "./db_data:/opt/homebrew/var/mysql" - "./mysql-init:/docker-entrypoint-initdb.d" Here is my django setting DATABASES = { "default": { "ENGINE": "django.db.backends.mysql", "NAME": "my_db", "USER": "me", "PASSWORD": "me", "HOST": "db", "PORT": "3306", } } I have tried many things most of which i don't remember now. i.e i tried swapping the services, keeping only db service seems to work without web, tried changing the volume location, deleted all images, containers and volumes and rebuilding. If this works in ubuntu one machine shouldn't it work with … -
Using gevent in Django
I am using the Huey package for task queue in Django, which offers the use of the Greenlet worker. To use Greenlet, the documentation says, "the only way is to apply Gevent monkey-patch to create a custom bootstrap script that mimics the functionality of manage.py". #!/usr/bin/env python import os import sys # Apply monkey-patch if we are running the huey consumer. if 'run_huey' in sys.argv: from gevent import monkey monkey.patch_all() if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "conf") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv) How can apply this patch in Django. -
Storing values from a from into an ontology
I'm trying to store values in an ontology from a form using django, here is my form page, my problem reside in the Symptome area, those values aren't getting stored in my ontology, and the print statement print an empty list [] {% extends 'main.html' %} {% load static %} {% block title %} Création{% endblock %} {% block css %} <link rel="stylesheet" type="text/css" href="{% static 'css/forms.css' %}"> {% endblock %} {% block content %} <div class="form-container"> <h1>Ajouter un patient</h1> <form method="post"> {% csrf_token %} <div class="form-group"> <label>Nom :</label> {{ form_patient.Nom }} </div> <div class="form-group"> <label>Prénom :</label> {{ form_patient.Prenom }} </div> <div class="form-group"> <label>Sexe :</label> {{ form_patient.Sexe }} </div> <div class="form-group"> <label>Âge :</label> {{ form_patient.Age }} </div> <div class="form-group"> <label>Adresse :</label> {{ form_patient.Adresse }} </div> <div class="form-group"> <label>Profession :</label> {{ form_patient.Profession }} </div> <div class="form-group"> <label>Mail :</label> {{ form_patient.Mail }} </div> <div class="form-group"> <label>N° Téléphone :</label> {{ form_patient.Tel }} </div> <h1>Dossier médical</h1> <div class="form-group"> <div> <label>Antécédents Personnels:</label> {% for choice in form_dossier.AntPers %} <label>{{ choice.tag }} {{ choice.choice_label }}</label> {% endfor %} </div> <div> <label>Antécédents Familiaux:</label> {% for choice in form_dossier.AntFam %} <label>{{ choice.tag }} {{ choice.choice_label }}</label> {% endfor %} </div> </div> <div class="form-group"> <label>Habitude de vie:</label> {% for … -
How to display the contents of each portfolio separately?
How to display the contents of each portfolio separately? Lists are now displayed for all portfolios views.py: class ProjectView(ListView): template_name = 'project/project.html' model = Project context_object_name = 'projects' ordering = ['-title'] paginate_by = 2 def get_queryset(self, **kwargs): query = super(ProjectView, self).get_queryset() data = query.filter(is_active=True) return data class SingleProjectView(DetailView): template_name = 'project/single_project.html' model = Project def get_context_data(self, *args, **kwargs): context = super(SingleProjectView, self).get_context_data(*args, **kwargs) context["add_project_option"] = ProjectOption.objects.all() return context -
I am facing problem while deploying my django app in vercel
Error WARN! Due to builds` existing in your configuration file, the Build and Development Settings defined in your Project Settings will not apply. Learn More: https://vercel.link/unused-build-settings Installing Builder: @ardnt/vercel-python-wsgi Starting build Build AMI version: Amazon Linux release 2 (Karoo) ERROR Invalid runtime configured (python3.6). Available runtimes: ERROR - python3.9 ERROR See Vercel runtime documentation for more information: ERROR https://github.com/vercel/vercel/blob/main/DEVELOPING_A_RUNTIME.md#lambdaruntime Error: Invalid runtime configured (python3.6). Deployment completed : Invalid runtime configured (python3.6). **vercel.json**{ "builds": [{ "src": "Portfolio/wsgi.py", "use": "@vercel/python", "config": { "maxLambdaSize": "15mb", "runtime": "python3.9" } }], "routes": [ { "src": "/(.*)", "dest": "Portfolio/wsgi.py" } ] }` wsgi.py `import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Portfolio.settings') application = get_wsgi_application() app = application` -
Can't deploy django project on vercel
I am deploying a Django app on Vercel, but at the time of deployment the build_files.sh is not getting called vercel.json { "builds": [{ "src": "mysite/wsgi.py", "use": "@vercel/python", "config": { "maxLambdaSize": "15mb", "runtime": "python3.9" } }, { "src": "build_files.sh", "use": "@vercel/static-build", "config": { "distDir": "staticfiles_build" } } ], "routes": [{ "src": "/static/(.*)", "dest": "/static/$1" }, { "src": "/(.*)", "dest": "mysite/wsgi.py" } ] } build_files.sh echo "BUILD START" python3.9 -m pip install -r requirements.txt python3.9 manage.py collectstatic --noinput --clear echo "BUILD END" -
WebSocket+ API Django
I use the API https://rapidapi.com/chicmi/api/chicmi-local-fashion/ and websockets in Django. I have an HTML form where I enter the number of days and maximum result, click a button, and nothing happens. When trying to open the page http://127.0.0.1:8000/events/London/, the browser also attempts to establish a WebSocket connection using the URL ws://127.0.0.1:8000/ws/London/, but the server cannot find a corresponding handler for this URL and returns a 404 error. So, I need to redirect the client to a page with fashion show data after the client enters data into the form. Please advise on how to fix the error. [11/May/2023 20:55:04] "GET /events/London/ HTTP/1.1" 200 1676 Not Found: /ws/London/ [11/May/2023 20:55:04] "GET /ws/London/ HTTP/1.1" 404 4822 I tried to configure the paths correctly, but I still get an error [11/May/2023 20:55:04] "GET /events/London/ HTTP/1.1" 200 1676 Not Found: /ws/London/ [11/May/2023 20:55:04] "GET /ws/London/ HTTP/1.1" 404 4822 My code events.html <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Events</title> <script> var ws_url = 'ws://' + window.location.host + '/ws/' + '{{ city }}' + '/'; var ws = new WebSocket(ws_url); ws.onmessage = function(event) { var event_data = JSON.parse(event.data)['event_data']; var event_list = document.getElementById('event-list'); event_list.innerHTML = ''; for (var i = 0; i < event_data.length; i++) { var event … -
Django Web App - Axios 502 Error - Debugging
I'm not that familiar with Django and Axios, but I'm currently getting a 502 Error. Here's the console error that appears: M {message: 'Request failed with status code 502', name: 'AxiosError', code: 'ERR_BAD_RESPONSE', config: {…}, request: XMLHttpRequest, …} Does anybody know what this means or where I should start to debug this? Is this a front end error or a back end error? I tried editing both my API and front end code back to a version that worked before but it's still not working for some reason. I also logged into my server console log but it doesn't seem to be logging any error related to this api call. -
How to show only 5 elements of each foreign ID elements in ORM query?
id comment answer_id question_id 1 some comment 2 1 2 some comment 2 1 3 some comment 42 1 4 some comment 42 1 5 some comment 42 1 6 some comment 42 1 7 some comment 2 1 8 some comment 2 1 9 some comment 2 1 10 some comment 2 1 11 some comment 2 1 12 some comment 42 1 13 some comment 2 1 14 some comment 2 1 15 some comment 2 1 16 some comment 2 1 17 some comment 42 1 18 some comment 42 1 19 some comment 42 1 20 some comment 42 1 21 some comment 42 1 Above is the table of name Comment which contains comments of answers and questions. Note: I have two more tables that is Answer and Question which contains data of question and answer. I want to get the records of only first 5 of each answer_id i.e.,(2 and 42) of that particular question_id i.e., (1). Following is the query I have tried, answer = Answer.objects.filter(question=question_id) answer_comment = Comment.objects.filter(answer_id__in=answer.values('id')) but the above query gives all the data of specific question.