Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Working on Django forms, I will like to use input field as variable for a regular expression function? not working as I have it
passing input of form search = form.cleaned_data["search"] return get_search(request,search, list1) *using input form as variable def get_search(request,search, list): # convert list to string for re entries = str1.join(list) # using pattern to match items in my string?? re pattern = re.compile(r'{}.*.format(search)', re.IGNORECASE) matches = pattern.finditer(entries) # ** passing variables to a new template but it is not working!! return render(request, "encyclopedia/search.html", { "matches": matches }) -
Remove empty spaces in assertDictEqual to pass Flake8
I'm fixing code to normalize in PEP8 by Flake8. One of the problems is long lines that I need skip lines to accomplish Flake8. This is my return that I skip line using : expected_return = { "error": { "message": None, "type": "You are logged as admin. This endpoint requires\ a customer or an anonymous user.", "detail": None, } } Using from django.test import TestCase with Django, my assertion is: self.assertDictEqual(self.deserialize(response.content), expected_return) My test don't pass because the assert reads with spaces: AssertionError: {u'error': {u'message': None, u'type': u'You are logged as admin. This endpoint [truncated]... != {u'error': {u'message': None, u'type': u'You are logged as admin. This endpoint [truncated]... {u'error': {u'detail': None, u'message': None, - u'type': u'You are logged as admin. This endpoint requires a customer or an anonymous user.'}} + u'type': u'You are logged as admin. This endpoint requires a customer or an anonymous user.'}} I tried to use self.assertMultiLineEqual too, but other errors appers. What solutions usually you use to skip lines, in accordance to PEP8 and do not receiving with this error with unittest? Best regards. -
Get user's last login time in Django using LDAP Authentication
I tried user.last_login in order to get the last login time for LDAP user. But i'm receiving null value although user has done login several times. It works for Django users like admin. Is there any way around this? -
Is it possible translate URL's with Rosetta?
Is it possible to translate the URLs with Rosetta? Example: Spanish: domain.com/es/contacto English: domain.com/en/contact Check that Contact has the translation in the Spanish URL. Many thanks Alfredo -
Django Forms Invalid but no Errors
Maybe it might be an oversight but I do not know the point where I am getting it wrong. My form is rendered correctly but it keeps failing without errors. forms.py from crispy_forms.helper import FormHelper from django import forms from django.utils.translation import ugettext as _ class BeneficiaryForm(forms.Form): """Add Beneficiary template form""" # Form fields account_currency = forms.ModelChoiceField(queryset=Currency.objects.all(), empty_label=_('Select account currency')) bank_account_type = forms.CharField(max_length=50, required=False) email = forms.CharField(max_length=150, required=False, help_text=_("We'll notify them when a transfer is made")) name = forms.CharField(max_length=50, required=False) swift_code = forms.CharField(max_length=11, required=False, widget=forms.TextInput(attrs={'placeholder': 'MSBCCNBJ001'})) iban = forms.CharField(max_length=34) def __init__(self, *args, **kwargs): super(BeneficiaryForm, self).__init__() self.helper = FormHelper() self.helper.form_show_labels = False views.py def beneficiaries(request): """View function for viewing Beneficiaries and adding a Beneficiary instance""" if request.method == 'POST': form = BeneficiaryForm(request.POST) if form.is_valid(): print("Form is valid") print(request.POST['bank_account_type']) print(request.POST['email']) print(request.POST['name']) print(request.POST['iban']) print(request.POST['swift_code']) print("Form is invalid") print(form.errors) form = BeneficiaryForm() context = { 'form': form } return render(request, 'dashboard/beneficiaries.html', context) and in my rendered form. I have this block to show errors and nothing shows up -
django.db.utils.IntegrityError: NOT NULL constraint failed fom Postman
I am trying to create a simple model with foreign keys using Django rest framework. This are the models: class Route(models.Model): place_origin = models.ForeignKey( Place, null=False, on_delete=models.DO_NOTHING) class Place(models.Model): name = models.CharField(max_length=50, null=False) This are the serializers for each model: class PlaceSerializer(serializers.ModelSerializer): class Meta: model = Place fields = ["id", "name"] class RouteSerializer(serializers.ModelSerializer): place_origin = PlaceSerializer(many=False, read_only=True) class Meta: model = Route fields = ["id", "place_origin"] This RouteSerializer has the place_origin property in order to show the place details(all the fields from it) when I am looking at the route detail. What I mean is for routes I want to display: [ { "id": 1, "place_origin": { "id": 1, "name": "New york" } }, { "id": 2, "place_origin": { "id": 2, "name": "Boston" } } ] And not just: [ { "id": 1, "place_origin": 1 }, { "id": 2, "place_origin": 2 } ] This is the view: @api_view(['POST']) def routes_new_route_view(request): """ Create a new route """ if request.method == "POST": data = JSONParser().parse(request) place_origin = Place.objects.get(id=data["place_origin"]) data["place_origin"] = PlaceSerializer(place_origin) data["place_origin"] = data["place_origin"].data serializer = RouteSerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) else: return JsonResponse(serializer.errors, status=status.HTTP_400_BAD_REQUEST) I want to send the request from postman this way: { "place_origin": 3 } But … -
Reverse for 'create_chat' with arguments '('',)' not found. 1 pattern(s) tried: ['create_chat/(?P<id>[0-9]+)/$']
I am building chat app and I am using Django Version 3.8.1. I am stuck on Error. This view is for Chat with friend private. views.py def create_chat(request,id): from_user = get_object_or_404(User,id=id) user1 = request.user user2 = from_user chat_box = ChatBox(user_1=user1,user_2=user2) chat_box.save() urls.py path('create_chat/<int:id>/',views.create_chat,name='create_chat'), profile.html <a href="{% url 'create_chat' from_user.id %}">Chat</a> The Problem When i open profile.html in browser this error is occured named :- Reverse for 'create_chat' with arguments '('',)' not found. 1 pattern(s) tried: ['create_chat/(?P<id>[0-9]+)/$'] I will really appreciate your Help. Thank You In Advance. -
Do I need to lock a SQL update query with an "is null" check?
I have an API endpoint that can be called multiple times (in theory), even though it should be only called once. The API endpoint basically just performs an update operation that looks like this: MyModel.objects.filter( pk=kwargs["pk"], accessed_at__isnull=True, ).update(accessed_at=now()) I'm wondering what happens if this API endpoint gets called by another user in parallel. Is this vulnerable to a race condition or is it safe because I'm doing the isnull check before which should prevent that this field gets updated after setting it once? This is more like a SQL related question because I'm not sure how Postgres handles these situations. Or should I explicitly lock the row to prevent parallel updates with select_for_update? -
Language selection of third party packages, Django
I am dealing with this problem for 2 days approximately. Let me tell you what I did and why I did then asking my question. I have a project that I want to support multilanguage but right now it should support only one language, I will add other languages over time. So my settings.py has these: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'phonenumber_field', 'project.apps.ProjectConfig', ] MIDDLEWARE = [ ... 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', ... ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR / 'project/templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ ... 'django.template.context_processors.i18n' ], }, }, ] LANGUAGE_CODE = 'tr' LANGUAGES = [ ('tr', 'Türkçe') ] LOCALE_PATHS = [ BASE_DIR / 'project/locale', ] TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True I translated my forms.py and models.py files only for now. and ran makemessages: python manage.py makemessages -l tr --ignore=venv/* (I ignored venv packages) python manage.py compilemessages --ignore=venv/* after all of these, my website was correctly translated to my desired language (which is the only language now) also Django admin page is "tr" now because the project language is set to "tr". Form errors are "tr" too. BUT. I am using the third-party phonenumber_field … -
Use context var to access attribute in django template
I'm actually building a template to render several models in the same table format. I use a class based listviews to access the model. I've also overwritten the context to give the fields needed for each type of model : views.py class ProductListView(ListView): template_name = 'myApp/table.html' model = Product def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['fields'] = ['name', 'product_type', 'cost', 'margin'] return context In the template, I'd like to loop through the given fields, by doing : {% for element in object_list %} <tr> {% for field in fields %} <td>{{ element.field }}</td> {% endfor %} </tr> {% endfor %} But it does not display anything. I've read in the documentation (https://docs.djangoproject.com/en/3.1/ref/templates/language/) that : Note that “bar” in a template expression like {{ foo.bar }} will be interpreted as a literal string and not using the value of the variable “bar”, if one exists in the template context. and I understand what I'm doing wrong but I can't figure out how to display this field. I can't just explicitely write the field names in the template because I want this template to be able to handle differents models. Is there any way to loop through the given fields ? -
Serializer with other Serializer as attribute not parsing incoming request data
In Django Rest Framework I have this serializer: class RecipeSerializer(serializers.ModelSerializer): user = UserSerializer(read_only=True, many=False) id = serializers.ReadOnlyField() ingredients_list = IngredientCompositionSerializer(read_only=False, many=True) def create(self, validated_data): validated_data['user'] = self.context['request'].user return super().create(validated_data) class Meta: model = Recipe fields = ['user', 'id', 'name', 'description', 'ingredients_list', 'created', 'modified'] In his ViewSet, when I try to create a new Recipe, I got an error for ingredients_list field saying that it's a required field (true), but I'm sending its value as Json in the request. This is how request.data is reaching the create function in the ViewSet of RecipeSerializer. I'm using Postman: <QueryDict: { 'name': ['a new recipe test'], 'description': ['the description'], 'ingredients_list': [ '{"id": 4, "quantity": 350}, {"id": 3, "quantity": 500}' ] }> Also tried with sending ingredients_list between [] but the error is the same. Here is IngredientCompositionSerializer, which represents ingredients_list in RecipeSerializer: class IngredientCompositionSerializer(serializers.HyperlinkedModelSerializer): id = serializers.PrimaryKeyRelatedField(source='ingredient.id', queryset=Ingredient.objects.all()) name = serializers.ReadOnlyField(source='ingredient.name') class Meta: model = IngredientComposition fields = ['id', 'name', 'quantity'] # quanitity is just a Django's DecimalField When I check serializer.data in RecipeViewSet.create() function, it only has name and description. What am I doing wrong? Thanks! -
Database entry not created by clicking on the accept friend request button
I am writing the view for accepting the friend request, I dont know what is happening, i am fetching jason data to the view but i doesn't working . i have tried all of the solutions that are on this website but they doesn't work for me here is my Javascript <script > function acceptFriendRequest(friend_request_id, uiUpdateFunction){ var url = "{% url 'friend:friend-request-accept' friend_request_id=53252623623632623 %}".replace("53252623623632623", friend_request_id) $.ajax({ type: 'GET', dataType: "json", url: url, timeout: 5000, success: function(data) { console.log("SUCCESS", data) if(data['response'] == "Friend request accepted."){ // ui is updated } else if(data['response'] != null){ alert(data['response']) } }, error: function(data) { console.error("ERROR... this is the error from accept", data) alert("Something went wrong") }, complete: function(data){ uiUpdateFunction() } }); } Here is my view def accept_friend_request(request, *args, **kwargs): user = request.user payload = {} if request.method == "GET" and user.is_authenticated: friend_request_id = kwargs.get("friend_request_id") # print(f"friend request id {friend_request_id}") if friend_request_id: friend_request = FriendRequest.objects.get(pk=friend_request_id) # print(f"friend request object {friend_request}") # confirm that is the correct request if friend_request.receiver == user: if friend_request: # found the request. Now accept it friend_request.accept() payload['response'] = "Friend request accepted." else: payload['response'] = "Something went wrong." else: payload['response'] = "That is not your request to accept." else: payload['response'] = … -
ForeignKey Constraint failed
I have followed Coreys blog app, and I have integrated a comments function. I now appear to have an issue when trying to delete a comment WITH a comment attached. after reading about a million posts on stackoverflow, most people refer to the USER on_delete, but mine already appears to be on CASCADE. Odd issue. a post without a comment can be deleted by the user the issue is a post with a comment can't be deleted (foreignkey constraint issue) error: POST Request URL: http://127.0.0.1:8000/post/31/delete/ Django Version: 3.1.4 Exception Type: IntegrityError Exception Value: FOREIGN KEY constraint failed I should be able to create a post, have multiple users comment on said post. Then if the user of the post wishes to delete the post all comments should be deleted(obviously- cascade has been added) at the moment the only way i can get around this, is to delete a users comments and then delete the post. models.py (post function) class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) category = models.CharField(choices=cat_new_choice, max_length=200,default='Onboarding') likes = models.ManyToManyField(User, related_name='blog_posts', blank=True) #user who created this post, then the user gets deleted - what happens to the post? this will … -
Is it possible to list files in a dir with Azure storages
I'm using Django and django-storages[azure] as backend. But i can't to find out to list dir the files instead I have to use snippets like this: block_blob_service.list_blobs(container_name='media', prefix=folderPath)] this is not working: listdir(absoluteFolderPath) In storages/backend/azure_storage.py I found this part: def listdir(self, path=''): """ Return directories and files for a given path. Leave the path empty to list the root. Order of dirs and files is undefined. """ files = [] dirs = set() for name in self.list_all(path): n = name[len(path):] if '/' in n: dirs.add(n.split('/', 1)[0]) else: files.append(n) return list(dirs), files But how can I use it? regards Christopher. -
Django React Serving Together Page not found (404)
I develop an application using Django and React. I want to serving Django and React together. I create an build in react. I use it in Django. This is urls.py ; urlpatterns = [ url(r'^$', views.index), ] and views.py; def index(request): return render(request, "build/index.html") When I run development server there is no any error but when ı want to go url directly ; http://www.x.com:8000/accounts I got page not found (404) error. -
The view urlshort.views.page_redirect didn't return an HttpResponse object. It returned None instead
I'm making a url shortener with django. I have a form that has a long_url attribute. I'm trying to get the long_url and add it to a redirect view with a HttpResponseRedirect. # Form from .models import ShortURL from django import forms class CreateNewShortURL(forms.ModelForm): class Meta: model=ShortURL fields = {'long_url'} widgets = { 'long_url': forms.URLInput(attrs={'class': 'form-control'}) } # View def page_redirect(request, url): if request.method == 'GET': form = CreateNewShortURL(request.GET) if form.is_valid(): original_website = form.cleaned_data['long_url'] return HttpResponseRedirect(original_website) When I go to the link, it gives me The view urlshort.views.page_redirect didn't return an HttpResponse object. It returned None instead. Does anyone know why this is happening? -
AuthFailed at /social-auth/complete/linkedin-oauth2/
I am a bit confuse while LinkedIn r_basicprofile is not authorized for my application after completing the necessary process. I have check some related question on SO but it appears that solutions are not working for me maybe because of the different changes on LinkedIn social oauth. Authentication failed: Scope &quot;r_basicprofile&quot; is not authorized for your application My backend settings, frontend and API are correct, but I don't know why it is not working. 'social_core.backends.linkedin.LinkedinOAuth2', SOCIAL_AUTH_LINKEDIN_OAUTH2_KEY = 'correct' SOCIAL_AUTH_LINKEDIN_OAUTH2_SECRET = 'correct' SOCIAL_AUTH_LINKEDIN_OAUTH2_SCOPE = ['r_basicprofile', 'r_emailaddress'] SOCIAL_AUTH_LINKEDIN_OAUTH2_FIELD_SELECTORS = ['email-address', 'formatted-name', 'public-profile-url', 'picture-url'] SOCIAL_AUTH_LINKEDIN_OAUTH2_EXTRA_DATA = [ ('id', 'id'), ('formattedName', 'name'), ('emailAddress', 'email_address'), ('pictureUrl', 'picture_url'), ('publicProfileUrl', 'profile_url'), ] frontend <li class="linkedin"><a href="{% url "social:begin" "linkedin-oauth2" %}">Login with LinkedIn</a></li> urls.py path('social-auth/', include('social_django.urls', namespace='social')), -
UnboundLocalError: local variable '_' referenced before assignment
Seems that django/python is not recognizing that I want to use this library: from django.utils.translation import gettext as _ If I do: {"id": user.pk, "status": _("Password changed")} He gives an error: UnboundLocalError: local variable '_' referenced before assignment He thinks that I want to reference to a local variable, while I just wanted to use the translation function. In other parts of my application, the translation does work perfect. How is this possible? Thank you -
Django MySQL Raw
So I want to get data from my mysql database. I want to get the street, name,... All my database data. So I want to make a django-mysql-raw query but I don't get my data instead I get: Data object (1) Can anybody help me? So and this is my code if you need it: # Create your models here. class Data(models.Model): userid = models.AutoField(primary_key=True) name = models.CharField(max_length=100, blank=True, null=True) firstname = models.CharField(max_length=100, blank=True, null=True) age = models.IntegerField(blank=True, null=True) street = models.CharField(max_length=100, blank=True, null=True) country = models.CharField(max_length=100, blank=True, null=True) postcode = models.IntegerField(blank=True, null=True) print("\n\n\n-----------") for p in Data.objects.raw('SELECT userid FROM Data'): print(p) print("-----------\n\n\n")``` -
is it fine to name django apps with capital letters?
In django I named my app as "Home". I created a class named "images" inside models.py and make migrations thus I got table created in my database as "Home_images". but the problem arises when I tried to execute raw query on that table. query = "select * from Home_images" cursor.execute(query) string query gets converted into smaller letters so django couldn't find table named "Home_images". -
Installing mod_wsgi in windows throws error using pip
C:\Users\admon>pip install mod_wsgi Collecting mod_wsgi Using cached mod_wsgi-4.7.1.tar.gz (498 kB) Using legacy 'setup.py install' for mod-wsgi, since package 'wheel' is not installed. Installing collected packages: mod-wsgi Running setup.py install for mod-wsgi ... error ERROR: Command errored out with exit status 1: command: 'c:\users\admon\appdata\local\programs\python\python39\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\admon\\AppData\\Local\\Temp\\pip-install-6eym66br\\mod-wsgi_1f52cc6d2c7e4894895a1e698895bdcb\\setup.py'"'"'; __file__='"'"'C:\\Users\\admon\\AppData\\Local\\Temp\\pip-install-6eym66br\\mod-wsgi_1f52cc6d2c7e4894895a1e698895bdcb\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\admon\AppData\Local\Temp\pip-record-08vnzxv4\install-record.txt' --single-version-externally-managed --compile --install-headers 'c:\users\admon\appdata\local\programs\python\python39\Include\mod-wsgi' cwd: C:\Users\admon\AppData\Local\Temp\pip-install-6eym66br\mod-wsgi_1f52cc6d2c7e4894895a1e698895bdcb\ Complete output (33 lines): c:\users\admon\appdata\local\programs\python\python39\lib\distutils\dist.py:274: UserWarning: Unknown distribution option: 'bugtrack_url' warnings.warn(msg) running install running build running build_py creating build creating build\lib.win-amd64-3.9 creating build\lib.win-amd64-3.9\mod_wsgi copying src\__init__.py -> build\lib.win-amd64-3.9\mod_wsgi creating build\lib.win-amd64-3.9\mod_wsgi\server copying src\server\apxs_config.py -> build\lib.win-amd64-3.9\mod_wsgi\server copying src\server\environ.py -> build\lib.win-amd64-3.9\mod_wsgi\server copying src\server\__init__.py -> build\lib.win-amd64-3.9\mod_wsgi\server creating build\lib.win-amd64-3.9\mod_wsgi\server\management copying src\server\management\__init__.py -> build\lib.win-amd64-3.9\mod_wsgi\server\management creating build\lib.win-amd64-3.9\mod_wsgi\server\management\commands copying src\server\management\commands\runmodwsgi.py -> build\lib.win-amd64-3.9\mod_wsgi\server\management\commands copying src\server\management\commands\__init__.py -> build\lib.win-amd64-3.9\mod_wsgi\server\management\commands creating build\lib.win-amd64-3.9\mod_wsgi\docs copying docs\_build\html\__init__.py -> build\lib.win-amd64-3.9\mod_wsgi\docs creating build\lib.win-amd64-3.9\mod_wsgi\images copying images\__init__.py -> build\lib.win-amd64-3.9\mod_wsgi\images copying images\snake-whiskey.jpg -> build\lib.win-amd64-3.9\mod_wsgi\images running build_ext building 'mod_wsgi.server.mod_wsgi' extension creating build\temp.win-amd64-3.9 creating build\temp.win-amd64-3.9\Release creating build\temp.win-amd64-3.9\Release\src creating build\temp.win-amd64-3.9\Release\src\server C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\BIN\x86_amd64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -IC:\xampp\apache/include -Ic:\users\admon\appdata\local\programs\python\python39\include -Ic:\users\admon\appdata\local\programs\python\python39\include -IC:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\INCLUDE -IC:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\ATLMFC\INCLUDE -IC:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt /Tcsrc/server\mod_wsgi.c /Fobuild\temp.win-amd64-3.9\Release\src/server\mod_wsgi.obj mod_wsgi.c c:\users\admon\appdata\local\temp\pip-install-6eym66br\mod-wsgi_1f52cc6d2c7e4894895a1e698895bdcb\src\server\wsgi_apache.h(39): fatal error C1083: Cannot open include file: 'ws2tcpip.h': No such file … -
Django Graphene how do i add custom fields to ObjectType of type model Object
class StoreType(DjangoObjectType): is_expired = graphene.Boolean(source='is_expired') is_pending = graphene.Boolean(source='is_pending') ranking = graphene.Int(source='ranking') success_rate = graphene.Float(source='success_rate') total_revenue = graphene.Float(source='total_revenue') best_selling_product = graphene.????(source='best_selling_product') class Meta: model = Store exclude = ['user'] for fields like is_expired, ranking etc.. i can easily see what type they are to be represented in e.g graphene.Int and graphene.Boolean, but the best_selling_product field is return Django object model.. here is the Model property below class Store(models.Model): .... def best_selling_product(self): products = self.orders.all().values_list('variant__product', flat=True) product_id = products.annotate(count=models.Count( 'variant__product')).order_by("-count")[0] return self.products.get(id=product_id) so what should i use to represent this and how? graphene.???? -
Django rest_framework datetime_format with milliseconds
Django REST_FRAMEWORK has a setting for the date format, e.g for timestamp in seconds: REST_FRAMEWORK = { 'DATETIME_FORMAT': '%s', } so my API output is for instance: {"creation_date":"1610700530"} How would I tell it to output a timestamp in milliseconds? E.g.: {"creation_date":"1610700530000"} -
Serializer not returning clean data in django-channels
I implemented serializer in my consumers.py to get data for a form I submit on the front end. But it doesn't seem to be returning ordered data. My consumers.py : import json from .models import Order from channels.db import database_sync_to_async from channels.generic.websocket import AsyncWebsocketConsumer from django.core import serializers from .serializers import OrderSerializer class WSConsumer(AsyncWebsocketConsumer): @database_sync_to_async def _get_order_info(self, number): j = Order.objects.get(order_number=number) response = OrderSerializer(instance=j).data return response async def connect(self): self.groupname = 'new_orders' await self.channel_layer.group_add( self.groupname, self.channel_name, ) await self.accept() async def disconnect(self, code): await self.channel_layer.group_discard( self.groupname, self.channel_name, ) await super().disconnect(code) async def take_order(self, event): number = event['number'] details = event['details'] info = await self._get_order_info(number) await self.send(text_data=json.dumps({ 'number' : number, 'details' : details, 'info' : info, })) async def receive(self, text_data): order_data_json = json.loads(text_data) number = order_data_json['number'] details = order_data_json['details'] info = order_data_json['info'] await self.channel_layer.group_send( self.groupname, { 'type': 'take_order', 'number' : number, 'details' : details, 'info' : info, } ) Here is what is returns in the console: {number: "50001", details: "fdgf", info: {…}} details: "fdgf" info: fulfilled_by: null id: 157 is_fulfilled: false order_date_time: "2021-01-15T10:37:46.200495Z" order_details: "fdgf" order_number: 50001 taken_by: 14 __proto__: Object number: "50001" __proto__: Object I feel it should return this: {number: "50001", details: "fdgf", info: fulfilled_by: null id: … -
How to return a response after django form is submitted?
I am new to django framework and application development. I am building an application to take some user input then process the data and save in the database. I am using Django forms to accept some input from user and send to my views. The data sent by user will be processed in the backend and then accordingly a response will be sent to the user after processing the data. I am able to successfully send the data from my template to the views. However, i am not getting how to send a response back to the template for user. Any suggestions on this would be very helpful.