Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python - Django, Cannot install mysqlclient using pip
I'm new to Django and I'm facing some issues installing mysqlclient for my application running this command pip install mysqlclient I'm getting an error ModuleNotFoundError: No module named 'pip._internal.operations.build.wheel_legacy' Traceback (most recent call last): File "C:\Users\Ahmad\AppData\Local\Programs\Python\Python38-32\lib\runpy.py", line 194, in _run_module_as_main return _run_code(code, main_globals, None, File "C:\Users\Ahmad\AppData\Local\Programs\Python\Python38-32\lib\runpy.py", line 87, in _run_code exec(code, run_globals) File "E:\Python-projects\web_project\venv\Scripts\pip.exe\__main__.py", line 7, in <module> File "e:\python-projects\web_project\venv\lib\site-packages\pip\_internal\cli\main.py", line 73, in main command = create_command(cmd_name, isolated=("--isolated" in cmd_args)) File "e:\python-projects\web_project\venv\lib\site-packages\pip\_internal\commands\__init__.py", line 104, in create_command module = importlib.import_module(module_path) File "C:\Users\Ahmad\AppData\Local\Programs\Python\Python38-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "e:\python-projects\web_project\venv\lib\site-packages\pip\_internal\commands\install.py", line 37, in <module> from pip._internal.wheel_builder import build, should_build_for_install_command File "e:\python-projects\web_project\venv\lib\site-packages\pip\_internal\wheel_builder.py", line 11, in <module> from pip._internal.operations.build.wheel_legacy import build_wheel_legacy ModuleNotFoundError: No module named 'pip._internal.operations.build.wheel_legacy' I have Python 3.8.3 and pip 20.2.3 what is the cause of this error and how can I solve it? -
Django : Can a user affect/change the view of another user?
So I am trying to implement a wheel of fortune into my website, wich can be spun by clicking on a button. Now, if one user spins the wheel I want that the wheel also spins for all the other users. How can I achieve that one user can affect the view of another user (like spinning the wheel for another user)? -
Retrievel of data from Django Redis Cache is taking great amount of time
I'm trying to use Redis in caching my data so that DB calls are reduced. But the time taken for retrieval from cache is much large than the time which I'm getting when fetching the records without caching. I'm trying to store the django queryset object which consist of around 28k+ records and it's only going to increase as the data increases in the Database. I'm using Django - 3.0 DRF - 3.10.3 django-redis - 4.12 redis - 3.5.3 CodeWise: here is my settings.py for setting default cache CACHES = { 'default': { 'BACKEND': 'django_redis.cache.RedisCache', 'LOCATION': [ f'redis://{REDIS_HOST}:{REDIS_PORT}/1', f'redis://{REDIS_HOST}:{REDIS_PORT}/2' ], 'OPTIONS': { 'CLIENT_CLASS': 'django_redis.client.ShardClient', 'CONNECTION_POOL_KWARGS': { 'max_connections': 100, 'retry_on_timeout': True }, 'PASSWORD': os.environ.get('REDIS_PASSWORD') } } views.py from rest_framework import viewsets from django.core.cache import cache from django.conf import settings from django.core.cache.backends.base import DEFAULT_TIMEOUT from rest_framework.response import Response CACHE_TTL = 60 * 1 class RecordsList(viewsets.ModelViewSet): __basic_fields = ('name', 'id') # queryset = Records.objects.all() serializer_class = RecordsNewSerializer http_method_names = ['get', 'post', 'put', 'delete'] filter_fields = __basic_fields search_fields = __basic_fields def get_queryset(self): if 'records' in cache: print('from cache') queryset = cache.get('records') else: print("Saving to Cache") queryset = Records.objects.all() # queryset = queryset[1:5] cache.set('records', queryset, timeout=CACHE_TTL) return queryset Here as you can see I'm saving … -
Best authentication way in django rest framework
I was using spring boot and my favorite way to authenticate users then was JWT, now i am learning django and there is a lot of ways to authenticate users and i am confused which one i should use, So what's the most common way to authenticate users in django? is it Basic authentication(Of course not), or built in auth token in django rest framework, or Djoser, or Oauth? I need to know the best way/the most popular way/the most way that used in real life applications? -
Private Chat Messaging django Such as facebook
I want to implement a private chat messaging app just like on linkedin or facebook as they have a chat bar on the bottom bar of the screen. I have created the chat application as a different app on the project as the user has to go the messages/ url in order to chat with the user, but in order to make chat boxes like that on facebook home page, do I have to make chat as a separate app or just make the chat app within my main app. I don't have any strategy to it. any help towards the approach would help alot. -
Django (DRF) Patch with composite key
I'm trying to update the model which has a composite key but I always run into a problem when the update itself is being run Here's the Model: class ProductOnClient(models.Model): productid = models.CharField(db_column='productId', max_length=255) clientid = models.ForeignKey(Host, models.DO_NOTHING, db_column='clientId') producttype = models.CharField(db_column='productType', max_length=16) targetconfiguration = models.CharField(db_column='targetConfiguration', max_length=16, blank=True, null=True) installationstatus = models.CharField(db_column='installationStatus', max_length=16, blank=True, null=True) actionrequest = models.CharField(db_column='actionRequest', max_length=16, blank=True, null=True) actionprogress = models.CharField(db_column='actionProgress', max_length=255, blank=True, null=True) actionresult = models.CharField(db_column='actionResult', max_length=16, blank=True, null=True) lastaction = models.CharField(db_column='lastAction', max_length=16, blank=True, null=True) productversion = models.CharField(db_column='productVersion', max_length=32, blank=True, null=True) packageversion = models.CharField(db_column='packageVersion', max_length=16, blank=True, null=True) modificationtime = models.DateTimeField(db_column='modificationTime') class Meta: db_table = 'PRODUCT_ON_CLIENT' unique_together = (('productid', 'clientid'),) The Serializer: class ProductOnClientSerializer(serializers.ModelSerializer): class Meta: model = ProductOnClient fields = "__all__" The View class ProductOnClientDetailView(generics.ListAPIView): queryset = ProductOnClient.objects.all() serializer_class = serializers.ProductOnClientSerializer def patch(self, request, clientid, productid): print("patch recevied") filter = { 'productid': productid, 'clientid': clientid } item = ProductOnClient.objects.filter(**filter)[0] ser = serializers.ProductOnClientSerializer(item, data=request.data, partial=True) if ser.is_valid(): ser.save() return JsonResponse(201, data=ser.data, safe=False) print(ser.errors) return JsonResponse(400, safe=False) When I send a request via patch with a json valid json body, I get a MySQL error that there's a duplicated error. django.db.utils.IntegrityError: (1062, "Duplicate entry '<productid>-<clientid>' for key 'PRIMARY'") Also the ProductID and ClientID is one string merge with … -
How to extend the Django auth.permissions model?
I have the following models. class Post(models.Model): content = models.TextField() class User(AbstractUser): pen_name = models.Charfield() I want to restrict a user to create a specific number of posts (let's say 10) and no more than that. Also, I want the permission to expire by a certain date. How can I extend the auth.permissions model to achieve this, for APIViews in DRF? -
Django RF 405 error for POST request on APIView without ending slash
I'm pretty new to Django Rest Framework and I've been investigating this issue but can't find any solution. I'm pretty sure it will be a small detail but I'm out of idea. I'm using DRF for a project. The team made the choice to not end URL paths with a ' / '. I have an endpoint linked to an APIView with a POST method. We want to do some stuff with a body sent in this POST. However calling it brings (Postman response): 405 Method Not allowed { "detail": "Method \"POST\" not allowed." } Putting a ' / ' at the end of the URL path works (Postman response for normal behavior): { "success": True, "message": "A message returned by the function in APIView" } urls.py from django.urls import path, include from runbook import views from rest_framework.routers import DefaultRouter router = DefaultRouter(trailing_slash=False) router.register(r'my_objects', views.ObjectViewset) urlpatterns = [ path('', include(router.urls)), path('my_objects/myFunction', views.MyFunctionView.as_view(), name="my-function") views.py class MyFunctionView(APIView): """ """ def post(self, request, format=None): try: MyObject.objects.get(slug=slugify(request.data['candidate_name'])) except MyObject.DoesNotExist: return Response(boolean_response(False)) else: return Response(boolean_response(True)) What I read and tried: Wrong type of view: 405 "Method POST is not allowed" in Django REST framework ; 405 “Method POST is not allowed” in Django REST … -
How to correctly setup Global Site Tag (gtag.js) for user_id tracking
I'm trying to implement user_id tracking on my website. I send emails to users with a user_id in their personal link which I need to track. As per the documentation I have added to gtag.js. gtag('config', 'MY_GA_MEASUREMENT_ID', { 'user_id': 'USER_ID' }); But when I go to my website with the following parameters ?user_id=1 I check my Tag Assistent to see which parameters are set and I see the following: uid = USER_ID And no mention at all of user_id or the value I supposedly gave to the parameter. I figured gtag would look for the value in the request but it looks like it accepts the value USER_ID as the string assigned in gtag.js. Does anyone have a clue about how to tackle this? -
Django REST Framework: Can you mix API views with template views?
I am developing a web application using Django and React, and using Django REST Framework to have them talk to each other. I am trying to create a Django view that could handle both AJAX requests from React code AND render Django HTML templates. To accomplish this, I am using the TemplateHTMLRenderer class from Django REST Framework that I found here. However, when I try to fetch() data from that view from React I do not receive any valid response. Here is my view: # URL: "/" class IndexView(APIView): renderer_classes = [TemplateHTMLRenderer] template_name = "dictionary/index.html" def get(self, request, format=None): definitions = Definition.objects.all() return Response({"definitions": definitions}) And here is how I am trying to fetch() datafrom React: componentDidMount() { fetch("/") .then(response => response.json()) .then(data => { this.setState({ definitions: data }); }, error => { this.setState({ alert('ERROR') }); }) } This code ends up displaying the alert "ERROR". Apparently, my view is not returning a valid JSON object. How can I change it to provide both rendering and API functionality? -
Django form of CreateView not accepting submission after setting default value
My django form made using CreateView is refusing to get submitted because of the inital value I prepopulated it with ( and which is correct ) This is my model : class Post(models.Model): #some code author = models.ForeignKey(User, on_delete=models.CASCADE) #some more code This is my view for the form : class AddPostView(CreateView): model = Post form_class = PostForm template_name = 'add_post.html' def get_initial(self): initial = super(AddPostView, self).get_initial() #Setting the inital value of author in the form to the username of the logged in user initial['author'] = self.request.user.username return initial And this is the form being referred by the above view class PostForm(forms.ModelForm): class Meta: model = Post fields = ('x','y', 'author', 'z', 'm') widgets = { #some code 'author': forms.TextInput(attrs={'class': 'form-control','readonly':'readonly' }), #some more code } Now , When I am trying to submit the form , I am getting the error Select a valid choice. That choice is not one of the available choices. Why is this happening?d -
Error with Pillow library when dockerinzing Django app
I develop Django apps in Windows environnement and deploy my apps in production in Linux server. Python 3.8.3 I have a Django project that works (in dev and prod) and I try to "dockerize" it but I got an error when installing requirements.txt error seems to come from pillow library but even if I remove the Pillow==6.2.1 it doesn't change below the tracelog error requirements.twt Django==2.2.5 django-bootstrap4==1.0.1 django-crispy-forms==1.7.2 django-debug-toolbar==2.0 django-extensions==2.2.9 django-maintenance-mode==0.15.0 django-partial-date==1.2.2 django-safedelete==0.5.2 django-simple-history==2.7.3 django-widget-tweaks==1.4.5 Pillow==6.2.1 python-gettext==4.0 pytz==2019.2 reportlab==3.5.32 selenium==3.141.0 six==1.12.0 soupsieve==1.9.3 sqlparse==0.3.0 urllib3==1.25.6 xlwt==1.3.0 Creating network "coverage_africa_default" with the default driver Building web Step 1/10 : FROM python:3.8.3-alpine ---> 8ecf5a48c789 Step 2/10 : WORKDIR /usr/src/app ---> Using cache ---> 6e7b9e258aae Step 3/10 : ENV PYTHONDONTWRITEBYTECODE 1 ---> Using cache ---> 130a8576b1fa Step 4/10 : ENV PYTHONUNBUFFERED 1 ---> Using cache ---> 6e32ad96bd91 Step 5/10 : RUN apk update && apk add postgresql-dev gcc python3-dev musl-dev ---> Using cache ---> c4010960001d Step 6/10 : COPY requirements/ requirements/ ---> 2591c3840465 Step 7/10 : RUN pip install --upgrade pip && pip install -r requirements/dev.txt ---> Running in defe0caa7725 Collecting pip Downloading pip-20.2.3-py2.py3-none-any.whl (1.5 MB) Installing collected packages: pip Attempting uninstall: pip Found existing installation: pip 20.1.1 Uninstalling pip-20.1.1: Successfully uninstalled pip-20.1.1 Successfully … -
I am rendering HTML template and sending context with it but in fetch response it is not reading that context and showing an error regarding JSON
I am sending context json object to template here in views.py all the things are working properly views.py def adminLogin(request): if request.method == 'GET': return render(request, 'admin/login.html') elif request.method == 'POST': data = request.POST username = data['username'] password = data['password'] user = authenticate(username=username, password=password) if user is not None and isAdmin(user.username): token, created = Token.objects.get_or_create(user=user) context = { "login" : "Done", "token" : token.key, "username" : user.username, "email" : user.email, } print("admin login done") context = dumps(context) return render(request, 'admin/login.html', {"context" : context}) else: print("login unseccesfull") return render(request, 'admin/not-login.html') the context i am catching in javascript and try to read context but i am failed to read that context even i am using JON.parse() and also JSON.stringify() both are not working Template HTML ` var loginForm = document.getElementById("adminLogin"); loginForm.addEventListener('submit', function(event) { event.preventDefault(); const formData = new FormData(this); const searchParams = new URLSearchParams(); for (var pair of formData) { searchParams.append(pair[0], pair[1]); } fetch('http://127.0.0.1:8000/my_admin/login/', { mode: 'cors', method: 'post', headers: { "Content-type": "application/x-www-form-urlencoded; charset=UTF-8" }, body: searchParams, }) .then(res => { var context = JSON.stringify("{{context|escapejs") if (context.login === "Done"){ localStorage.clear(); localStorage.setItem("username", context.username); localStorage.setItem("token", context.token); localStorage.setItem("email", context.email); localStorage.setItem("login", "done"); window.location.href = "http://127.0.0.1:8000/my_admin/"; } }) .catch(function(error) { console.log(error) alert("Something went wrong"); }); }) </script>` -
Django get checkbox data list from HTML
I'm pretty sure that this is something basic, but I'm not really sure on how to do this. Anyway, I'm trying to get all of the selected fields from my checklist, but for some reason, it only returns the last one. For some reason when i try to access the values at 'a' I only get the last value, as a string. TLDR; im getting 'a' variable as a string of 'Wont Print' And i need it to be a list of ['Won't Fail', 'Won't Print'] HTML: {% for q in mquestions %} <h4 class="card-title alert">{{q.text}}</h4> <div class="form-check"> <input class="form-check-input " type="checkbox" name="mult{{q.id}}" id="{{q.id}}" value="{{q.option1}}"> <label class="form-check-label " for="{{q.id}}"> {{q.option1}} </label> <br> <input class="form-check-input" type="checkbox" name="mult{{q.id}}" id="{{q.id}}" value="{{q.option2}}"> <label class="form-check-label" for="{{q.id}}"> {{q.option2}} </label> <br> <input class="form-check-input" type="checkbox" name="mult{{q.id}}" id="{{q.id}}" value="{{q.option3}}"> <label class="form-check-label" for="{{q.id}}"> {{q.option3}} </label> <br> <input class="form-check-input" type="checkbox" name="mult{{q.id}}" id="{{q.id}}" value="{{q.option4}}"> <label class="form-check-label" for="{{q.id}}"> {{q.option4}} </label> <br> </div> {% endfor %} Code part from the view: try: if 'mult' in a: print(request.POST) print(a) print(request.POST.get(a)) except: continue current result: <QueryDict: {'csrfmiddlewaretoken': ['odREEU3kXpGvYZnNHllCBrOS1r9rTFZvejEq5zMGP6t4jLrtw1HHPTmB5BbBOAQg'], 'mult1': ['Won't Fail', 'Won't Print'], 'Submit': ['Submit']}> mult1 Won't Print #### Need this to be ['Won't Fail', 'Won't Print'] -
Logging in view not done when run via pytest
When my methods in a View class are executed by pytest, the logging statements don't produce any outputs on the console. Is that expected behavior or am I missing something? This is the view: import logging from django.views import View logger = logging.getLogger(__name__) class FancyWebhook(View): def post(self, request, *args, **kwargs): logger.info("DUMMY logging") print("DUMMY printing") return HttpResponse(status=200) The logging configuration in configs/settings/test.py: # ... LOGGING = { "version": 1, "disable_existing_loggers": False, "handlers": { "console": {"class": "logging.StreamHandler"}, }, "loggers": { "django": { "handlers": ["console"], "level": os.getenv("DJANGO_LOG_LEVEL", "INFO"), }, }, } The test method: import pytest @pytest.mark.django_db def test_fancy_webook_empty_payload_fails(client): print("calling client.post()...") response = client.post('/pricing/fancywebhook', {}, content_type='application/json') assert response.status_code == 403 Running the test via pytest --ds=config.settings.test only prints the error that assert 301 == 403 to the console, but neither the "DUMMY logging" nor the "DUMMY printing" statements. I'm surely missing the obvious, am I not? -
Python / Django Users Profile Page URL Turkish Character Problem
Its working on my localhost. But my server (centos 7-plesk) dosn't wok same code. Example My user profile link: domain.com/user/Maşuka This link working on my localhost without any problem. But this link auto redirect like this and i give 404 error page: domain.com/user/Ma%25c5%259fuka/ where is problem? How can i fix this. What's the difference between localhost and centos? Why working good only localhost. -
Django Celery Progress Bar
I'm using Celery in my Django project and I'm trying to add a progress bar for the status of the progress of the upload of my data. The script is just a simple API upload script. On the celery Git Hub they provide you with a example with a FOR loop using seconds. However, this is hard coding a time frame on the progress bar than actually pulling the status of the actual function in real time. So my question is, how do I make the progress bar pull the actual status of the script ? Id imagine some sort of Java Script will be needed for this. I am not by any means a Java Script expert. So I appreciate any help everyone can give me on this. Thank you so much ! API SCRIPT def ImportSchools(): AuthTokenP() print("Getting school data from SIS") url = "" payload = {} token = APIInformation.objects.get(api_name="PowerSchool") key = token.key headers = {'Authorization': 'Bearer {}'.format(key)} response = requests.request("GET", url, headers=headers, data = payload) encode_xml = response.text.encode('utf8') pretty_xml = xml.dom.minidom.parseString(encode_xml) pretty_xml_str = pretty_xml.toprettyxml() xml_string = ET.fromstring(encode_xml) schools = xml_string.findall("school") for school in schools: psid = school.find("id").text name = school.find("name").text school_number = school.find("school_number").text low_grade = school.find("low_grade").text … -
Django incorrect filename encoding on uploading file in FileField
I am uploading a file using ajax with non-ascii characters (hindi). After uploading, the filename saved is incorrect, instead of संज्ञा it shows सजञ. Models.py - class PostFile(models.Model): file = models.FileField(upload_to='posts/files/%Y/%m/%d') timestamp = models.DateTimeField(auto_now_add=True) views.py - def ajax_add_post_file(request): file = request.FILES['file'] print(file.name.encode()) # get correct filename encoding model_object = PostFile.objects.create(file=file) print(connection.queries[-1]['sql'].encode()) # get sql which gives the following output on terminal - b'\xe0\xa4\xb8\xe0\xa4\x82\xe0\xa4\x9c\xe0\xa5\x8d\xe0\xa4\x9e\xe0\xa4\xbe.pdf' b'INSERT INTO "posts_postfile" ("file", "timestamp") VALUES (\'posts/files/2020/09/21/\xe0\xa4\xb8\xe0\xa4\x9c\xe0\xa4\x9e.pdf\', \'2020-09-21T12:23:02.184338+00:00\'::timestamptz) RETURNING "posts_postfile"."id"' As you can see, the filename encoding of both the files is different. I am using Django 1.11, python 3, postgres 10 with UTF8 encoding database. How to resolve this? -
Why v-model not working when used in vue.extend?
I have a page structure similiar to this: <main id="app"> <div id="mount-place"></div> </main> <script type="text/x-template" id="my-template"> ...some code here... <input type="text" v-model="address"> ...some other code here... </script> <script> var ExtendedElement = Vue.Extend({ template: '#my-template', data: function() { return { address: {{ some_address|safe }}; // gets values from django } }, mounted: function() { console.log(this.address); // Works just fine } }); new ExtendedElement.$mount('#mount-place'); </script> ...some unimportant logic here... <script> const app = new Vue({ delimiters: ['[[', ']]'], el: '#app' }); </script> And the problem is it renders just fine, but v-model not working i.e. input shows nothing. When accessing it via console it shows values inside vue object. No errors or warnings. -
Why do we use tests.py in django ? or Why need tests?
Explain pls. I am a beginner in this project. I'm reading a book about Django and I didn't understand about test.py -
Aggregating a subquery with multiple OuterRefs in Django
I'm trying to solve an N+1 selects issue. Currently, the code looks something like this, somewhat simplified - the code is really in a DRF serializer and does some other things: for payment in Payment.objects.filter(...): refunds_total = Payment.objects.filter( batch__merchant=obj.batch.merchant, payment_id=obj.id, payment_type="refund", status="success", ).exclude( tab__is_void=True, ).aggregate( total=Sum('amount') ).get('total', 0.0) # Do something with refunds_total. The performance is really bad. What I'd like to do is something like this: refunds = Payment.objects.filter( batch__merchant=OuterRef("batch__merchant"), payment_id=OuterRef("id"), payment_type="refund", status="success", ).exclude( tab__is_void=True ).aggregate(total=Coalesce(Sum("amount"), 0.0)) return Payment.objects.filter( ... ).annotate(total_refunds=Subquery(refunds)) But Django doesn't allow aggregating in a subquery, as aggregating immediately evaluates the QuerySet. I've tried two approaches. The first is following this documentation. However, I'm not sure how I need to put the query together as there are multiple OuterRefs required. My first shot at a subquery looks like this: refunds = CustomerPayment.objects.filter( batch__merchant=OuterRef("batch__merchant"), payment_id=OuterRef("id"), payment_type="CreditRefund", status="success", ).exclude( tab__is_void=True ).order_by().values( "batch__merchant", "payment_id", ).annotate(total_refunds=Coalesce(Sum("amount"), 0.0)).values("amount") But however I try to get it working, it always returns multiple rows rather than single row with the total, so I can't use it in a subquery. I've also tried making my own Subquery subclass but I couldn't put together anything that worked. -
Django channels: what is an efficient way to implement chat notification system?
Currently I am working on a chat system using django channels and I am not able to find an efficient way to implement chat notification system. Can someone please help me. Any idea is appreciated :) So my problems are how can server notify clients if new messages has arrived when they are not in a chat view ? if we use websocket to send new messages from server to client, does it mean, whenever user is logged in one websocket channel is open for each user ? -how many simultaneous websocket channels/connections can django channels support? do we need to have separate websocket channels for chat notifications and sending actual chat messages? It would be great if someone can share their experiences :) :) - Thank you -
Getting error "Uncaught SyntaxError: Unexpected token o in JSON at position 1" in the front-end
I hope all are fine and safe! I am trying this below requirement where there is a voice synthesizer and it converts my voice (which is a question) into a text and it sends that text to the back-end Django through Ajax. I can see that the backend Django is able to get the value from the front-end and using that to get the value from the db and returning it to the front-end(status code is showing as 200 63) But the problem is that at the ajax success part its not getting the value from the back-end and displaying/speaking it. I am sharing both front-end and the back-end part of the requirement. def Answer(request): if request.method=='GET' and request.is_ajax(): question_asked=str(request.GET.get("message_now")) try: answer=QuestionAnswer.objects.filter(question=question_asked).values_list('answer', flat=True)[0] #data={"data1":answer} print(answer) return JsonResponse({"success": True, "data": answer}, status=200) except Exception as e: print(e) return JsonResponse({"success": False}, status=400) else: print("Not Suceess") function chatbotvoice(message){ const speech = new SpeechSynthesisUtterance(); if(message!==null && message!==''){ $.ajax({ url: "http://127.0.0.1:8000/getanswer", dataType: 'json', type: 'GET', data: { message_now:message }, success: function (data) { var yourval = JSON.parse(data); speech.text=yourval; window.speechSynthesis.speak(speech); chatareamain.appendChild(showchatbotmsg(speech.text)); }, error: function(error){ speech.text = "Oh No!! I don't Know !! I am still learning!! Your question got recorded and answer for your question will … -
def __str__(self) issue - Django
I'm trying to print the title of the first object in my DB in django. However, when I enter the command Project.objects.all() in the shell, it just returns the following: <QuerySet [<Project: Project object (1)>]> This is my code: # Create your models here. class Project(models.Model): title = models.CharField(max_length=100) progress = models.FloatField(default=0) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self.title): return self.title class Task(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) title = models.CharField(max_length=100) priority = models.SmallIntegerField(default=0) open_date = models.DateTimeField() close_date = models.DateTimeField() status = models.SmallIntegerField(default=0) def __str__(self.title): return {self.title} The str part doesn't seem to be doing anything, even when I purposely misspell something, no error is returned. There seems to be a few threads with similar issues with no accepted solutions as of yet. I would like it to return the title that I've entered, which should be <QuerySet [<Project: My First Project>]>. Thanks in advance for your help. -
Hwo to convert array into Comma Saperated string in python?
I Have following Array in python, [4,5,6] i want my output as ['4','5','6'] How to Do that?