Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Stripe MetaData Working Properly But Not Showing Up on Stripe Dashboard
I've implemented Stripe checkout on a Django app and it's all working correctly except that it's not showing up on the Stripe Dashboard, even though it's showing in the event data on the same page. Have I formatted it incorrectly or am I overlooking something obvious? This is how I added meta data: checkout_session = stripe.checkout.Session.create( payment_method_types=['card'], line_items = line_itemz, metadata={ "payment_type":"schedule_visit", "visit_id":visit_id }, mode='payment', success_url= 'http://localhost:8000/success', cancel_url = 'http://localhost:8000/cancel',) Here is a screenshot of the Metadata section empty, but in the events the Metadata is there as it should be: Again I can access the metadata every where else but would like it to show up on the dashboard so my team can more easily access that information. -
Use data as Django response field name?
I have the following data class: class IndustryScore: industry: str score: Decimal class Foo: ... industry_scores = List[IndustryScore] I want the response to be something where the key of the response is the industry and the score is the value. For example: { "automotive": 5.1, "construction": 10.0, "technology": 8.6, } Right now I have a serializer like this: class IndustryScoreSerializer(serializers.Serializer): industry = serializers.Charfield() score = serializers.DecimalField() but the response is something like this instead: [ { industry: "automotive", score: 5.1 } ] How can I change the serializer so I get the expected JSON structure? -
Docker-compose volume not creating new directory
i'm writing docker compose yml file and i have problem with setting volume that would create new directory. This is my directories tree ├── backend │ ├── projectname │ ├── manage.py │ └── requirements.txt ├── docker-compose.yml ├── Dockerfile └── README.md Dockerfile FROM python:3 ENV PYTHONUNBUFFERED=1 ENV PYTHONDONTWRITEBYTECODE=1 WORKDIR /app COPY backend/requirements.txt . COPY backend/ . RUN pip install -r requirements.txt docker-compose.yml version: "3.9" services: app: build: . volumes: - ./backend:/app ports: - 8000:8000 command: bash -c "python manage.py makemigrations && python manage.py migrate && python manage.py runserver 0.0.0.0:8000" depends_on: - db db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=name - POSTGRES_USER=name - POSTGRES_PASSWORD=pass container_name: postgres Problem is when i'm running docker-compose, then it creates no data/db directory with database data. -
Unittest for close_old_connections
On current project we had a problem with recovery a connection to DB, after some problems with a DB pod. We found a solution for this problem: from functools import wraps from django import db def cleanup_db_connections(func): @wraps(func) def wrapper(*args, **kwargs): try: r_val = func(*args, **kwargs) except db.OperationalError as e: db.close_old_connections() r_val = func(*args, **kwargs) return r_val return wrapper Now we want to create a unittest for this decorator and solution in general and we faced with new problem: We can reproduce the problem with connection (connection.close() or connection.creation.destroy_test_db()) but our solution, which works in the application, does not solve the problem in the test. If I understand correctly, it depends on Django - in unittest its doesn`t recover connection after close. I have a two questions: Am I right in understanding at the problem? Could I make Django recover connection? Is there a way for me to test this decorator? -
file.write returning two \n\n
I have a markdown file called CSS.md: # CSS CSS is a language that can be used to add style to an [HTML](/wiki/HTML) page. My main goal is to have a input field where I can edit this file, save it, and return the web page with the new file. Here's the code: def edit_page(request, page): data = {'edit':''} with open(os.path.join('.\entries',f'{page}.md'), 'r', encoding='utf-8') as editing_page: for line in editing_page.readlines(): data['edit'] += line edit = EditPage(data) if request.method == 'GET': return render(request, 'encyclopedia/edit_page.html', { 'edit':edit, 'page':page, }) elif request.method == 'POST': form = EditPage(request.POST) if form.is_valid(): content = form.cleaned_data['edit'] with open(os.path.join('.\entries',f'{page}.md'), 'w', encoding='utf-8') as edited_page: edited_page.write(content) # FIXME ta duplicando o \n return HttpResponseRedirect(f'/wiki/{page}') When I run print(editing_page.readlines()) before clicking the submit button (POST method): ['# CSS\n', '\n', 'CSS is a language that can be used to add style to an [HTML](/wiki/HTML) page.\n'] After clickin the submit button, even without any alteration, it duplicates the \n: ['# CSS\n', '\n', '\n', '\n', 'CSS is a language that can be used to add style to an [HTML](/wiki/HTML) page.'] I tried to do writelines but it did not work... -
The difference between
what is the difference between request.post.get('blog','') AND request.post.get('blog') I am not able to figure out what is the difference between this two and they what they return, iT will be great help if someone tell me -
Modify patch.object variable to test
Hey guys need some general guidance. Im trying to write some tests for a django app but im a bit confused how mock/patch works. If i use patch.object on a function. and run a test how do i then change a variable in it to do another test. For eg. if my function was simple like def myfunc(potato): number = count(potato) if number >0: print('foo') else: print('bar) How do I test both if number was greater than 0 or less than 0? (My real function takes a queryset and filters a model to find out the count then uses the count in a if/else.). Bonus question I am also trying to test that a email was sent but when I try to use use: self.patchobject.assertEqual(len(mail.outbox),1) I am getting an assertion error.. -
Django import into many to many relationship with custom through table
I am not sure the proper way to import using django-import-export tsv files into many to many relationship tables. What I have done is create a books table, a genre table and a bookgenre through table which contains the foreignkeys to each of the other tables. So what I have is: class Book(models.Model): title = models.CharField(max_length=255) class Genre(models.Model): genre = models.CharField(max_length=64) class BookGenre(models.Model): book_id = models.ForeignKey('Book', on_delete=models.CASCADE) genre_id = models.ForeignKey('Genre', on_delete=models.CASCADE) Then I import all three tables and the relationships are working but I can't figure out a way to make a view or template that works effectively. I am thinking there must be a better way to create a many to many relationship and import data into it. Any Ideas? -
How to use data from postgresql in django?
I have switched from sqlite to postgresql following Django: What are the best practices to migrate a project from sqlite to PostgreSQL the fourth answer. Here are my updated settings: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'scraper', 'USER':'user', 'HOST':'localhost', 'PORT':5432, } } However, I cannot seem to find/grab any of the data from my database. Here's some example data from the database: I have tried python manage.py dumpdata But get this: [{"model": "auth.permission", "pk": 1, "fields": {"name": "Can add log entry", "content_type": 1, "codename": "add_logentry"}}, {"model": "auth.permission", "pk": 2, "fields": {"name": "Can change log entry", "content_type": 1, "codename": "change_logentry"}}, {"model": "auth.permission", "pk": 3, ... I wanted to upload that data based on my current app: models.py from django.db import models class Cruises(models.Model): title = models.CharField(max_length=200) #ship_name = models.CharField(blank=True, null=True,max_length = 200) def __str__(self): return self.title views.py from django.shortcuts import render #from .models import Cruises from .models import Cruises def basic(request): #form_destination = Cruises long_list = Cruises.objects.values('title') return render(request, 'cruise_control/basic.html', context = {'long_list':long_list}) urls.py from django.urls import path from . import views urlpatterns = [ path('',views.basic, name = 'basic') ] basic.html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Cruises</title> </head> <body> <h1> Cruise Control </h1> <form action="/action_page.php"> <label for='destination'>Destination</label> <input … -
Django Extract functions always groups by Day
I have DateTimeField - snap_at. I need GROUP PY this field by Day, Week, Month etc. I try it qs .annotate(month=ExtractMonth('snap_at')) .values('month') .annotate( .... ) .annotate( .... ) .values( ... ) ) But, judging by the output, Django made a grouping by Days. SQL output SQL - SELECT COUNT(*) FROM (SELECT "wb_stockshistory"."snap_at" AS "col1", EXTRACT('month' FROM "wb_stockshistory"."snap_at" AT TIME ZONE 'UTC') AS "month", COUNT(DISTINCT "wb_stockshistory"."good_id") AS "goods_count", COUNT(DISTINCT "wb_stockshistory"."good_id") FILTER (WHERE "wb_stockshistory"."sales" > 0) AS "goods_sales_count", SUM("wb_stockshistory"."sales") AS "total_sales", COUNT(DISTINCT "wb_good"."brand_id") FILTER (WHERE "wb_stockshistory"."sales" > 0) AS "brands_sales_count", COUNT(DISTINCT "wb_good"."supplier_id") FILTER (WHERE "wb_stockshistory"."sales" > 0) AS "suppliers_sales_count", SUM("wb_stockshistory"."revenue") AS "total_revenue", ROUND(AVG("wb_stockshistory"."price"), 2) AS "avg_price", ROUND(AVG("wb_stockshistory"."rating"), 2) AS "rating", COUNT(DISTINCT "wb_good"."brand_id") AS "brands_count", COUNT(DISTINCT "wb_good"."supplier_id") AS "suppliers_count", ROUND((SUM("wb_stockshistory"."feedbacks") / COUNT(DISTINCT "wb_stockshistory"."good_id")), 2) AS "feedbacks", ROUND((SUM("wb_stockshistory"."revenue") / COUNT(DISTINCT "wb_stockshistory"."good_id") FILTER (WHERE "wb_stockshistory"."sales" > 0)), 2) AS "avg_sales" FROM "wb_stockshistory" INNER JOIN "wb_good" ON ("wb_stockshistory"."good_id" = "wb_good"."id") GROUP BY EXTRACT('month' FROM "wb_stockshistory"."snap_at" AT TIME ZONE 'UTC'), "wb_stockshistory"."snap_at") subquery SQL - SELECT "wb_stockshistory"."snap_at", EXTRACT('month' FROM "wb_stockshistory"."snap_at" AT TIME ZONE 'UTC') AS "month", COUNT(DISTINCT "wb_stockshistory"."good_id") AS "goods_count", COUNT(DISTINCT "wb_stockshistory"."good_id") FILTER (WHERE "wb_stockshistory"."sales" > 0) AS "goods_sales_count", SUM("wb_stockshistory"."sales") AS "total_sales", COUNT(DISTINCT "wb_good"."brand_id") FILTER (WHERE "wb_stockshistory"."sales" > 0) AS "brands_sales_count", COUNT(DISTINCT "wb_good"."supplier_id") FILTER (WHERE "wb_stockshistory"."sales" > 0) … -
How to Send an Email by passing an URL from anchor tag in Django
enter image description hereTo track email has opened or not I want to call an API whenever I will click the image from the email. My question is how to pass the URL in href, inside the anchor tag (check the below code I have provided). ** My problem is in the second last line : new_message = message + ' ' #<----My problem is on this line class SendEmailView(View): def post(self, request): # get data email_template_id = request.POST.get('email_template') recipient_email = request.POST.get('recipient_email') created_by = request.user email_template = Email.objects.get(id=email_template_id) recipient_instance = Recipient.objects.get(email=recipient_email) # Send_mail args subject = email_template.subject.replace('{name}', recipient_instance.name) message = email_template.email_body.replace('{name}', recipient_instance.name).replace('{email}', recipient_instance.email) from_email = "saadi.techlogicinas@gmail.com" recipient_list = listify(recipient_email) # Track Email email_id = email_template.id recipient_id = recipient_instance.id base_url = "http://127.0.0.1:8000/email/track/" **final_url = f'{base_url}/{email_id}/{recipient_id}/'** new_message = message + '<a href= final_url > <img src="#" /> </a>' #<----My problem is on this line # send_mail send_mail(subject, message, from_email=from_email, recipient_list=recipient_list, html_message=new_message) -
How can I pass in a CSRF token with my API requests if I don't have a user login for my Django site?
Using the Django rest framework, I have an API endpoint I created that I call within my static files that I would like to pass a CSRF token into so that I'm the only one who can access the API. My Django site does not have users with logins. I essentially want to do something like this in my API endpoint: @api_view(['POST']) def payment(request, *args, **kwargs): if (("Authorization" not in requests.headers) or (request.headers["Authorization"] != "token")): return Response({"Error": "Not authorized for access."}) ... Do I need to generate a token one time and use that repeatedly? Or can I generate one every time the script is used? And how can I access this csrf token in my HTML file? I'm using class-based views and I assume I would pass it in to get_context_data, but how would I set up the API endpoint to accept this CSRF token? -
Polymorphic relationship in Django
I have this relationship between my models: The model called MyModel might have a foreign key to model A or model B, How can I do this in Django? I heard that the solution called Polymorphic relationship but could not find the correct way to implement it. My code: from django.db import models class A(models.Model): email = models.EmailField() national_id = models.IntegerField() class B(models.Model): name = models.CharField(max_length=255) age = models.IntegerField() class MyModel(models.Model): name = models.CharField(max_length=255) provider = models.ForeignKey(to=A, on_delete=models.CASCADE) -
Integrating Nuxt Js in Django "GET /_nuxt/bed9682.js HTTP/1.1" 404 2918
I am trying to integrate my Nuxt application inside Django. I have my Nuxt application and django application inside the same folder. I have set up the settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR,'(Name of the nuxt application folder)/dist') ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] And urls.py from django.contrib import admin from django.urls import path, include from django.views.generic import TemplateView from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), #'admin-dashboard/' path('',TemplateView.as_view(template_name='index.html')) ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) But It's failling to load this files in index.html GET http://localhost:8000/_nuxt/3433182.js net::ERR_ABORTED 404 (Not Found) GET http://localhost:8000/_nuxt/369ee37.js net::ERR_ABORTED 404 (Not Found) GET http://localhost:8000/_nuxt/aad44e2.js net::ERR_ABORTED 404 (Not Found) GET http://localhost:8000/_nuxt/bed9682.js net::ERR_ABORTED 404 (Not Found) GET http://localhost:8000/_nuxt/img/page-background.74b6577.png 404 (Not Found) -
How can I show my images through JsonResponse in Django's view?
I have a question, my collaborator's code works well, it shows some images that were previously uploaded through an input through a modal. The problem is that I want to display the images in a detail view. I modified it and I can only show one of the 10 that were uploaded. How can I show all 10? I have no idea how to handle that JSON he used views.py class detail_carro(DetailView): template_name = 'carros/carros-detail.html' queryset=Carro.objects.all() context_object_name = 'carros' def create_carros_picture(request): if request.FILES['files']: file = request.FILES['files'] fs = FileSystemStorage() # defaults to MEDIA_ROOT new_name = "picture" new_name = fs.get_valid_name(new_name)+".jpg" filename = fs.save(new_name, file) return JsonResponse({filename:file.name},safe=False) else: form=CarroForm() return render(request, "carros/carros-form-add.html",{'form':form}) def create_carros_warranty(request): if request.FILES['files']: file = request.FILES['files'] fs = FileSystemStorage() # defaults to MEDIA_ROOT ext = file.name.split('.')[-1] new_name = "warranty" new_name = fs.get_valid_name(new_name) + '.' + ext filename = fs.save(new_name, file) return JsonResponse({filename: file.name}, safe=False) else: form = CarroForm() return render(request, "carros/carros-form-add.html", {'form': form}) carros-detail.html {% if carros.new_name %} <a data-id="{{carros.id}}" class="btn_view_gallery"> <img src="{% get_media_prefix %}{{carros.new_name}}" height="300"> </a> {% endif %} -
How to create a dynamic form in htmx and Django?
I'm creating a form that sends a request back to Django via POST method using htmx to get the search results without having to reload the page. I have already tried to create a form with Django and htmx but without success. Htmx being new, I can't seem to find solid sources for learning. Every time I submit my form, the page reloads despite me. Here is my source code: <form method="POST" action="search"> ... <input type="search" name="search" hx-post="/search" hx-target="#results" hx-trigger="keyup changed delay:500ms" value="{{form.search.value}}" placeholder="Search here..." autofocus x-webkit-speech/> </form> When the user submits this form, the keywords entered are sent to Django views.py file via the POST method and this is responsible for returning the results. -
Unable to start Django server within Docker container - TypeError: argument of type 'NoneType' is not iterable
So I've created a dev-container within Docker using VSCode's Remote - Container extension. The config looks as follows: devcontainer.json file: // For format details, see https://aka.ms/devcontainer.json. For config options, see the README at: // https://github.com/microsoft/vscode-dev-containers/tree/v0.238.0/containers/python-3-postgres // Update the VARIANT arg in docker-compose.yml to pick a Python version { "name": "Python 3 & PostgreSQL", "dockerComposeFile": "docker-compose.yml", "service": "app", "workspaceFolder": "/workspace", // Configure tool-specific properties. "customizations": { // Configure properties specific to VS Code. "vscode": { // Set *default* container specific settings.json values on container create. "settings": { "python.defaultInterpreterPath": "/usr/local/bin/python", "python.linting.enabled": true, "python.linting.pylintEnabled": true, "python.formatting.autopep8Path": "/usr/local/py-utils/bin/autopep8", "python.formatting.blackPath": "/usr/local/py-utils/bin/black", "python.formatting.yapfPath": "/usr/local/py-utils/bin/yapf", "python.linting.banditPath": "/usr/local/py-utils/bin/bandit", "python.linting.flake8Path": "/usr/local/py-utils/bin/flake8", "python.linting.mypyPath": "/usr/local/py-utils/bin/mypy", "python.linting.pycodestylePath": "/usr/local/py-utils/bin/pycodestyle", "python.linting.pydocstylePath": "/usr/local/py-utils/bin/pydocstyle", "python.linting.pylintPath": "/usr/local/py-utils/bin/pylint", "python.testing.pytestPath": "/usr/local/py-utils/bin/pytest" }, // Add the IDs of extensions you want installed when the container is created. "extensions": [ "ms-python.python", "ms-python.vscode-pylance" ] } }, // Use 'forwardPorts' to make a list of ports inside the container available locally. // This can be used to network with other containers or the host. "forwardPorts": [5000, 5432, 8000], // Use 'postCreateCommand' to run commands after the container is created. "postCreateCommand": "pip install --user poetry" // Comment out to connect as root instead. More info: https://aka.ms/vscode-remote/containers/non-root. // "remoteUser": "vscode" } docker-compose.yml file: > version: … -
Iterating over a list from an object in Django template
I am trying to iterate over a list that is below an object in a Django template. Unfortunately I am not getting anywhere. This is the object: {'Value1': [8, 5, 4, 7, 4, 5], 'Value2': [], 'Value3': []} I am doing in the template something like: {% for entry in data %} <tr> <td>{{ entry }}</td> <td>{{ entry.0 }}</td> </tr> {% endfor %} or {% for entry in data %} <tr> <td>{{ entry }}</td> {% for i in entry %} <td>{{ i }}</td> {% endfor %} </tr> {% endfor %} But all I am getting is just the first letter of the key. -
Displaying D3.js Chart with Django Backend
I am learning to build dashboard using Django as backend and D3.js for visualization. Following is my index.html: {% load static %} <html> <script src="https://d3js.org/d3.v7.min.js"></script> <body> <h1> Hello! </h1> <script src={% static "js\linechart.js" %}> var data = {{ AAPL|safe }}; var chart = LineChart(data, { x: d => d.date, y: d => d.close, yLabel: "↑ Daily close ($)", width, height: 500, color: "steelblue" }) </script> </body> </html> Data AAPl is extracted from database and the views.py is as follows: from django.shortcuts import render from django.http import HttpResponse from cnxn import mysql_access import pandas as pd # Create your views here. def homepage(request): sql = ''' select Date, Close from tbl_historical_prices where ticker = 'AAPL' ''' cnxn = mysql_access() conn = cnxn.connect() df = pd.read_sql(sql, con=conn) context = {'AAPL':df.to_json()} return render(request, 'index.html', context=context) Function line chart can be viewed here which is being used in js\linechat.js in index.html file. I can see the Hello! being displayed on the page but can't see the line chart. I am unable to debug the problem. No errors found in console tab either. How can I display the line plot? I've added the current page display in attached image. -
How to remove "Unresolved refernce" errror in PyCharm I have changed python interpreter so many times but not working
enter image description here enter image description here enter image description here Guys please help me what should I do? I tried so many times to change the Python Interpreter path also I have reinstalled my python and pycharm but this error is not resolving please help me :( -
Rendering phone numbers in flask jinja2 urlize filter
By using the 'urlize' filter in jinja2 in flask templates; every text website link gets rendered into clickable. But I can't make phone numbers turn <a href='tel:+966850766817'> "phone number" <a/> but they don't render this way. any suggestions? -
django-import-export how to deal with the import_id_fields is unique_together key?
the parentmodel is class Work(models.Model): po = models.ForeignKey(Po, verbose_name="合同号", on_delete=models.CASCADE) remark = models.CharField(max_length=100, verbose_name="备注说明") create_time=models.DateField(verbose_name="日期") class Meta: verbose_name = "工作清单" verbose_name_plural = verbose_name unique_together=("po","remark") def __str__(self): return self.remark and the children model is class Acceptance(models.Model): work = models.ForeignKey(Work, on_delete=models.CASCADE, verbose_name="工作清单") detail=models.ForeignKey(Detail,on_delete=models.CASCADE,verbose_name="验收物品") accecpt_time = models.DateField(verbose_name="验收日期") num = models.IntegerField(verbose_name="验收数量", validators=[MinValueValidator(1)]) person = models.CharField(max_length=100, verbose_name="验收人员") class Meta: verbose_name = "验收清单" verbose_name_plural = verbose_name unique_together=("accecpt_time","work") I want to ask about how to defind the Acceptance Resource when the work foreign_key is unique_together key? my test code is class AcceptanceSource(resources.ModelResource): work = fields.Field(attribute="work", widget=ForeignKeyWidget(Work, 'remark'), column_name="工作清单") detail = fields.Field(attribute="detail", widget=ForeignKeyWidget(Detail, "name"), column_name="物料清单") po = fields.Field(attribute="work__po", column_name="合同号", widget=ForeignKeyWidget(Po, "po_num")) num = fields.Field(attribute="num", column_name="验收数量") accecpt_time = fields.Field(attribute="accecpt_time", column_name="验收时间") person = fields.Field(attribute="person", column_name="验收人员") but it get error like this: 行号: 1 - get() returned more than one Work -- it returned 2! -
How to do simple arithmetic calculator in django template?
I want to show two sets of number from model in the django template for the same. I am using for loop to get each row data of the table to show in template as below : {% for a in vis %} {a.numone} {a.numtwo} {% endfor %} its working fine!. Now, I want to do simple arithmetic calculation by using this numbers. say for example add, sub, div, multiply this two number and show it in template. How to do it? -
unable to post item to database, Django
I have a model called CurrentBestSellersListItem, with an integer field, some CharFields, and a URLField. I also have a serializer for the given model. I am able to create instances of the CurrentBestSellersListItem in the database manually from http://127.0.0.1:8000/admin/lists/currentbestsellerslistitem/add/, i.e. from the admin panel, but am unable to create them on another route. The other route I have (in urls.py) is: path('list-items-create/', views.create_saved_list_item, name='create_saved_list_item'), and the create_saved_list_item function in views.py is: @api_view(['POST']) def create_saved_list_item(request): json_object = json.dumps(request.data, indent = 1) serializer = CurrentBestSellersListItemSerializer(data=json_object) if serializer.is_valid(): serializer.save() return Response(serializer.data) If I go to http://127.0.0.1:8000/api/list-items-create/ and POST the following data: { "rank": 555, "weeks_on_list": 555, "publisher": "a", "description": "b", "title": "c", "author": "d", "amazon_product_url": "amazon.com/books/5" } then I get back this response: HTTP 200 OK Allow: OPTIONS, POST Content-Type: application/json Vary: Accept {} and the item is NOT added to the connected database, as expected. Can any of you spot where the error is? -
Djangochannelsrestframework custom action doesn't work
I want to create custom action like in documentation but it answer that Method doesn't allow Documentation: https://pypi.org/project/djangochannelsrestframework/ "Adding Custom actions" block other websocket urls worked correctly My source code: consumers.py: from games.models import GameLaunchers, GamesCategories, Games, Tournires from news.models import News from games.serializers import GamesCategoriesSerializer, GameLaunchersSerializer, GameSerializer, TourniresSerializer from news.serializers import NewsListSerializer from market.models import MarketCategory, MarketProductsType, MarketProducts, MarketOrders from market.serializers import MarketCategoriesSerializer, MarketProductsTypeSerializer, MarketProductsSerializer, MarketOrdersListSerializer from django.core import serializers from djangochannelsrestframework.settings import api_settings from django.http import Http404 from djangochannelsrestframework.generics import GenericAsyncAPIConsumer from djangochannelsrestframework.consumers import AsyncAPIConsumer from djangochannelsrestframework.decorators import action from djangochannelsrestframework.mixins import ( ListModelMixin, RetrieveModelMixin, PatchModelMixin, UpdateModelMixin, CreateModelMixin, DeleteModelMixin, PaginatedModelListMixin ) class GamesLaunchersAddConsumer( CreateModelMixin, GenericAsyncAPIConsumer, ): serializer_class = GameLaunchersSerializer class GameLaunchersConsumers(GenericAsyncAPIConsumer): queryset = GameLaunchers.objects.all() serializer_class = GameLaunchersSerializer @action async def send_email(self, request_id, some=None, **kwargs): # do something async return {'response_with': 'some message'}, 200 routing.py from django.urls import path from socketapp import consumers # from socketapp.views import GamesViewSet from django.urls import re_path from djangochannelsrestframework.consumers import view_as_consumer # from djangochannelsrestframework.consumers import view_as_consumer # from games.views import GameLaunchersAddView, GameLaunchersView websocket_urlpatterns = [ re_path(r'ws/games/launchers/add', consumers.GamesLaunchersAddConsumer.as_asgi()), re_path(r'ws/games/launchers', consumers.GameLaunchersConsumers.as_asgi()), ] Sending message: { "action": "send_email", "request_id": 42, "some": "value passed as keyword argument to action" } I got this error: { "errors": [ "Method …