Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
KeyError: 'room_name' in Django channels
I'm stuck on this KeyError issue. Can anyone advise what's the problem? First I'll show you my code here. class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room await(self.channel_layer.group_add)(self.room_group_name, self.channel_name) await self.accept() routing.py websocket_urlpatterns = [ re_path(r'^ws/(?P<room_name>\w+)/$', ChatConsumer.as_asgi()), ] urls.py path('chat/<str:room_name>/', views.ChatAPIView.as_view()) and The Error is - KeyError: 'room_name'. I referred to the Django docs, but the difference is I used ApiView in views.py. I'm using this project for an android project as a server. Need to be fixed the KeyError. -
Django relative_name issues on model Inheritance
I have an issus with inheritance on models and reverse relations. Here my models : class A(B): designation = CharField() class B (): owner = ForeignKey(A, null=True, blank=True, related_name='sites') name = CharField() street1 = CharField() class C(): name = CharField() relation_a = ForeignKey(A, related_name='all_elements', null=True, blank=True) relation_b = ForeignKey(B, related_name='elements', null=True, blank=True) Firstly my model A inherits from the model B for get all address informations.Model A can have several sites(B) I have an other model C with foreign key to model A and another to model B. For each element B I want get all elements. This work fine: for b in B.objects.all(): print(b.elements.all()) For get all elements link to A is work: print(A.all_elements.all()) But I can't get just the element C linked to A by the relation_b print(A.elements.all()) I got an empty list. If I want only this element I need to pass by B models B.objects.get(id=A.id).elements.all() This is the first issues. Secondly, my main problem is with serializer. My serializer : A_Serializer(B_Serializer): class Meta: model = A fields = [ 'designation', 'street1', 'site', 'all_elements', 'elements', ] expandable_fields = { 'sites': (B_Serializer, {'many'=True} 'all_elements': (C_Serializer,{'many':True}), 'elements': (C_Serializer,{'many':True}), } In DRF I can expend the all_elements in serializer A. … -
csv download is not including all the results in a django application
im trying to build a web app with python and django, in this application a user can enter a list of websites, the results will show the website status, the website title, the website summary, the email, the phone number, facebook and instagram links if present. At the end the user can download the results as csv, btw the csv is showing only 1 result, and even incomplete (the website, the phone, the email, fb and instagram are missing). What am i doing wrong? here is the main file # website_checker/checker/views.py from django.shortcuts import render from django.http import HttpResponseRedirect from django.shortcuts import render, HttpResponse from django.urls import reverse import requests from bs4 import BeautifulSoup from .utils import get_business_summary, extract_emails, extract_phones, extract_social_media_links import spacy import re import csv import io # Function to get a business summary from the text def get_business_summary(text): nlp = spacy.load('en_core_web_sm') doc = nlp(text) sentences = [sent.text.strip() for sent in doc.sents] business_summary = '' for sent in sentences: # You can add more conditions to extract business-specific information from the text if 'business' in sent.lower() or 'company' in sent.lower(): business_summary = sent break return business_summary # Function to extract emails from the text def extract_emails(text): # Use … -
Error when trying to delete model instance in Django 4.2.2
I've been trying to delete an existent instance from the user table (mysql) but I keep getting error from the user.delete() this is the my viewpoint: @api_view(['GET', 'PUT', 'DELETE']) def user_api_id(request): try: id = request.GET.get('id') user = User.objects.get(pk=id) if request.method == 'GET': serializer = UserSerializer(user) return Response(serializer.data) elif request.method == 'PUT': serializer = UserSerializer(user, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) elif request.method == 'DELETE': try: user.delete() return Response(status=status.HTTP_204_NO_CONTENT) except ValidationError as ve: return Response({"error": str(ve)}, status=status.HTTP_400_BAD_REQUEST) except Exception as e: return Response({"error": str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) except User.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) When I launch a DELETE request I get this: "error": "(1292, \"Truncated incorrect DOUBLE value: 'john'\")" (btw the user I want to delete has id='john') This is my User model: class User(models.Model): id = models.CharField(primary_key=True, max_length=50) password = models.CharField(max_length=50) name = models.CharField(max_length=25) lastname = models.CharField(max_length=25) age = models.IntegerField() gender = models.CharField(max_length=6) email = models.CharField(max_length=50, blank=True, null=True) phone = models.CharField(max_length=50, blank=True, null=True) address = models.CharField(max_length=50, blank=True, null=True) educationallevel = models.CharField(db_column='educationalLevel', max_length=50, blank=True, null=True) # Field name made lowercase. experience = models.CharField(max_length=20, blank=True, null=True) is_active = models.BooleanField(default=True) is_anonymous = models.BooleanField(default=False) is_authenticated = models.BooleanField(default=True) USERNAME_FIELD = 'id' REQUIRED_FIELDS = [] class Meta: managed = False db_table = 'user' And this is the … -
DRF Spectacular - @extend_schema subclass method for Serializers
Im using DRF_SPECTACTULAR to generate swagger DOC from my DRF Project. I have a GenericViewSet that implement CRUD methods. Over each ones, I have extend_schema decorator. Take this one as example: @extend_schema( # extra parameters added to the schema parameters=[ OpenApiParameter(name = "jwt_token", description="JSON Web Token", required=True, type=str), OpenApiParameter(name = "id", type = OpenApiTypes.STR, location=OpenApiParameter.PATH , description = "ID "), ], methods=["GET"], description = 'Return a serialized User', request = JWTRequestSerializer, responses = { 200: GenericResponseSerializer }, ) def retrieve(self, request, pk=None): I Have a lot of ViewSet for every Models that extends the Generic and override some methods to make it specific for the model. I need something like this for the Serializer in extend_schema. In the example, I have GenericResponseSerializer but I need every subclasses that extends this SuperClass, return its own specific Serializer. I've tried with a static method: @staticmethod def getRetrieveSerializer(): return GenericResponseSerializer() ... responses = { 200: getRetrieveSerializer }, ... It works well but it always return the SuperClasses method even if Im extending it. Unfortunally in decorator, I cant access self so I cant use a method that is overwritten at runtime. Is there a way to reach this goal? Maby with reflection? -
Django is not sending POST request
I am building a simple web app with Django and got into this weird situation. I want to delete an entry of a model but the html won't send any post request. delete.html {% extends 'main.html' %} {% block content %} <form method="POST" action=""> {% csrf_token %} <p> Are you sure to delete "{{obj}}" ?</p> <a href="{{request.META.HTTP_REFERER}}">GO BACK </a> <input type="submit" value="Confirm"> </form> {% endblock %} View for delete.html in views.py def delete_room(request, pk): room = Room.objects.get(id=pk) if request.method == 'POST': room.delete() return redirect('home') return render(request, 'base/delete.html', {'obj':room}) Model in models.py class Room(models.Model): host = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) topic = models.ForeignKey(Topic, on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=200) description = models.TextField(null=True, blank=True) # participants = created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return self.name class Meta: ordering = ['-updated', '-created'] urls.py from django.urls import path from . import views urlpatterns = [ path('', views.home, name='home'), path('room/<str:pk>', views.room, name='room'), path('create-room/', views.create_room, name='create-room'), path('update-room/<str:pk>', views.update_room, name='update-room'), path('delete-room/<str:pk>', views.delete_room, name='delete-room'), path('about/', views.about, name='about'), ] I've tried sending POST request from other templates and it woorks fine like adding new rooms and updating existing ones. When I click on Confirm, it shows nothing in terminal. -
Issue with swagger docs in django views
I have a view in my django project like this class SampleView(MixinPermissionsByAction, MixinSerializerByAction, generics.ListCreateAPIView): serializer_class = SampleCreateSerializer permission_classes = (IsAuthenticated) permissions_by_action = {"POST": (SomePermission,)} serializer_by_action = {"GET": SampleListSerializer} filter_backends = [DjangoFilterBackend, SearchFilter, OrderingFilter] filterset_fields = ["status"] ordering_fields = ["-updated", "-created"] search_fields = [ "name", ] queryset = None throttle_classes = [SomeThrottling] def get_queryset(self): <get request logic here....> in my serializers.py class i have two serializers. one for get rquest and other for post request class SampleListSerializer(serializers.ModelSerializer): <some fields here> class Meta: model = MyModelName exclude = <fields to be excluded> class SampleCreateSerializer(serializers.ModelSerializer): <some fields here> class Meta: model = MyModelName fields = "__all__" def create(self, validated_data): <logic for post request> I want to add get and post methods in swagger docs and tried following added @method_decorator above SampleView but it did not worked added @swagger_auto_schema above get_queryset method in view class and create method in SampleCreateSerializer here is my swagger implementation schema_view = get_schema_view( openapi.Info( title="My API", default_version="v1", description="API documentation for MyAI", ), public=True, permission_classes=(permissions.IsAdminUser, ), authentication_classes=(SessionAuthentication, ), ) and in urlpatterns path('docs/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui') Need help here to implement swagger on my above views. I have tried different stuff that i mentioned above but it did not work. … -
Setting minimum-width in line [Django]
Consider class MyTable(tables.Table): name = tables.Column(attrs={'cell': {'min-width': '200px'}}) Is this the right syntax for setting the minimum width of the 'name' column to 200px? This doesn't work on my machine. The 'name' column doesn't respond to variations in the min-width. -
Why are `connection.wait psycopg` suddenly high?
I noticed that my django tests became slow so I profiled them using pyinstrument. I noticed that connection.wait psycopg/connection.py:949 were taking a lot more time than before. So I focused on profiling this chunk of code that just does 2 queries: def test_foo(self): from pyinstrument import Profiler profiler = Profiler() profiler.start() foos = Foo.objects.filter(status=True) nb_foos = foos .count() first_foo = foos.first() profiler.stop() profiler.print() And the results are: BEFORE: 0.005 foo.py:93 ├─ 0.004 BaseFooQuerySet.first django/db/models/query.py:1050 │ [27 frames hidden] django, inspect, psycopg │ 0.001 Connection.wait psycopg/connection.py:949 └─ 0.001 BaseFooQuerySet.count django/db/models/query.py:597 [6 frames hidden] django AFTER: 0.543 foo.py:62 ├─ 0.275 BaseFooQuerySet.count django/db/models/query.py:597 │ [9 frames hidden] django, psycopg │ 0.274 Connection.wait psycopg/connection.py:949 └─ 0.268 BaseFooQuerySet.first django/db/models/query.py:1050 [10 frames hidden] django, psycopg 0.266 Connection.wait psycopg/connection.py:949 It's 100x slower. It's running on the same python env (python version and requirements). Python 3.11.3 Django==4.2.4 psycopg==3.1.9 psycopg-c==3.1.9 psycopg-pool==3.1.7 The "before" version is using an old commit so obviously something changed in my code then but what could this be to have such an impact on the db connection? -
Django custom filter - to convert datetime
I am working on a Django app and need to show datetime on the UI. the datetime is UTC format and I need to convert it into local timezone of the user. for this I implemented this custom filter in my app from django import template import pytz register = template.Library() @register.filter def convert_to_localtime(value, user_tz): if not value: return value local_tz = pytz.timezone(user_tz) local_time = value.astimezone(local_tz) print("Conversion function",value, local_time) return local_time In the template I am using this custom filter like this {%load custom_filters%} <span class="text-center match-date-time">{{ match.start_time|convert_to_localtime:user_tz}}</span> I can see that the custom filter is executing and converting datetime properly into local timezone as I can see following output for the print statement Conversion function 2023-08-03 17:30:00+00:00 2023-08-03 23:00:00+05:30 But on the UI I still the UTC datetime rather than the converted time. What am I missing? -
Django Edited images not showing up after processing in views
The website allows user to upload an image and will be edited and shown to the user. (learning to use Pillow for image editing). It gives no error in the terminal, the images are getting saved, but not showing up after edit. Is there issue with how the image is generating? Or in the javascript? Terminal also looks fine, showing this: [03/Aug/2023 15:28:32] "GET / HTTP/1.1" 200 1445 [03/Aug/2023 15:28:37] "POST / HTTP/1.1" 200 1521 index.html: <!DOCTYPE html> <html> <head> <title>Image Editor</title> <style> img { max-width: 400px; max-height: 400px; } </style> </head> <body> <h1>Image Editor</h1> <form action="{% url 'edit_image' %}" method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="image_file" id="image_file" onchange="previewImage(event)"> <input type="submit" value="Upload and Edit"> </form> <div id="imagePreview"> <h2>Uploaded Image Preview:</h2> <img id="preview" src="" alt="Uploaded Image"> </div> {% if edited_image %} <h2>Edited Image:</h2> <img src="{{ edited_image.url }}" alt="Edited Image"> {% endif %} <script> function previewImage(event) { const fileInput = event.target; const imagePreview = document.getElementById("imagePreview"); const preview = document.getElementById("preview"); if (fileInput.files && fileInput.files[0]) { const reader = new FileReader(); reader.onload = function (e) { preview.src = e.target.result; }; reader.readAsDataURL(fileInput.files[0]); imagePreview.style.display = "block"; } else { preview.src = ""; imagePreview.style.display = "none"; } } </script> </body> </html> views.py: from django.shortcuts import render … -
Time Limit not Working for Django Celery 5.3.1
I am having a trouble with trying time_limit and soft_time_limit feature in celery and django app. import os from celery import Celery # Set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'server.settings') app = Celery('server') # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') app.conf.update( task_soft_time_limit=1, task_time_limit=1, ) # Load task modules from all registered Django apps. app.autodiscover_tasks() @app.task(bind=True, ignore_result=True) def debug_task(self): print(f'Request: {self.request!r}') I have this celery configuration. I'm trying time limit config with for celery task in django and run this task. from celery import shared_task from celery.exceptions import SoftTimeLimitExceeded from celery.signals import task_success, task_failure, task_prerun import time from server.celery import app shared_task def scrape(domain: str, route: str = None): try: time.sleep(5) except SoftTimeLimitExceeded: print("Time Limit") @task_prerun.connect(sender=scrape) def scrape_prerun_notifier(task_id=None, task=None, *args, **kwargs): print("From task_prerun_notifier ==> Running just before add() executes") @task_success.connect(sender=scrape) def scrape_success_notifier(sender=None, result=None, **kwargs): print("Success") task_id = sender.request.id @task_failure.connect(sender=scrape) def scrape_failure_notifier(task_id=None, exception=None, *args, **kwargs): print("Failure") How ever, the scrape task always succeed without catching any exception. I've also tried modifying the decorator but it doesn't work either. @app.task(soft_time_limit=1, … -
Choices not being rendered in template
Working in Django. I've added choices and the necessary field in my model. The choices are well populated in the admin site, but not rendered in the template. I've double checked several times and everything seems right so I don't understand why the choices aren't rendered in the template. Could it be related to the CSS? I'm using materialize. I've added the .input-field class and initialized the select element as per the materialize documentation. Nothing changed. This is my code: model: class Grocery(models.Model): """ Model to create a grocery_list """ CATEGORIES = [("groceries", "Groceries"), ("school", "School"), ("hardware", "Hardware"), ("travel", "Travel"), ("gifts", "Gifts"), ("decoration", "Decoration"), ("lifestyle", "Lifestyle"), ("wishlist", "Wishlist")] name = models.CharField(max_length=500, default='My grocery list') category = models.CharField(max_length=20, choices=CATEGORIES, default='Shopping') form: class GroceryForm(forms.ModelForm): """ Form to create a grocery shopping list """ class Meta: model = Grocery fields = ['name', 'category', 'shop', 'item'] template: {% block title %}Create shopping list{% endblock %} {% block content %} <div class="container row"> <div class="col s10 m8 push-s1 push-m2"> <h1 class="center-align">Create a grocery shopping list</h1> <div class="divider"></div> <div class="input-field section"> <form method="POST"> {% csrf_token %} {{ form.media }} {{ form.as_p }} <button type="submit" class="waves-effect btn">Create list</button> </form> </div> </div> </div> {% endblock %} JS // … -
TinyMCE data setting issue
Actually i am trying setup data in tinyMCE editor. But, before the tinyMCE editor gets its initialization, function which set data in tinyMCE calls. So, when tinyMCE is loaded, it is with null data. Actually in one page i have around 10-12 editors. At first i started directly form data to load into tinyMCE from serverside in python django. But, it generates missing of data in some of the last editors. So, I decided to set data from client side through javascript. But I could not able to handle that my data setting function call, after the initialization of tinyMCE. So, please help to handle missing data in some of editors. -
celery running issue on raliway
inside the Procfile of my django app im using this worker: celery -A project.celery worker (using Redis as broker) and using railway platform for hosting my application but after deployment application is crashing : error is something like this : /opt/venv/lib/python3.9/site-packages/celery/platforms.py:800: RuntimeWarning: You're running the worker with superuser privileges: this is absolutely not recommended! Please specify a different user using the --uid option. User information: uid=0 euid=0 gid=0 egid=0 warnings.warn(RuntimeWarning(ROOT_DISCOURAGED.format( suggest how to run the celery process efficiently on railway. -
ModuleNotFound error (Django), i am beginner in django
It was all working when i started the server first time without startapp. after i made an application and did some modifications in the application now the server is not starting. they only changes I made in views.py and urls.py Here is the log. PS E:\CS50\files\Django\demo> python manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.11_3.11.1264.0_x64__qbz5n2kfra8p0\Lib\threading.py", line 1038, in _bootstrap_inner self.run() File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.11_3.11.1264.0_x64__qbz5n2kfra8p0\Lib\threading.py", line 975, in run self._target(*self._args, **self._kwargs) File "C:\Users\Abdul Basit Khan\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\Abdul Basit Khan\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\django\core\management\commands\runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "C:\Users\Abdul Basit Khan\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\Users\Abdul Basit Khan\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\django\core\management\__init__.py", line 394, in execute autoreload.check_errors(django.setup)() File "C:\Users\Abdul Basit Khan\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\Abdul Basit Khan\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Abdul Basit Khan\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) ^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Abdul Basit Khan\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\django\apps\config.py", line 193, in create import_module(entry) File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.11_3.11.1264.0_x64__qbz5n2kfra8p0\Lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1204, in _gcd_import File "<frozen importlib._bootstrap>", line 1176, in _find_and_load File "<frozen importlib._bootstrap>", line 1126, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File … -
Formatting form's film with Boostrap and Django
I have a form which is generated by a model in Django made by text area, choice field, toggle field and so on like: class Test(models.Model): workerID = models.CharField(max_length=200, blank=True, null=True) dashboardURL = models.URLField(blank=True) centralinaVecchia = models.BooleanField(default=False) And I've styled the form with class StartWorker(ModelForm): class Meta: model = Test fields = ('testTitle', 'testDescription', 'centralinaVecchia') labels = { "testTitle": _("Titolo"), "testDescription": _("Descrizione"), "centralinaVecchia": _("Centralina Vecchia?"), } widgets = { 'testTitle': forms.TextInput(attrs={'class':'form-control'}), 'testDescription': forms.Textarea(attrs={'class':'form-control'}), 'centralinaVecchia': forms.CheckboxInput(attrs={'class':'form-check-input'}), The issue is that, if every single field is correctly formated one below the other, the check box is located in a weired way (see screenshot) I'm unabel to style it like the rest of the form. According to the documentation I need to add the checkbox inside a <div class="form-check"></div> but I do not know how to do it in Django -
Django - Gentella Theme
¿How can I create a new app on the django template called "Gentella"? I've tried searching and I' ve not found anything yet. Please help me!!. I know how to create a new app on django, but, the question is that when you create that app, you don' t see it on the panel in the UI of gentella. What I'm doing wrong? -
Django:Filter entries of combobox in template to foreign key
I am having trouble to find a solution to a problem of filtering entries of a combobox. Just to make it easy to understand my problem here an ERM of my models: and my Template looks like: Basicly the queryset for this template is resulting of the following code: class EquipmentinLocationAdd(CreateView): model = EquipmentInLocation form_class = EquipmentAddToLocationForm template_name = 'Procure/equipmentinlocation_add.html' def get_success_url(self): return reverse('equipmentinlocation_sys', kwargs={'pk':self.object.Institute_id}) def get_initial(self): qs = Institute.objects.get( id = self.kwargs['pk'] ) initial = {'Institute': qs} return initial Now I need to filter and restrict the entries of the combobox "Lot" only to the lots which belong to the same project as the institute. However, bringing two queries together in one template seems to be a challenge hard to solve. Need your help, please advise!!! -
Message is not sending in JavaScript WebSocket
I am trying to build a chat application using Django channels and WebSocket HTML code {% extends 'core/base.html' %} {% block title %} {{room.name}} | {% endblock %} {% block content %} <div class="p-10 lg:p-20 text-center"> <h1 class="text-5xl font-extrabold text-white drop-shadow-lg ">{{room.name}} </h1> </div> <div class="lg:w-2/4 mx-4 lg:mx-auto p-4 bg-white rounded-xl"> <div class="chat-messages space-y-3" id="chat-messages"> <div class="p-4 bg-gray-200 rounded-xl"> <p class="font-semibold">username</p> <p>lorem ipsum lolerem ipseum</p> </div> </div> </div> <div class="lg:w-2/4 mt-6 mx-4 lg:mx-auto p-4 bg-white rounded-xl"> <form action="" method="post" class="flex"> <input type="text" name="content" class="flex-1 mr-3 focus:outline-0" placeholder="Your message.." id="chat-message-input"> <button class="px-3 py-1 rounded-xl text-white bg-green-600 hover:bg-teal-700" id="chat-message-submit"> Send </button> </form> </div> {% endblock %} {% block scripts %} {{ room.slug|json_script:"json-roomname" }} {{ request.user.username|json_script:"json-username"}} <script> const roomName = JSON.parse(document.getElementById('json-roomname').textContent); const userName = JSON.parse(document.getElementById('json-username').textContent); const chatSocket = new WebSocket( 'ws://' + window.location.host + '/ws/' + roomName + '/' ); chatSocket.onmessage = function(e){ console.log('onmessage') const data = JSON.parse(e.data); if (data.message){ let html = '<div class="p-4 bg-gray-200 rounded-xl">'; html += '<p class="font-semibold">' + data.username + '</p>'; html += '<p>' + data.message + '</p> </div>'; document.querySelector('#chat-messages').innerHTML += html; }else { alert('The message was empty'); } } chatSocket.onclose = function(e){ console.log('onclose') } // document.querySelector('#chat-message-submit').onclick = function(e){ e.preventDefault(); const messageInputDom = document.querySelector('#chat-message-submit'); const message = messageInputDom.value; chatSocket.send(JSON.stringify({ … -
Django Admin ForeignKey issue,
The following are my models in Django. class Authors(models.Model): first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) total_books = models.IntegerField(default =0) class Book(models.Model): title = models.CharField(max_length=200) topic = models.CharField(max_length=200) author = models.ForeignKey(Authors, on_delete = models.CASCADE)` I want to use Admin platform to achieve: when I add a new Book, the total_books in related author add 1. Is there any way to solve it? I would appropriate it if someone help me. Can anyone give me some ideas? -
openai.error.InvalidRequestError: This is a chat model and not supported in the v1/completions endpoint. Did you mean to use v1/chat/completions?
Hi im new to chat gpt api and im trying to make a chatbot with it. I keep getting this error when i run my code: Internal Server Error: / Traceback (most recent call last): File "C:\Users\Nathan A\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Nathan A\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Nathan A\Downloads\finalproject\finalproject\django_chatbot\chatbot\views.py", line 23, in chatbot response = ask_openai(message) ^^^^^^^^^^^^^^^^^^^ File "C:\Users\Nathan A\Downloads\finalproject\finalproject\django_chatbot\chatbot\views.py", line 9, in ask_openai response = openai.Completion.create( ^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Nathan A\AppData\Local\Programs\Python\Python311\Lib\site-packages\openai\api_resources\completion.py", line 25, in create return super().create(*args, **kwargs) PS C:\Users\Nathan A\Downloads\finalproject\finalproject\django_chatbot> python manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). August 02, 2023 - 21:17:40 Django version 4.2.2, using settings 'django_chatbot.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. [02/Aug/2023 21:17:42] "GET / HTTP/1.1" 200 4265 Internal Server Error: / Traceback (most recent call last): File "C:\Users\Nathan A\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Nathan A\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Nathan A\Downloads\finalproject\finalproject\django_chatbot\chatbot\views.py", line 23, in chatbot response = ask_openai(message) ^^^^^^^^^^^^^^^^^^^ File "C:\Users\Nathan A\Downloads\finalproject\finalproject\django_chatbot\chatbot\views.py", line 9, in ask_openai response = openai.Completion.create( ^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Nathan A\AppData\Local\Programs\Python\Python311\Lib\site-packages\openai\api_resources\completion.py", line … -
How to handle NULL for Django DB Function Concat?
I want the query set to return concatenated string for address. I'm currently writing code like this: queryset = Place.objects.annotate( place_address= Concat('address__city', Value(', '),'address__state__name')) ) It return fine when city and state field is not empty. But it does not handle null value with this solution where the result could ended up: "Kuala Lumpur, " OR ", Selangor" OR ", " Is there a way to skip adding delimiter when the field in front is null? Thanks. -
Hide HTMX search results after option is selected
I have a search bar I created using HTMX and django forms that displays results correctly. I have a javascript selectOption() function filling the search bar with whatever the selected option is, but I am having trouble with the search results not going away after I select an option. Can this be handled through javascipt? Additionally, the search bar returns random results once I type something and then delete it, leaving it blank. Is there something I could fill into hx-trigger to fix this issue? See htmx tags below widget_attrs_nha_autosearch = { 'class': 'form-control', 'data-user-entry': 1, 'disabled': value.get('read_only'), 'hx-post': reverse('ng_django_pmp:nha-autosearch'), 'hx-target': '#results', 'hx-trigger': "keyup changed delay:500ms, search" } See search-results html below {% if results %} <ul class="list-group col-xs-12"> {% for part in results %} <li class="list-group-item d-flex justify-content-between align-items-center" onclick="selectOption('{{ part.manufacturer_part_number }}')">{{ part.manufacturer_part_number }}</li> {% endfor %} </ul> {% else %} <p>No search results</p> {% endif %} <script defer> function selectOption (partNumber) { const input = document.querySelector('#id_nha_override'); input.value = partNumber; } -
Django LIKE operation
I'm trying to send a query through Django python I also try to block any sql injection exploits Can someone explain to me how messaging is done LIKE Query for example "SELECT * FROM admin WHERE name LIKE '%myTitle%' It's easy to configure Query like this cursor.execute("SELECT * FROM admin WHERE name= %s", (_id, )); But when inserting %s Many errors are made when canceling %% From the text, for example SELECT * FROM admin WHERE name LIKE %s When Query Done it be like SELECT * FROM admin WHERE name 'MyTitle' It is being implemented correctly, but I want it to be set %% among %s LIKE SELECT * FROM admin WHERE name '%MyTitle%' Can someone explain to me how to solve this problem my Simple Script from django.db import connection title = "myTitle" query = "SELECT * FROM admin WHERE name LIKE %s" with connection.cursor() as cursor: cursor.execute(query, (title,))