Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make a form save to the database every time it is edited in Django?
So I am trying to replicate the Google Docs functionality wherein every time you edit, the document will be saved. Will I be putting an onchange function on every input in the form then sending the data through ajax? How should I approach this or is this even feasible? Note: I am just asking for some sort of pseudocode or simply the flow-chart of how I should do things. -
Filter based on two tables Django
I have two models with a through table: class Subscriber(models.Model): first = models.CharField(max_length=30) last = models.CharField(max_length=30) email_confirmed = models.BooleanField(default=False) class Newsletter(models.Model): title = models.CharField(max_length=100, default="Tiffany's Dynamic Digest") body = models.TextField(null=False, blank=False) subscribers = models.ManyToManyField('Subscriber', through='NewsletterEngagement') class NewsletterEngagement(models.Model): subscriber = models.ForeignKey(Subscriber, on_delete=models.CASCADE) newsletter = models.ForeignKey(Newsletter, on_delete=models.CASCADE) I need to search for: All subscribers where email_confirmed=True AND who have not received a newsletter. Thank you in advance. -
How to host two domains for one Django project in WSGI
I have two active domains which i want them to point to one project created using Django. i tried searching on other references but could not find satisfactory solution. Both sites should open same page. index.html residing in the project. Below is my current config file. I am using Apache server and Linux server. I am using SSL for one site as seen below but will not be using for other. <VirtualHost *:80> ServerAdmin admin@example.com ServerName (www.example.com) ServerAlias http://example.com DocumentRoot /home/tguser/tgportal/ ErrorLog /home/tguser/tgportal/core/err.log CustomLog /home/tguser/tgportal/core/access.log combined Alias /static/admin /home/tguser/tgportal/core/staticfiles/admin Alias /.well-known /home/tguser/tgportal/core/.well-known <Directory /home/tguser/tgportal/core/.well-known> Require all granted </Directory> Alias /media /home/tguser/tgportal/core/media <Directory /home/tguser/tgportal/core/media> Options Indexes FollowSymLinks AllowOverride All Require all granted </Directory> Alias /static /home/tguser/tgportal/core/staticfiles <Directory /home/tguser/tgportal/core/staticfiles> Require all granted </Directory> <Directory /home/tguser/tgportal/core/core> <Files wsgi.py> # Require expr %{HTTP_HOST} == "example1.com" Require all granted </Files> </Directory> WSGIPassAuthorization On RewriteEngine on RewriteCond %{HTTP:Authorization} ^(.*) RewriteRule .* - [e=HTTP_AUTHORIZATION:%1] WSGIScriptAlias / /home/tguser/tgportal/core/core/wsgi.py WSGIDaemonProcess tgproject python-path=/home/tguser/tgportal/core/ python-home=/home/tguser/tgportal/env WSGIProcessGroup tgproject </VirtualHost> <VirtualHost *:443> ServerAdmin admin@example1.com ServerName example1.com ServerAlias https://example1.com DocumentRoot /home/tguser/tgportal/ ErrorLog /home/tguser/tgportal/core/err.log CustomLog /home/tguser/tgportal/core/access.log combined SSLEngine on SSLCertificateFile /home/tguser/tgportal/core/keys/a4d9949d130ff93.crt SSLCertificateKeyFile /home/tguser/tgportal/core/keys/generated-private-key.txt SSLCertificateChainFile /home/tguser/tgportal/core/keys/gd_bundle-g2-g1.crt Alias /.well-known /home/tguser/tgportal/core/.well-known <Directory /home/tguser/tgportal/core/.well-known> Require all granted </Directory> Alias /media /home/tguser/tgportal/core/media <Directory /home/tguser/tgportal/core/media> Options Indexes FollowSymLinks AllowOverride All Require … -
Custom method create in ModelViewset Django Rest Framework
Hello guys and girls, Just having a little issue with Django Rest Framework : let's say I have a Book class : models.py class Books(models.Model): title = models.Charfield(max_length = 50, blank=False) serializers.py class BooksSerializer (serializers.ModelSerializer) class Meta: model = Books fields = ['id', 'title'] And now I want to allow the create method only until I have 30 books in database. This is the kind of code I have until now but it isn't working so far, how would you recommend me to proceed ? I can override the create method from the ModelViewSet class right ? views.py class BooksViewset(viewsets.ModelViewSet): queryset = Books.objects.all() serializer_class = BooksSerializer def create(self, serializer): number_of_books = queryset.count() if number of book < 30: serializer.save() else: response = {'message': 'You can't create more than 30 values'} return Response(response, status=status.HTTP_400_BAD_REQUEST) Thank you in advance for your help -
Applicatıon error on deployed django rest framework app on heroku
I'm trying to deploy my django rest framework app on Heroku. I read many other similar questions but I'm confused. My app structure is not right or I'm missing something. This is my structure on git: .gitignore requirements.txt src | --authorization --core --static --staticfiles --Procfile --manage.py --mainfolder | ---asgi.py ---settings.py ---urls.py ---wsgi.py authorization and core are apps under my django project. there wasn't static or staticfiles before heroku deploy. But it automatically created staticfiles. Then I also created static and followed instructions to make it work via changes in settings.py. It'd be awesome if someone help me figure out my problem on heroku and why it doesn't work. This is Procfile: web: gunicorn mainfolder.wsgi web: gunicorn mainfolder:app When I run app with this command my app works fine and run locally: gunicorn mainfolder.wsgi:application But I couldn't solve the error in deployed app. With heroku logs --tail I receive errors starts like below: heroku[router]: at=error code=H14 desc="No web processes running" When I run this heroku ps:scale web=1 --app mainfolder I get this: Scaling dynos... ! ▸ Couldn't find that process type (web). And finally when I try to run heroku locally under src folder with this command src % heroku local … -
RNCryptor - encrypted string cannot be validated in django backend
I am using RNCrytor to encrypt my JWT, however, the encrypted string cannot be validated from the backed, Django. I am using the SwiftJWT library to generate the jwt. Here is my Swift code let header = Header(kid: "KeyID1") var authHeader: String? = nil let clntConfig = ClientConfig() if clntConfig.isValid() { let clientID = clntConfig.getClientsID() let deviceID = clntConfig.getDevicesID() let appSecret = clntConfig.getAppsSecret() let deviceSecret = clntConfig.getDeviceSecrets() let myClaims = AuthClientClaims(clientKey: clientID,deviceUid: deviceID,deviceSecret: deviceSecret) do { print("****\(deviceSecret)***") let jwtSecret = passToPhrase(password: deviceSecret) print("****\(jwtSecret)***") let base64encodedSecretString = jwtSecret.data(using: .utf8)?.base64EncodedString() print("****\(base64encodedSecretString!)***") //let jwtSigner = JWTSigner.rs var myJWT = JWT(header: header, claims: myClaims) let privateKey: Data = base64encodedSecretString!.data(using: .utf8)! let jwtSigner = JWTSigner.hs256(key: privateKey) let signedJWT = try myJWT.sign(using: jwtSigner) print("****\(signedJWT)****") let ciphertext = RNCryptor.encrypt(data: signedJWT.data(using: .utf8)!, withPassword: appSecret) authHeader = ciphertext.base64EncodedString() } Here is the backend code def do_decrypt(en_data, secret): en_data = en_data + '===============' encrypted_data = base64.b64decode(en_data) decrypted_data = rncryptor.decrypt(encrypted_data, secret) return decrypted_data -
Can i pass form or other parametr, to the template, without doing it in view?
I have register form, and i need to display it on almost every template (on base.html), so can i do it without passing it in every view? -
How to customize message error for TokenAuthentication in Django Rest Framework
Right now I only get a brief message : [detail => Invalid token], how can I change it? I come more from a Java environment and I'm struggling with a whole new world now. I have found the custom exception handling in the official documentation but still unable to customize it. -
Django counting ForeignKeyField
I want to count from my brandListVeiw view how many assets I have of a certain brand models.py class Asset(models.Model): # Relationships room = models.ForeignKey("asset_app.Room", on_delete=models.SET_NULL, blank=True, null=True) model = models.ForeignKey("asset_app.Model", on_delete=models.SET_NULL, blank=True, null=True) # Fields created = models.DateTimeField(auto_now_add=True, editable=False) last_updated = models.DateTimeField(auto_now=True, editable=False) name = models.CharField(max_length=30) mac_address = models.CharField(max_length=30, null=True, blank=True) serial = models.CharField(max_length=30, unique=True, blank=True, null=True, default=None) purchased_date = models.DateField(null=True, blank=True) may_be_loaned = models.BooleanField(default=False, blank=True, null=True) notes = models.TextField(max_length=448, null=True, blank=True) ip = models.CharField(max_length=90, null=True, blank=True) class Meta: pass def __str__(self): return str(self.name) def get_absolute_url(self): return reverse("asset_app_asset_detail", args=(self.pk,)) def get_update_url(self): return reverse("asset_app_asset_update", args=(self.pk,)) class Brand(models.Model): name = models.CharField(max_length=30) notes = models.TextField(max_length=448, null=True, blank=True) last_updated = models.DateTimeField(auto_now=True, editable=False) created = models.DateTimeField(auto_now_add=True, editable=False) class Meta: ordering = ["name"] def __str__(self): return str(self.name) def get_absolute_url(self): return reverse("asset_app_brand_detail", args=(self.pk,)) def get_update_url(self): return reverse("asset_app_brand_update", args=(self.pk,)) class Model(models.Model): # Relationships asset_type = models.ForeignKey("asset_app.Asset_type", on_delete=models.SET_NULL, blank=True, null=True) brand = models.ForeignKey("asset_app.Brand", on_delete=models.SET_NULL, blank=True, null=True) # Fields name = models.CharField(max_length=30) notes = models.TextField(max_length=448, null=True, blank=True) created = models.DateTimeField(auto_now_add=True, editable=False) last_updated = models.DateTimeField(auto_now=True, editable=False) class Meta: pass def __str__(self): return str(self.name) + " :: " + str(self.brand.name) + " :: " + self.asset_type.name def get_absolute_url(self): return reverse("asset_app_model_detail", args=(self.pk,)) def get_update_url(self): return reverse("asset_app_model_update", args=(self.pk,)) views.py class BrandListView(generic.ListView): model = … -
How to create/add multiple groups in single django channels view
Hello guys I am currently building real time Django web application . And i am in dilemma. How do i create or add different group or view in single view. My currently working solution is : class StatusConsumer(AsyncWebsocketConsumer): async def connect(self): self.me = self.scope.get('user') if not self.me.is_authenticated: await self.close() self.room_name = "online_status" await self.channel_layer.group_add( self.room_name, self.channel_name ) await self.channel_layer.group_add( f"{self.me}-notify", self.channel_name ) await self.accept() this view has two groups one is "online_status" and other a unique group . I did create two group using await self.channel_layer.group_add( self.room_name, self.channel_name ) await self.channel_layer.group_add( f"{self.me}-notify", self.channel_name ) This is working fine i believe there are more good ways to do this. -
How to include Django static URL for digital ocean spaces using JavaScript?
I have a django application storing static images on digital ocean spaces. I can easily display these static images in my template by doing:<img>{% static 'images/my_image.png' %}</img> If I inspect the HTML page after this loads, I will see something like: https://nyc3.digitaloceanspaces.com/nameofmyspace/nameofmyspace-space-static_DEV/images/my_image.png?AWSAccessKeyId=XXXXXXXXXXXXXX&Signature=XXXXXXXXXXXXXXXXXX%3D&Expires=1621600823 But now I want to have this image change dynamically. So I thought I would use javascript to do this like: document.getElementById(id+"dynamicImage").src = "{% static 'images/my_image_2.png' %}"; Which almost works, but the image does not load. And the reason for this is after inspecting the src that the javascript supplied: https://nyc3.digitaloceanspaces.com/nameofmyspace/nameofmyspace-space-static_DEV/images/my_image.png?AWSAccessKeyId=XXXXXXXXXXXXXX&amp;Signature=XXXXXXXXXXXXXXXXXX%3D&amp;Expires=1621600823 You can see wherever there was an & it appended amp; to it. What is the correct way to do this? I can think of 2 ways to correct this, but they seem hacky. I could hard code the URL's into the javascript, which will be a nightmare later, and exposes the API key. I could do <img id = 'my_image' hidden >{% static 'images/my_image.png' %}</img> for all the links I plan on using, then access this URL in the javascript using let URL = document.getElementById("my_image").innerHTML;. This will be less of an updating nightmare, but will still expose the API key now that I think about it, … -
Is it possible to make nested queries in the Django ORM?
Is it possible to make a "nested query" (not sure of the correct term) in the Django ORM. For exampel in SQL: SELECT SUM("tbl1"."views") FROM ( SELECT DISTINCT "my_django_model" FROM INNER JOIN ... INNER JOIN ... ) AS tbl1 GROUP BY "tbl1"."date" I've tried SubQuery but that adds a Query in the SELECT fields, which is not the same thing. Why do I need this? I'm using Sum with a number of ForeignKeys and ManyToManyFields which i filter on. Django then joins all these tables to be able to filter. And that will cause duplicates. And no, Sum('views', distinct=True') does not work, because it is distinct on the actual value of 'views' which is not unique. I've tried a custom query in PGAdmin like the first one above. Then It works perfect. But I prefer to use the ORM and not Raw SQL when possible. Any suggestions welcome. -
Django Register Form redirecting to same url
i am new to django i have created a user registration form but when i click on submit it does nothing and just goes to the same page i am not under standing what i did wrong here views.py: class RegisterPage(FormView): template_name = "main/register.html" form_class = RegisterForm success_url = reverse_lazy('blog_list') def form_valid(self, form): user = form.save() if user is not None: login(self.request, user) return super(RegisterPage, self).form_valid(form) def get(self, *args, **kwargs): if self.request.user.is_authenticated: return redirect("blog_list") return super(RegisterPage, self).get(*args, **kwargs) forms.py: from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class RegisterForm(UserCreationForm): bio = forms.CharField(max_length=400, empty_value="Max Length 400") image = forms.ImageField() class Meta: model = User fields = ["username", "image", "password1", "password2", "bio"] register.html: {% extends "main/main.html" %} {% block title %}Create an Account{% endblock %} {% block content %} <div class="form"> <h1>Register</h1> <form method="post"> {% csrf_token %} <label>{{form.username.label}}</label> {{form.username}} <br> <label>{{form.password1.label}}</label> {{form.password1}} <br> <label>{{form.password2.label}}</label> {{form.password2}} <br> <label>{{form.image.label}}</label> {{form.image}} <br> <label>{{form.bio.label}}</label> {{form.bio}} <br> <input style="margin-top: 10px" class="button" type="submit" value="Register"/> </form> <p>Already Have An Account <a href="{% url 'login' %}" class="button">Login</a></p> </div> {% endblock content %} in the views.py i have also tried form_class = UserCreationForm the built in django creation form but still the same result so what is wrong -
How to Show Code Properly In HTML with Django?
I making a website where I can store my python code in. I want the spaces,line breaks,indentations to show correctly on the HTML side of the page, but they are not working properly. I used the <pre> tag, but I gives some sort of space on the first line. This is what I get when i put the <pre> tags. : I want the first line to be vertically aligned to the if-else statement. This is my html code: {% extends 'base/base.html' %} {% block head %} <title>CodeBase | {{ code.title }}</title> {% endblock %} {% block content %} <h1>{{ code.title }}</h1> <br> <pre> {{ code.code }} </pre> {% endblock %} This is my views.py def SeeCode(request, code_pk): code = Code.objects.get(pk=code_pk) # first_line = code.code.split('\n')[0] context = { "code": code, # "first_line": first_line } return render(request, "base/see_code.html", context) Thank you! -
How can I return an nested data in a get request?
Looking for help i got stuck at a point where I need to return a nested content in response to a GET request but getting error : django.core.exceptions.FieldError: Cannot resolve keyword 'order' into field. Choices are: amount, created_at, datetime, direction, id, is_active, orders, orders_id, payment_mode_code, reference_identifier, settlement_status, updated_at views.py @api_view(['GET']) def return_order_details(request,id): if request.method=='GET': order = get_object_or_404(Orders,id=id) id=order.id collection_payments = get_object_or_404(Payments,order=order,direction='Collection') content = { 'orders': { "id":id, "purpose_code":order.purpose_code, "amount":order.amount, 'collection_payments':{ "id":collection_payments.id, "amount":collection_payments.amount, "datetime":collection_payments.datetime, } } } return Response(json.dumps(content), status=status.HTTP_200_OK) -
How to count inventory stock in django grup by product
Can anyone help me? I'm trying to get something like this | book.name| book.author | book.release_year | inventory.filter(available=True).count()| |:-------- |------------: | ------------: | --------------------------------------: | | book1 | Author1 aut2... | 2021 | 5 | | book2 | Author3 aut5... | 1986 | 7 | I have a model class Author(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) biography = models.TextField(blank=True, null=True) picture = models.ImageField(upload_to='authors', blank=True, null=True) def __str__(self): return self.first_name + ' ' + self.last_name class Book(models.Model): CHOICE_CATEGORY = ( ) name = models.CharField(max_length=250, unique=True) author = models.ManyToManyField(Author) category = models.IntegerField( choices=CHOICE_CATEGORY, blank=True, null=True) release_year = models.CharField(max_length=4) def __str__(self): return self.name class Inventory(models.Model): book = models.ForeignKey( Book, related_name='book', on_delete=models.CASCADE) inventory_number = models.CharField(max_length=50, unique=True) available = models.BooleanField(default=True) def __str__(self): return self.book.name Problem is with authors, if i have more than one than i must get a list of authors With this code i get table but is grouped by authors individually def book_list(request): books = Inventory.objects.filter(available=True).values( 'book__name', 'book__id', 'book__release_year', 'book__author').annotate(total=Count('book')) print(books) context = {'books': books, } return render(request, 'book_list.html', context) if i remove authors from .values('book__author') i can't display author in template. Where I'm wrong? -
Django-channels can;'e connect to ws:mysite
I have some problems with django-channels,while connecting to wss://mysite.com server return this error.error with wss Here is my asgi.py settings,my template , supervisor settings, nginx settings Thanks for help! -
What should I use, request params or path converters in DRF get request?
I want to pass a pk to a get method in a APIView class, but I am confused whether I user request params or path converters for that. -
How to send articles a mail in Django
I am having an issue about sending out newsletters in Django. I want to send out series of posts or articles as one newsletter email but, what I have currently is that mails are sending out one after the other i.e each post is sent one after the other. I want my mail to be sent once, below is my code models.py class NewsLetters(models.Model): title = models.CharField(max_length=35) subject = models.CharField(max_length=150) image = models.ImageField(upload_to='uploads/') link = models.URLField(blank=True, null=True) content = models.TextField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.subject + " " + self.created_at.strftime("%B %d, %Y") class Meta(): verbose_name_plural = 'Newsletters' def img_url(self): if self.image: return self.image.url def send(self, request): subscribers = Subscribers.objects.filter(confirmed=True) email_data = [] for sub in subscribers: args = { 'title':self.title, 'content':self.content, 'image':self.image } email_data.append(args) html_message = render_to_string('website/newsletter.html', email_data) plain_message = strip_tags(html_message) from_email = settings.FROM_HOST mail.send_mail(self.subject, plain_message, from_email, [sub.email,], html_message=html_message) admin.py def send_newsletter(modeladmin, request, queryset): for newsletter in queryset: newsletter.send(request) send_newsletter.short_description = "Send selected Newsletters to all subscribers" @admin.register(NewsLetters) class NewsLetterAdmin(admin.ModelAdmin): actions = [send_newsletter,] newsletter.html {% if news %} {% for n in news %} <div class="col-md-4"> <p>n.title</p> <p>n.image</p> <p>n.content</p> </div> {% endfor %} {% endif %} -
How can i filter with checkboxes
I want to filter with checkboxes from column values Code: cursor.execute("[Prueba].[dbo].[N]" + "'" + str(format_min) + "'," + "'" + str(format_max) + "'") qs = cursor.fetchall() it returns the values image with values <input class="form-check-input" type="checkbox" id="h1" name="h1"> <label class="form-check-label" for="h1"> <b>H1</b> </label> <br /> <input class="form-check-input" type="checkbox" id="h2" name="h2"> <label class="form-check-label" for="h2"> <b>H2</b> I want to click on checkbox h1 and filter by h1 machines -
React JS - Module build failed (from ./node_modules/babel-loader/lib/index.js):
I'm having the following error and can't find out what I'm doing. whatever I try it gives this error. Please help me. Module build failed (from ./node_modules/babel-loader/lib/index.js): Error: Plugin/Preset files are not allowed to export objects, only functions. In E:\Neptune\node_modules\babel-preset-es2015\lib\index.js my files are: Index.JS import React from 'react'; import ReactDOM from 'react-dom'; import reportWebVitals from './reportWebVitals'; import App from './App' import './components/main.css' ReactDOM.render( <React.StrictMode> <App/> </React.StrictMode>, document.getElementById('root') ); // If you want to start measuring performance in your app, pass a function // to log results (for example: reportWebVitals(console.log)) reportWebVitals(); Package.json { "devDependencies": { "@babel/core": "^7.14.3", "@babel/preset-env": "^7.14.2", "@babel/preset-react": "^7.13.13", "babel-loader": "^8.2.2", "babel-plugin-transform-class-properties": "^6.24.1", "webpack": "^5.37.1", "webpack-cli": "^4.7.0" }, "dependencies": { "@testing-library/jest-dom": "^5.12.0", "@testing-library/react": "^11.2.6", "@testing-library/user-event": "^12.8.3", "babel-preset-es2015": "^6.24.1", "bootstrap": "^4.6.0", "prop-types": "^15.7.2", "react": "^17.0.2", "react-bootstrap": "^1.6.0", "react-dom": "^17.0.2", "react-router-dom": "^5.2.0", "react-scripts": "4.0.3", "styled-components": "^5.3.0", "web-vitals": "^1.1.2" } } .bablerc { "presets": ["@babel/preset-env", "@babel/preset-react", "es2015", "stage-0", "react"], "plugins": ["transform-class-properties"] } Webpack.config.js module.exports = { module: { rules: [{ test: /\.(js|jsx)$/, exclude: /node_modules/, use: { loader: 'babel-loader?cacheDirectory=true', } }] } }; -
TemplateSyntaxError at Posts, First Django Project
I'm trying to make my first Django project. I'm making the first post and in the the tutorial, it goes like this in HTML: <!DOCTYPE html> <html> <head> <title></title> </head> <body> <h1> This is our list of post</h1> {% for post in post_objects &} {{ post }} {% endfor %} </body> </html> Now that I'm trying to run the server and check the page so I can see the 'This is our list of post', there is an error. Error during template rendering In template C:\Users\Invoker\Dev\trydjango\src\posts\templates\posts\index.html, error at line 10 Invalid block tag on line 10: 'endfor'. Did you forget to register or load this tag? 1 <!DOCTYPE html> 2 <html> 3 <head> 4 <title></title> 5 </head> 6 <body> 7 <h1> This is our list of post</h1> 8 {% for post in post_objects &} 9 {{ post }} 10 {% endfor %} 11 </body> 12 </html> What should I do? -
Django models: implement
I am trying to build a Django app that allows the user to crawl a website, collect all the internal links of said website and then the user can create a number of variants on this list and make changes on those links to simulate a different website architecture (for example, delete some links, add a link, etc.). I need to keep the original link list and then be able to compare it with each variant to show differences (i.e. +50% removed links, -10% links in footer, etc.) I am not sure what the ideal model structure would be in this case. I have already created the models to save each crawl the user does and the model to store the crawled links: models.py # Django from django.db import models from django.urls import reverse from django.utils.timezone import now # Owner from apps.project.models import Project, Experiment CRAWL_STATUS = {(1, "Running"), (2, "Paused"), (3, "Finished")} # Custom model managers class CrawlManager(models.Manager): def new_crawl(self, exp_id, status): # get experiment instance experiment = Experiment.objects.get(id=exp_id) # save new crawl in DB crawl = self.create(experiment=experiment, status=status) return crawl class CrawledLinksManager(models.Manager): def new_link(self, crawl, source_url, target_url, nofollow): link = self.create( crawl=crawl, source_url=source_url, target_url=target_url, nofollow=nofollow ) return link … -
Merge each friend's tweets and own feeds, return top 100 tweets ordered by post date
enter image description here Filter out user's friends. Filter each friend's top 100 tweet ordered by post date. Filter user's own feeds. Merge each friend's tweets and own feeds, return top 100 tweets ordered by post date -
Django rest framework API is not responding when I run server with ASGI
I used channels in my Django project and when I changed WSGI to ASGI then some of my APIs stopped responding. 1. if customer_object.status == None: 2. new_user, created = User.objects.get_or_created(username="abc", role_id=Role(1)) 3. new_user.set_password('abc') 4. temp_object = User.objects.filter(id = self.request.data['user_id']).first() 5. new_user.restaurant_id = temp_object.restaurant_id 6. new_user.save() 7. url = settings.API_URL+"/api/v1/auth/sign_in/" 8. response = requests.post(url, data={'username': f"customer1", 'password': '123456'}) In the above-mentioned code at line 8 project not responds. I used the python async-await method like response = await requests.post(url, data={'username': f"customer1", 'password': '123456'}) It returns coroutine object and I try to get data from it by using response.text but it says couroutine object has no attribute text. Please answer if anyone came accros this kind of situation.