Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
razorpay and environ is not importing
I installed all of these but not importing, can you tell me why? I'm using python versin Python 3.9.5... django-environ 0.10.0 django-razorpay 1.1.6 razorpay 1.3.0 whenever I go to omport I get an error like, "environ" is not accessedPylance Import "environ" could not be resolvedPylance and, "razorpay" is not accessedPylance Import "razorpay" could not be resolvedPylancereportMissingImports import environ import razorpay can you please tell me where It occuring? Somewhere I got razorpay is not suitable for python version 3.9, is it true? Can you please guide me on how to integrate Razorpay payment with Django rest framework? -
Timestamp updating value over every item in a list rather than each one
I have two Django classes representing two different lists: models.py class Playinglist(models.Model): title = models.CharField(max_length=200) user = models.CharField(max_length=64) game_id = models.IntegerField() started_on = models.DateTimeField(auto_now=True) class Playedlist(models.Model): title = models.CharField(max_length=200) user = models.CharField(max_length=64) game_id = models.IntegerField() finished_on = models.DateTimeField(auto_now=True) And two functions that add data from one list to another: views.py def add_to_playinglist(request, game_id): obj = Playinglist.objects.filter(game_id=game_id, user=request.user.username) if obj: obj.delete() game = Game.objects.get(id=game_id) playing_game = Playinglist.objects.filter(game_id=game_id, user=request.user.username) return redirect("profile") else: obj = Playinglist() obj.user = request.user.username obj.game_id = game_id obj.save() game = Game.objects.get(id=game_id) playing_game = Playinglist.objects.filter(game_id=game_id, user=request.user.username) return redirect("profile") def add_to_playedlist(request, game_id): obj = Playedlist.objects.filter(game_id=game_id, user=request.user.username) if obj: obj.delete() game = Playinglist.objects.get(game_id=game_id) played_game = Playedlist.objects.filter(game_id=game_id, user=request.user.username) return redirect("profile") else: obj = Playedlist() obj.user = request.user.username obj.game_id = game_id obj.save() game = Playinglist.objects.get(game_id=game_id) game.delete() played_game = Playedlist.objects.filter(game_id=game_id, user=request.user.username) return redirect("profile") And to organize/display that data I am using this function: def profile(request): playinglist = Playinglist.objects.filter(user=request.user.username) playinglist_items = [] playing = 0 present_in_playinglist = False if playinglist: for item in playinglist: try: game = Game.objects.get(id=item.game_id) playinglist_items.append(game) present_in_playinglist = True playing += 1 playinglist = Playinglist.objects.get(id=item.game_id) except: present_in_playinglist = False playedlist = Playedlist.objects.filter(user=request.user.username) playedlist_items = [] finished = 0 present_in_playedlist = False if playedlist: for item in playedlist: try: game = Game.objects.get(id=item.game_id) playedlist_items.append(game) … -
upload file with rest api in function based view django
i want to create a file upload file rest api and need to call the rest api in django templates which has upload button option. I am confused in writing exact code for it rest api - view.py def uploadfile(request): message={"status":"uploaded"} try: file=request.FILES['fileuploaded'] message={"status data":"uploded and parsing started"} return Response(message,status=200) except: return Response(message,status=400) django - views.py def fileapicall(request): cont={} if request.method == "POST": context = request.method.POST.get("http://localhost:8000/apidata/") return render(request,'result.html',context) template file <form method='post' enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="filename"> <button type="submit"> upload </button> </form> i wana upload file and display the uploaded file in template (django) to api cal and read that file and display it in template (django). -
Why Django Rest_Framework Response() not setting cookies on my browser but works perfectly fine using postman?
I don't understand this bug or issue. So, i am building an application using Django Framework as the server and Angular as the client side. And consider using JWT on the server side. At first, i was testing Log in api(server) using Postman, works fine when log in and creating cookies and token however. When testing using any browser, then i don't get to see the cookies being set. By the way i am using djangocorsheader and jwt packages. I'll leave my views.py and client side. Also, I'd research and saw a few answers on youtube and here but no luck. The only issue i could think of is either my browser or i need to set something on Django side. Please help, any help appreciate it. Client Side (app-http, set up) app-http.service.ts import { throwError as observableThrowError, throwError } from 'rxjs'; import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders, HttpParams, HttpErrorResponse } from '@angular/common/http'; import { catchError, map, tap } from 'rxjs/operators'; import { LocalStorageService } from '../localStorage/local-storage.service'; import { environment } from '../../../environments/environment'; import { Router } from '@angular/router'; @Injectable({ providedIn: 'root' }) export class AppHttpService { public hostUrl = environment.API_URL; constructor( public localStorageService: LocalStorageService, public … -
django_tenants not resolving subdomains
I have setup and installed django_tenants with the standard settings and middleware from the documentation and watched Tom's Youtube video. 'django_tenants.middleware.main.TenantMainMiddleware' and the option SHOW_PUBLIC_IF_NO_TENANT_FOUND = True The PostgresSQL scheme segregation is working perfectly and I have created a demo tenant with host demo.localhost I am running the server locally with python3 manage.py runserver localhost:8000 in my browser, localhost:8000 works perfectly however the subdomain, demo.localhost:8000 is never resolved and I see no request in the terminal. Is there something I am missing or logs I can check to try and troubleshoot? -
FATAL: role "root" does not exist while running docker-compose up
I have a Django project and I need to create Docker for that project. Here is my code of docker-compose.yaml file version: "3.2" services: web: image: tdsp:latest build: context: . dockerfile: Dockerfile expose: - 9090 ports: - "9090:9090" volumes: - .:/app - /var/run/docker.sock:/var/run/docker.sock environment: DEPLOYMENT: api COMPOSE_HTTP_TIMEOUT: 3600 LC_CTYPE: en_US.UTF-8 LANG: en_US.UTF-8 LC_ALL: en_US.UTF-8 DEBUG: "True" depends_on: postgres: condition: service_healthy stdin_open: true tty: true env_file: .env restart: always command: bash -c 'python3 src/tdsp/manage.py runserver 0.0.0.0:9090' networks: pgnet: nginx: build: ./nginx/ volumes: - ./src:/data/src - ./nginx/sites-enabled:/etc/nginx/conf.d - ./nginx/passwd:/etc/nginx/passwd environment: COMPOSE_HTTP_TIMEOUT: 3600 links: - web:web networks: pgnet: postgres: image: postgres:alpine volumes: - postgres_data:/var/lib/postgresql/data/ env_file: - .env expose: - 5432 ports: - "5432:5432" healthcheck: test: [ "CMD-SHELL", "pg_isready" ] interval: 5s timeout: 5s retries: 5 networks: pgnet: volumes: postgres_data: networks: pgnet: After running sudo docker-compose up I got these errors and warnings: Recreating tdsp_postgres_1 ... done Recreating tdsp_web_1 ... done Recreating tdsp_nginx_1 ... done Attaching to tdsp_postgres_1, tdsp_web_1, tdsp_nginx_1 postgres_1 | postgres_1 | PostgreSQL Database directory appears to contain a database; Skipping initialization postgres_1 | nginx_1 | /docker-entrypoint.sh: /docker-entrypoint.d/ is not empty, will attempt to perform configuration nginx_1 | /docker-entrypoint.sh: Looking for shell scripts in /docker-entrypoint.d/ postgres_1 | 2023-04-05 18:20:00.664 UTC [1] LOG: … -
Choosing The Right TechStack
I am undergoing a bootcamp for web developer and i am about to finish the bootcamp, and for a graduation project,I am thinking about building a sports-betting app/website that uses the blockchain technology(solidity smart contracts),I would also like to incorporate the power of A.I to make some recommendations on the bets for premium users, what type of technologies/techstack would you recommend me to use? and also which currency do you recommend me to use? for the frontend and the backend. During this bootcamp i learned HTML,CSS,JavaScript,Node.js,PHP,Laravel,Mysql,MongoDb and React. i've been advised to use djando in the backend and next js in the fornetend, is this a good advice? -
Django MySql backend errors when getting features from Sphinxsearch
Django MySql backend tries to evaluate MySql settings every time it uses a connection and cannot convert an empty string, that is being returned to an integer. When it does so it throws an error as follows (in this example I am just running manage migrate command): root@2d37585a3d96:/mealplanner/trunk# python manage.py migrate Traceback (most recent call last): File "manage.py", line 11, in <module> execute_from_command_line(sys.argv) File "/py36-default/lib/python3.6/site-packages/django/core/management/init.py", line 381, in execute_from_command_line utility.execute() File "/py36-default/lib/python3.6/site-packages/django/core/management/init.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/py36-default/lib/python3.6/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/py36-default/lib/python3.6/site-packages/django/core/management/base.py", line 361, in execute self.check() File "/py36-default/lib/python3.6/site-packages/django/core/management/base.py", line 390, in check include_deployment_checks=include_deployment_checks, File "/py36-default/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 64, in runchecks issues = run_checks(tags=[Tags.database]) File "/py36-default/lib/python3.6/site-packages/django/core/checks/registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "/py36-default/lib/python3.6/site-packages/django/core/checks/database.py", line 10, in check_database_backends issues.extend(conn.validation.check(**kwargs)) File "/py36-default/lib/python3.6/site-packages/django/db/backends/mysql/validation.py", line 9, in check issues.extend(self._check_sql_mode(**kwargs)) File "/py36-default/lib/python3.6/site-packages/django/db/backends/mysql/validation.py", line 13, in checksql_mode with self.connection.cursor() as cursor: File "/py36-default/lib/python3.6/site-packages/django/db/backends/base/base.py", line 256, in cursor return self._cursor() File "/py36-default/lib/python3.6/site-packages/django/db/backends/base/base.py", line 233, in _cursor self.ensure_connection() File "/py36-default/lib/python3.6/site-packages/django/db/backends/base/base.py", line 217, in ensure_connection self.connect() File "/py36-default/lib/python3.6/site-packages/django/db/backends/base/base.py", line 197, in connect self.init_connection_state() File "/py36-default/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 231, in init_connection_state if self.features.is_sql_auto_is_null_enabled: File "/py36-default/lib/python3.6/site-packages/django/utils/functional.py", line 80, in get res = instance.dict[self.name] = self.func(instance) File "/py36-default/lib/python3.6/site-packages/django/db/backends/mysql/features.py", line 83, in is_sql_auto_is_null_enabled cursor.execute('SELECT @@SQL_AUTO_IS_NULL') File "/py36-default/lib/python3.6/site-packages/django/db/backends/utils.py", line … -
Incorrect syntax near 'OUTPUT' while running Django migrations with mssql-django
I am currently trying to connect my Django application to a MSSQL database. I'm using the mssql-django package and am able to run make migrations, however when I run migrate I get an error when it attempts to insert the first row into the django_migrations table. The error recieved is: pyodbc.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Incorrect syntax near 'OUTPUT'. (102) (SQLExecDirectW); [42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Statement(s) could not be prepared. (8180)") If I print out the SQL constructed by the mssql-django package, it looks something like this before the paramaters are inserted: INSERT INTO [backdrop_django_migrations] ([app], [name], [applied]) VALUES (?, ?, ?) OUTPUT INSERTED.[id] As far as I know, this is incorrect syntax and the OUTPUT clause should go before the VALUES. I briefly attempted to figure out if I could hack the library to change it but wanted to see if anyone else has experienced this. I don't see anything in the docs, I've tried changing versions, but I'm within the supported versions and still having issues. Django: 3.2 mssql-django: 1.2 python:3.7.4 SQL Server: 2019 Express OS: Windows 10 -
django queryset annotate and order_by. order_by('quantity') splits results
I'm making this queryset in Django. My goal is to list the Top 10 best selling products. The query works and Sum the two products with the same name. top_10_ordered_products = OrderedProduct.objects.filter(order__in=current_month_orders, vendor=vendor).values('product__product_name').annotate(qty=Sum('quantity')).order_by() Result: <QuerySet [{'product__product_name': 'Café Expresso', 'qty': 10}, {'product__product_name': 'Pão de nozes', 'qty': 15}]> But when adding the order_by('quantity') it separates the summed items in two. One with 10 units and the other with 5. top_10_ordered_products = OrderedProduct.objects.filter(order__in=current_month_orders, vendor=vendor).values('product__product_name').annotate(qty=Sum('quantity')).order_by('-quantity') Result: <QuerySet [{'product__product_name': 'Café Expresso', 'qty': 10}, {'product__product_name': 'Pão de nozes', 'qty': 10}, {'product__product_name': 'Pão de nozes', 'qty': 5}]> Does anyone know how if it is possible to use the order_by without dismembering the same product_name in the query in these case? -
Python Keyword Arguments behaving differently when taking Default Values
Python Version: 3.8.10 Django Version: 3.1.7 I have a recursive classmethod which walks through a JSON to find any 'Errors' keys and tracks where it was found to help troubleshooting. However, I was seeing that when Errors were not found by getErrorsFromResponse, the function was returning the last value of 'errorMap' which DID have values and I cannot figure out why. When specifying the loc & errorMap values when calling the function, it works fine. But, when allowing python to use the default values specified in the function definition, it has the issue. Can anyone explain why this would happen? I feel like I'm completely misunderstanding how Python works if this doesn't behave. The Method in Question: @classmethod def getErrorsFromResponse(c, response, loc=[], errorMap={}): if type(response) is dict: if "Errors" in response: err = response["Errors"] if len(err) > 0: errorMap[".".join([*loc, "Errors"])] = err else: for k, v in response.items(): c.getErrorsFromResponse(v, loc=[*loc, k], errorMap=errorMap) elif type(response) is list: for i in range(len(response)): c.getErrorsFromResponse(response[i], loc=[*loc, f"[{i}]"], errorMap=errorMap) else: # Error Handling for the Error Finder return errorMap Call which works (views.py) if settings.DEBUG: errorMap = mainReportQuery.getErrorsFromResponse(response, loc=[], errorMap={}) Call which does not work (views.py) if settings.DEBUG: errorMap = mainReportQuery.getErrorsFromResponse(response) Appreciate any help. Switching … -
Retrieving timestamp data from Django models
New to Django and am having some issues trying to display the timestamps from my models in my code. I have two Django classes representing two different lists: models.py class Playinglist(models.Model): title = models.CharField(max_length=200) user = models.CharField(max_length=64) game_id = models.IntegerField() started_on = models.DateTimeField(auto_now=True) class Playedlist(models.Model): title = models.CharField(max_length=200) user = models.CharField(max_length=64) game_id = models.IntegerField() finished_on = models.DateTimeField(auto_now=True) When I create a new model I understand that models.DateTimeField(auto_now=True) should create a timestamp in the model for when that model was last saved. The functions I am using to add data to these models look like this: views.py def add_to_playinglist(request, game_id): obj = Playinglist.objects.filter(game_id=game_id, user=request.user.username) if obj: obj.delete() game = Game.objects.get(id=game_id) playing_game = Playinglist.objects.filter(game_id=game_id, user=request.user.username) return redirect("profile") else: obj = Playinglist() obj.user = request.user.username obj.game_id = game_id obj.save() game = Game.objects.get(id=game_id) playing_game = Playinglist.objects.filter(game_id=game_id, user=request.user.username) return redirect("profile") @login_required(login_url='/login') def add_to_playedlist(request, game_id): obj = Playedlist.objects.filter(game_id=game_id, user=request.user.username) if obj: obj.delete() game = Playinglist.objects.get(game_id=game_id) played_game = Playedlist.objects.filter(game_id=game_id, user=request.user.username) return redirect("profile") else: obj = Playedlist() obj.user = request.user.username obj.game_id = game_id obj.save() game = Playinglist.objects.get(game_id=game_id) game.delete() played_game = Playedlist.objects.filter(game_id=game_id, user=request.user.username) return redirect("profile") And when I try displaying the data I use these functions: views.py playinglist = Playinglist.objects.filter(user=request.user.username) playinglist_items = [] playing = playinglist.count() present_in_playinglist = False … -
Django-Templates: Is there a middle ground between extend and include?
I am developing a webpage with Django and I came across the problem of having certain reocurring elements within a webpage. The base layout inluding the menue for instance wraps the rest of the webpage and can thereby be outsourced by extend. Similarly if I have a reocurring element that is completly wrapped by the current webpage without altering html inside it can be implemented by using include (for instance a specific Button). However I have a third category where I do not know how to outsource redundant information: Lets say I have a card design, that always certain propery and contains of a div, with a header an image and content. I want to reuse this design displaying different contents and i also have different cards on the same page, how do I do that? Is this really the way to go: card_x.html: {% extend 'card_template.html' %} {% block title %} Title x{% endblock title %} {% content %} Content x {% endblock content %} ... card_template.html: <div> <h1>{% block title %} {% endblock title %}</h1> <div> {% content %} {% endblock content %} </div> </div> mainpage.html: {% include 'card_1.html' %} {% include 'card_2.html' %} {% include 'card_3.html' %} … -
DRF CSRF cookie not set
I have a DRF project, with an endpoint path('api/auth/', include('rest_framework.urls')), When sending a POST request from Postman to the endpoint api/auth/login/, in order to login with an existing user. I get the following error Forbidden (403) CSRF verification failed. Request aborted. You are seeing this message because this site requires a CSRF cookie when submitting forms. This cookie is required for security reasons, to ensure that your browser is not being hijacked by third parties. If you have configured your browser to disable cookies, please re-enable them, at least for this site, or for “same-origin” requests. Help Reason given for failure: CSRF cookie not set. I tried to set a csrf header (X-CSRFTOKEN, XSRF-TOKEN). I also logged in with the user from the DRF API interface and found the value for X-CSRFTOKEN, which I set in Postman with no success. I also tried to tweak many settings in setttings.py such as (CSRF_COOKIE_NAME, CSRF_TRUSTED_ORIGINS .. Also, to mention the POST method is working on other endpoints for creating objects. I am so thankful if anyone would have an idea. -
paragraph text caused exception findSpanStyle not implemented in this parser - Django
I am trying the generate a pdf using reportlab in django. The content I am trying to print in the pdf is a rich text data which also contains footnotes. I am generating the pdf with the following function makepdf def generate_pdf(request,cat,id): page_width, page_height = A4 page_size = A4 try: citation = get_citation(cat, id) pdf_buffer = BytesIO() # create a document template with the given title doc = BaseDocTemplate(pdf_buffer, pagesize=A4, title=id) # define a page template for all pages header_table_obj = HeaderContent().header(request) header_frame = Frame(0, 25.3*cm, page_width-1.8*cm, 3.1*cm, showBoundary=0, id="header") # define the content frame content_frame = Frame(2*cm, 2.5*cm, page_width-4*cm, page_height-4*cm-3.1*cm, showBoundary=1, id="content") page_template = PageTemplate(frames=[ header_frame, content_frame, ]) # add the page template to the document doc.addPageTemplates(page_template) # making the canvas pdf = canvas.Canvas(pdf_buffer, pagesize=A4) pdf.translate(cm,cm) # adding the pdf title pdf_title = f"SL-{str(citation.get('title', ''))}" pdf.setTitle(pdf_title) header_frame.addFromList([header_table_obj], pdf) # add your content to the content frame judgement_para= ContentParas().judgement_content(citation) // get the rich text data content_frame.addFromList([judgement_para], pdf) pdf.showPage() pdf.save() pdf_buffer.seek(0) return pdf_buffer except Exception as e: return str(e) the judgement_content function is given below which basically styles the paragraph class ContentParas: backColor='#F1F1F1' borderWidth=1 borderColor="#FF0000" borderPadding=(1,1,1) fontName="Times-Roman" fontSize=14 def judgement_content(self, citation): judgment_obj = citation.get('judgements', '') para_styles = ParagraphStyle("Para style", fontName= self.fontName, … -
{TypeError} '<=' not supported between instances of 'CombinedExpression' and 'datetime.date'
I'm new in django and I want to filter my model with certain conditions: for example get only team expired after 7 days. This is my django query: current_date = datetime.datetime.today().date() MyModel.objects.filter( Q(end_date__lt=current_date) & Q(locked=False) & Q(F('end_date') + datetime.timedelta(days=7) <= current_date) ).values('id') end_date is DateField. When I perform this piece of code I get this error: {TypeError} '<=' not supported between instances of 'CombinedExpression' and 'datetime.date'. How can I solve it? Evvery solution I found on web brings me to the same error (Cast, expression wrapper...) Thanks in advance. I try to solve the problem with Cast operator, Expression Wrapper etc. Here my last trial: MyModel.objects.filter( Q(end_date__lt=current_date) & Q(locked=False) & Q(Cast(F('end_date') + timezone.timedelta(days=7), output_field=models.DateField()) <= current_date) ).values_list('id', flat=True) -
Django cannot find 'myapp.setting' via django.setup() when running my script as a module
I'm working on a rather elaborate project and have run into some confusion regarding why I get a ModuleNotFoundError: No module named 'burrow.settings' (I called it myapp.settings in the title for better searchability) when calling __main__.py by running $ python -m burrow, but $ python burrow works perfectly well! I have no relative imports anywhere in my code and haven't touched the boilerplate generated by Django, and have tried and searched all kinds of things and can't find out why this is behaving differently, so any insight would be greatly appreciated! The repository structure may be a little confusing (suggestions for improvement welcome), but effectively consists of a single Project (meercat) consisting of two sub-packages (burrow and lookout) which represent a server and a client respectively. Within the server package (burrow), there is the regular Django boilerplate (burrow/burrow) as well as a Django REST Framework app (api). meercat - data - docs - meercat - burrow - api // newly created - burrow // created with startapp, untouched - __init__.py - __main__.py - controller.py - manage.py - env - lookout - __init__.py - core.py README.md Relevant code: # __main__.py import argparse as ap import logging import os import sys import … -
Add autocomplete CKEditorUploadingWidget with with some list of values
I have a form and I want the html_field to display a list of possible autocomplete options when the user types in matches from a certain list. However, I'm not sure how to correctly implement this, given that I'm using CKEditorUploadingWidget forms.py from ckeditor_uploader.widgets import CKEditorUploadingWidget class TemplateMesForm(forms.RequestForm): temp_html = forms.CharField( label='Html:', widget=CKEditorUploadingWidget(), #If the user types words into this form field that match the list in the function, they receive a dropdown list with all the matches and select the desired one ) views.py def get_autocomplete_list(request): autocomplete_list = ["apple", "banana", "cherry", "date", "elderberry"] return JsonResponse(autocomplete_list, safe=False) -
Why I cannot redirect to "User access URL" in Enterprise Application?
When I copy and paste this URL into the browser it works fine: https://myapps.microsoft.com/signin/xxxxxd7-xxxx-xxxx-xxxx-c6dxxxxxx83?tenantId=xxxxxxx-xxxx-xxxx-xxxxx-xxxxxxxx but when I redirect using Django: from django.http import HttpResponseRedirect def redirect_to_login_url(): .... url = "https://myapps.microsoft.com/signin/xxxxxd7-xxxx-xxxx-xxxx-c6dxxxxxx83?tenantId=xxxxxxx-xxxx-xxxx-xxxxx-xxxxxxxx" return HttpResponseRedirect(url) it doesn't work and I see: -
How to reset a postgres database for django
What do I need to do to get the a django app and the postgres database it connects back to the zero state? and then what do I need to do in Django to re-initialize the database tables? All of the references I've seen online are to MySQL and involve deleting the actual database file. I do not have the option of deleting the whole Postgres installation. -
Making put request to django with external script
I want to make put and post request to my django app with python script that is not in that app. I can make those request with postman but i want to automate them with just python code. Here is code that postman gives me but it doesn't seem to work import http.client import json conn = http.client.HTTPSConnection("localhost", 8000) payload = json.dumps({ data }) headers = { 'Content-Type': 'application/json' } conn.request("PUT", "api/raport/1", payload, headers) res = conn.getresponse() data = res.read() print(data.decode("utf-8")) I tried to run this code and expected record in db change but it doesn't seem to do so. -
Exception while running docker-compose up with Django Rest Framework
To setup secure websocket in Django Rest Framework, I added Daphne to docker-compose.yml as follows daphne: platform: linux/amd64 build: context: . dockerfile: Dockerfile.dev command: 'sh -c "daphne -b 0.0.0.0 -p 8000 apps.asgi:application"' restart: always When I bring the docker-compose up, I'm seeing the following error. If I remove the daphne entry from docker-compose.yml, this error does not happen. I was able to successfully build the compose earlier. daphne_1 | Traceback (most recent call last): daphne_1 | File "/usr/local/lib/python3.8/site-packages/urllib3/connectionpool.py", line 703, in urlopen daphne_1 | httplib_response = self._make_request( daphne_1 | File "/usr/local/lib/python3.8/site-packages/urllib3/connectionpool.py", line 398, in _make_request daphne_1 | conn.request(method, url, **httplib_request_kw) daphne_1 | File "/usr/local/lib/python3.8/http/client.py", line 1256, in request daphne_1 | self._send_request(method, url, body, headers, encode_chunked) daphne_1 | File "/usr/local/lib/python3.8/http/client.py", line 1302, in _send_request daphne_1 | self.endheaders(body, encode_chunked=encode_chunked) daphne_1 | File "/usr/local/lib/python3.8/http/client.py", line 1251, in endheaders daphne_1 | self._send_output(message_body, encode_chunked=encode_chunked) daphne_1 | File "/usr/local/lib/python3.8/http/client.py", line 1011, in _send_output daphne_1 | self.send(msg) daphne_1 | File "/usr/local/lib/python3.8/http/client.py", line 951, in send daphne_1 | self.connect() daphne_1 | File "/usr/local/lib/python3.8/site-packages/docker/transport/unixconn.py", line 30, in connect daphne_1 | sock.connect(self.unix_socket) daphne_1 | FileNotFoundError: [Errno 2] No such file or directory daphne_1 | daphne_1 | During handling of the above exception, another exception occurred: daphne_1 | daphne_1 | Traceback … -
I'm facing this error "ImportError: cannot import name 'smart_text' from 'django.utils.encoding'"
I'm trying to implement Tags on my project using the django-tagging package. Below is the full error.\ File "C:\Users<user>\Desktop<App>\models.py", line 9, in from tagging.fields import TagField File "C:\Users<User>\Desktop<User><App>\env\lib\site-packages\tagging\fields.py", line 9, in from tagging.forms import TagField as TagFormField File "C:\Users<User>\Desktop<User><App>\env\lib\site-packages\tagging\forms.py", line 8, in from tagging.models import Tag File "C:\Users\Nicholas Karimi\Desktop\NicholasKarimi\WebLog\env\lib\site-packages\tagging\models.py", line 8, in from django.utils.encoding import smart_text ImportError: cannot import name 'smart_text' from 'django.utils.encoding' ("C:\Users<User>\Desktop<User><App>\env\lib\site-packages\django\utils\encoding.py) models.py\ class ModelName(models.Model): ..... tags = TagField() Working with django.VERSION (4, 2, 0, 'final', 0) -
how to add functionality of choose_all and remove_all functionality for a model in django-admin
I need to add the Choose all and Remove all functionality to one of the django model in the admin view. but not finding any documentation. I am creating Food table: <group1-> name:vegetarian food ---- vegetables nuts greens chicken egg <group2-> name: non-veg food ---- vegetables nuts greens chicken egg like above i need to choose the food-items and create a group. i want to display like groups option with choose_all/remove_all options. -
RelatedObjectDoesNotExist at /api/v1/user/
I am using drf-social-oauth2 for social authentication in django. When I make a request to backend using following json "grant_type": "convert_token", "client_id": "QhT0Z....u3m5f", "client_secret":"W2DMVGg.....CfhO", "backend":"google-oauth2", "token": "ya29.a0Ael9sCNIcDes5Zb85GJCGWj9ok5kmCH8oBAWWJP9gGRu1Mzrqgtkw6Ut4WE- aOaj0S5Fpf4IrZYjp8bYST93u6yb-MWIHzp3zmtUffbzKnA5VoKlvQ7aC5cSbCauBe4ckTn18XH0_3tWYn5QNg3D2bJqw6H1EAaCgYKARISARISFQF4udJhR0eV5UmE8pvApsrTCMq-8w0165" then following response is returned access_token:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbiI6IjVaU2tncnpJUlNIczlrd3liNUhrQXoyOFNwVVZnZCJ9.FRk7hYDP0ndlBpH3L2jkdNpO3kopRcLqCFfx-6C5GKA" expires_in: 27791.630586 refresh_token:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbiI6IjdibURRUk54ckdLbVJiczR5UGd0ZTJidVNPMklQRyJ9.r5wH-RqhzN2DaG5uUF4Z7F-8ufPgBTUPn7fWLVFwt3k" scope: "read write" token_type: "Bearer" By default if this response is returned the user profile and email should automatically gets saved in the db but the drf-social-oauth2 is only returning the access tokens and is not saving user data. So when I make request to fetch user, following error occurs RelatedObjectDoesNotExist at /api/v1/user/ UserProfile has no student. Following is my written code settings.py INSTALLED_APPS = [ ... 'oauth2_provider', 'social_django', 'drf_social_oauth2', 'users', ... ] AUTH_USER_MODEL = 'users.UserProfile' REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'oauth2_provider.contrib.rest_framework.OAuth2Authentication', 'drf_social_oauth2.authentication.SocialAuthentication', ], 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination', } AUTHENTICATION_BACKENDS = ( # Google OAuth2 'social_core.backends.google.GoogleOAuth2', # Facebook OAuth2 'social_core.backends.facebook.FacebookAppOAuth2', 'social_core.backends.facebook.FacebookOAuth2', # Instagram OAuth2 'social_core.backends.instagram.InstagramOAuth2', # drf_social_oauth2 'drf_social_oauth2.backends.DjangoOAuth2', # Django 'django.contrib.auth.backends.ModelBackend', ) ACTIVATE_JWT = True SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = os.getenv("G_APP_ID") SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = os.getenv("G_APP_SECRET") # Define SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE to get extra permissions from Google. SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE = [ 'https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile', ] ... TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ ... 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', ], }, }, ] urls.py from django.contrib import admin from django.urls …