Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django csrf token error only with uploading file
When update user profile model using model form in django: Raise csrf token missing or incorrect only with uploading file. In case of without file attached, I can update other fields. model.py file: class UserProfile(models.Model): user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE) avatar = models.ImageField(upload_to='avatars', blank=True) first_name = models.CharField(blank=True, max_length=128) last_name = models.CharField(blank=True, max_length=128) birthday = models.DateField(blank=True, default='1990-12-01') town = models.CharField(blank=True, max_length=128) forms.py file: class UserProfileForm(forms.ModelForm): class Meta: model = UserProfile fields = ('avatar', 'first_name', 'last_name', 'birthday', 'town') in views.py file: @method_decorator(login_required, name='dispatch') class ProfileView(FormView): form_class = UserProfileForm template_name = 'profiles/profile.html' def dispatch(self, request, *args, **kwargs): self.username = kwargs.get('username') self.user = get_user_model().objects.get(username=self.username) self.userprofile = UserProfile.objects.get_or_create(user=self.user)[0] self.form = UserProfileForm({'first_name': self.userprofile.first_name, 'last_name': self.userprofile.last_name, 'avatar': self.userprofile.avatar, 'birthday': self.userprofile.birthday, 'town': self.userprofile.town) return super().dispatch(request, *args, **kwargs) def get_context_data(self, **kwargs): return {'userprofile': self.userprofile, 'selecteduser': self.user, 'form': self.form} def post(self, request, *args, **kwargs): return super().post(request, *args, **kwargs) def get_form(self, *args, **kwargs): return self.form_class(self.request.POST, self.request.FILES, instance=self.userprofile) def form_valid(self, form): form.save(commit=True) return redirect('profiles:profile', self.user.username) in profile.html file: <form method="post" action="." enctype="multipart/form-data"> {% csrf_token %} {{ form.non_field_errors }} {% for field in form %} <div class="form-group"> {{ field }} {{ field.errors }} </div> {% endfor %} <input type="submit" class="btn btn-primary" value="Update" /> </form> and software viersions: ubuntu 18.04 nginx 1.14.0 uwsgi 2.0.18 Django … -
Html content of Django application doesn't update after git pull and gunicorn restart
I'm running a Django website on Ubuntu 18.04. I have Nginx and Gunicorn running and website loading. I have initially installed it using git, and now as I'm trying to update it, something weird is happening. What I did: Pulled new code from git Made sure files are updated with nano Restarted Gunicorn (website still shows old html) Restarted server, then Nginx and Gunicorn (still old html) At this point I don't know where to check because all the files are new and it should have updated the website after restart. -
Ajax selected dropdown value and pass
I am trying to do following: user will select the value from the drop down menu, I would like to capture the data and pass to value to check if it exits and filter it. Using django view to fetch the media data files list. I would like to filter base on selected data site. VIEW @ajax_request def listofiles(request, *args, **kwargs): dir_name = "configurations" template_name = 'loadlistofiles.html' path = os.path.join(settings.MEDIA_ROOT, dir_name) filelist = [] context = {'file': filelist} for f in os.listdir(path): if f.endswith(".pdf"): # to avoid other files filelist.append("{}{}/{}".format(settings.MEDIA_URL, dir_name, f)) return render(request, template_name, {'file': filelist}) Above code will provide the list of all the files. I would like to filter it down using the dropdown select HTML AJAX <script> $(document).ready(function() { $("#files").submit(function() { // catch the form's submit event $.ajax({ url: 'loadlistofiles.html', type: $(this).attr('GET'), data: $(this).serialize(), // get the form data success: function(data) { // on success.. $("#fetchdata").html(data); // update the DIV } }); return false; }); }); </script> How to filter based on dropdown select value and check if the string in the file. For example: File name: dublin.aus1.pdf Dropdown will have a list like: AUS1, CH1, IND1 Like to check if the aus1 is in the … -
Use m2m_changed to modify original instance
When someone adds or removes an item from the additional_options field, I am catching that modification with the m2m_changed signal. If I wanted to use the data found in the m2m_changed signal to modify the original instance, how would I go about doing that? For example: class Topping(models.Model): name = models.CharField(max_length=100) class Pizza(models.Model): ingredients = models.CharField(max_length=100) toppings = models.ManyToManyField(Topping) def save(self, *args, **kwargs): super().save(*args, **kwargs) def update_data(sender, **kwargs): instance = kwargs['instance'] toppings = instance.toppings.all() for topping in toppings: instance.ingredients += f"{topping.name}, " print(instance.ingredients) # this will print the list of ingredients: "" instance.save() print(instance.ingredients) # this prints: "" and does not update the object in the admin m2m_changed.connect(update_data, sender=Pizza.toppings.through) In the example above, when instance.save() is called, the value in instance.ingredients reverts back to the default value. I believe this has something to do with the reverse parameter but I don't quite understand how to use it. -
Django Error: "ManyToOneRel object has no attribute verbose name"
I have a model named dashboard. Dashboard has a field called model_name which is the just a charfield. I have another field called Dashboard_Field which im trying to populate when the server initially starts. I do this by getting the dashboards and models. However I get the error "ManyToOneRel object has no attribute verbose name" for s_dashboard in dashboard: for models in model fields = model._meta.get_fields() for sfield in fields: if sdashboard.model_name == model._meta.verbose_name: field = Dashboard_Field.objects.create(field=sfield.verbose_name, dashboard=sdashboard) -
In the backend, can you access data from previous requests?
This is more of a theory question, so I'm not going to post any code. On the frontend, the user types in a search command. On the backend (Django in my case), it hits an API, the results of the search are saved into a Django View in views.py. On the frontend, the user interacts with this returned data and sends another request. On the backend, is the data from the first Django View still available for use? How do you access it? (The data is also in the frontend and I can send it with the second request. But if it's still stored on the backend then I wouldn't need to.) -
Error when making $http.post request "blocked by CORS policy"
Setup: I am running a webapp on DJango with AngularJS Situation: A peer has provided me an API link and I am trying to make a POST request through my webapp. I am currently running it through my app's angularjs controller and I get this error: Access to XMLHttpRequest at 'https://stage-xxxx.xxxx.com/api/po/createPO' from origin 'https://aggrisellshadow.aggrigator.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' Here is my Code - JS/Controller: $scope.sendAPI = function(){ console.log("sending API") var testData = { "gpo_number": "new Po", "plu_code": "123456712", "farmers_userId": "sujatha", "farmers_email": "sujatha@gmail.com", "delivery_date": "09/03/2019", "quantity_value": "100", "quantity_unit": "test Quan", "foodhub_userId": "sujatha", "foodhub_email": "sujatha@gmail.com" } $http.defaults.headers.post = { 'Content-Type': "application/json", 'tenant': 'XXXXXXapiTenent', "apikey": "XXXXXXX", "Access-Control-Allow-Credentials": true } $http.post("https://xxx.xxxx.xxxxx",testData,{data:JSON}) .success(function(data,status,headers){console.log("success")}) .error(function(data,status,headers){console.log("fail");console.log(data);console.log(headers);console.log(status)}) } Is this because I am trying to do this through my js and not through python? I can't seem to figure this out. Any help will be appreciated. Thank you ahead of time! -
Activate Virtual enviornment in Cpanel without SSH
I am deploying a django based web application. My hosting provider doesn't allow SSH access. So I deployed my application via python setup app. But it doesn't load static files altough it loads media files. so i wanted to execute "python manage.py collectstatic" But Only way to execute python command is through python setup app. But with the latest upgrade of Cpanel Python Setup Interface is fully different. I can't find a way to activate my virtualenv and execute command. #My Static configuration in Settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'static') #My Urls.Py urlpatterns = [ path('admin/', admin.site.urls), ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) #I also tried STATIC_URL = '/static/' STATIC_ROOT = '/home/user/public_html/static' This is the screenshot of Latest Cpanel. How to activate virtualenv and Execute Command. -
retrieving Django object returns AttributeError: module 'types' has no attribute 'StringTypes'
I'm attempting to migrate my apps from py2 to py3, and I'm running into this error when running migration scripts. After some digging, I get the same error when doing MyModel.objects.get(id=<some_id>) Now, I know StrginType is obsolete in python3 and I removed all basestring and replace with string in my scripts (not sure if related), but I'm not sure where this error is being triggered. I'm running Django 1.11 so it should be compatible. It seems to be it's something about Django but I can't figure out what. I searched on django doc and got nothing. Anyone got the same error before when retrieving an object through django? -
Django, how to get query with upper() in search
how to solve this, when i search with upper text dont show nothing.bellow my view def cerca(request): qs = Kompany.objects.filter(owner=request.user) name = request.GET.get('name') name = name.upper() # does work piva = request.GET.get('piva') if is_valid_queryparam(name): qs = qs.filter(name=name) if is_valid_queryparam(piva): qs = qs.filter(piva=piva) context = { 'kompany': qs, } return render(request, "inventary/kompany_list.html", context) -
Django cant be reached via parameterized url
Hello StackOverflow community, I'm currently learning how to use the library Django combined with Python. However, I've ran into some issues which are somehow strange. My situation is the following. I have a project called "animals" which is the base of the Django application. My app is called "polls". Then I've defined the following views. polls/views.py from django.shortcuts import render from django.http import HttpResponse def animals(request, animal_id): return HttpResponse("%s" % animal_id) def index(request): return HttpResponse('Hello world') So far, so good. Unfortunatly I can't say the same about the urlpatterns. polls/urls.py from django.urls import path from . import views urlpatterns = [ path('',views.index,name='index'), # Redirects to localhost:8000/polls/<animal_id> path('<int:animal_id>/',views.animals,name='animals') ] Whenever I want to navigate to the url "localhost:8000/polls/10/" Django reminds me of the fact, that the url is not accepted by the application and a 404 Error is thrown inside my browser. Am I missing something here? -
how can i use django form dropdown to my template?
i've created a form that has fields with dropdown, one for Countries and another one for Nationality but i do not know how to pass it to my html template. How can I solve this problem? i wrote my models and passed it to my form.py and use it into my template Models.py class User(models.Model): first_name = models.CharField(max_length=100) second_name = models.CharField(max_length=100) E_mail = models.EmailField(max_length=254) COUNTRY_CHOICES = [('saudi arabia +966','SAUDI ARABIA +966'), ('oman +968','OMAN +968'), ('kuwait +965','KWUAIT +965'), ('Qatar +948','QATAR +948')] country = models.CharField(max_length=250, choices=COUNTRY_CHOICES, null=True) phone = models.IntegerField(null=True) phone_code = models.IntegerField(null=True) birthday = models.DateField(null=True, blank=True) NATIONALITY_CHOICES = [('خليجي','خليجي'), ('ليس خليجي','ليس خليجي')] nationality = models.CharField(max_length=250, choices=NATIONALITY_CHOICES, null=True) def __str__(self): return self.first_name forms.py from django import forms from .models import User class UserForm(forms.ModelForm): class Meta: model = User fields = ('first_name', 'second_name', 'E_mail', 'country', 'phone', 'phone_code','birthday', 'nationality',) form_page.html <form action="{% url 'LandingPage:form_page' %}" method="POST" class="ui inverted form container"> {% csrf_token %} <div class="field"> <label>البريد الألكتروني</label> <input type="text" name="last-name" placeholder="joe@schmoe.com" {{form.E_mail}}> </div> <div class="ui field"> <label>أختر الدولة</label> <select name="gender" class="ui dropdown" id="select" {{form.country}}> <option value="">أختر الدولة</option> <option value="Saudi">Saudi Arabia +966</option> <option value="Qatar">Qatar +974</option> <option value="Oman">Oman +968</option> <option value="Kuwait">Kuwait +965</option> <option value="Bahrain">Bahrain +973</option> </select> </div> <!-- Mobile Number --> <div class="ui field"> <label>رقم الهاتف</label> … -
Django tests failing to run because they can't create table due to malformed foreign key
When attempting to run my tests, I get the error in the title. It does not tell me anything remotely useful about which table has failed to be created because the raw output of the error is: django.db.utils.OperationalError: (1005, 'Can\'t create table `test_pogo`.`#sql-269_231` (errno: 150 "Foreign key constraint is incorrectly formed")') #sql-269_231 gives me absolutely no information as to where I should go and check in my models to find the error, as it is not the name of any of my models or database tables. When running the project (not the testing modules) locally with my prod copy, everything seems to work as expected. How do I find and fix the broken model? -
How to pass external server IP to SSO service through Gunicorn and Nginx?
I'm setting up SSO using: Django (with django_auth_adfs), Gunicorn, NGINX, and Active Directory federation. I have successfully setup the Federation on active directory, however my server will only pass http://localhost or http://127.0.0.1 to AD for the Redirect URI. When I add these to the federation and test from my local machine this works, expected. But I can't get my server, CentOS7, to pass anything but localhost or 127.0.0.1. I'm not sure how to change, or what to change, on the server side to alter the outbound IP address from the internal Gunicorn to the external IP on the box itself. I have tried playing with the reverse proxy settings in NGINX, this didn't change what AD was receiving. I have tried changing the return 301 setting for the enabled site and this results in an infinite redirect. Currently using proxy pass for inbound through NGINX to Gunicorn to point to the socket. Expected results when a user navigates to the web page is that they are redirected to sign in on AD, this currently happens. After this AD should send them back to the web page with an authentication token, this currently happens but it fails because AD tries to … -
Is it possible to use django countries in manytomany field
Hello I have a quiz that maybe will help me reduce the number of model instances I will have for my code, I am working with django countries and I was asking if I can save more than one country in a model when I use the country field, again django countries serializer am working with does not return django full details about a country class CountrySerializer(serializers.Serializer): country = CountryField() my models has country being country = CountryField() any idea on how i can make this country model hold more than one counrty -
Pass javascript variable to views.py
I have the following script in a template.html function updateArea(e) { var data = draw.getAll(); var answer = document.getElementById('calculated-area'); if (data.features.length > 0) { var area = turf.area(data); // restrict to area to 2 decimal points var rounded_area = Math.round(area*100)/100; answer.innerHTML = '<p><strong>' + rounded_area + '</strong></p><p>square meters</p>'; var convertedData = 'text/json;charset=utf-8,' + encodeURIComponent(JSON.stringify(data)); document.getElementById('export').setAttribute('href', 'data:' + convertedData); document.getElementById('export').setAttribute('download','data.geojson'); } else { answer.innerHTML = ''; if (e.type !== 'draw.delete') alert("Use the draw tools to draw a polygon!"); } } I want to take the area variable and convertedData variable and pass them to this view @login_required def fertisatmap(request): mapbox_access_token = if request.method == "POST": o_form = FertidbForm(request.POST, request.FILES) if o_form.is_valid(): fertidb = o_form.save(commit=False) fertidb.user = request.user # o_form.user = request.user.username() # fertidb.data = Fertidb.objects.create(convertedData) fertidb.save() messages.success(request, f'Vos informations ont été envoyées') return redirect('fertisat-map') else: o_form = FertidbForm() context = {'title': title, 'o_form': o_form} return render(request, 'fertisat/fertisatmap.html ', context, {'mapbox_access_token': mapbox_access_token}) how do i use request.post.get() to take the value of the area and convertedData in the view.py ? -
Serializer with custom response
I have the following example of serializer: class CallSerializer(serializers.Serializer): call_status = serializers.BooleanField() call_type = serializers.CharField() weight = serializers.IntegerField() How can I get the response including data on the results: { "results": [ { "call_status": True, "call_type": "open", "weight": 10, }, { "call_status": "data", "call_type": "result", "weight": "weight", }, ], "data": { "total": "2", "status": "1", } } Thank you. -
Is there a way, using queryset, for get count for certain field with more 3 values using Count model?
I'm trying get count of alternative field by certain question using one queryset. I tried this: Answer.objects.filter( evaluation_instance=EvaluationInstance(code=code), alternative__in=[1,2,3,4,5],question__type_question='RA' ).values('alternative') .annotate(count=Count('alternative')) And I got this output: <QuerySet [{'alternative': 1, 'count': 2}, {'alternative': 2, 'count': 4}, {'alternative': 3, 'count': 4}, {'alternative': 4, 'count': 4}, {'alternative': 5, 'count': 18}]> but I need to know how many answers with 5 (or 4 or ..1) has one question, so I added idquestion in the queryset: Answer.objects.filter( evaluation_instance=EvaluationInstance(code=code), alternative__in=[1,2,3,4,5], question__type_question='RA' ).values('alternative', 'question__id').annotate(count=Count('alternative')) But I got this: <QuerySet [{'alternative': 1, 'question__id': 5, 'count': 1}, {'alternative': 1, 'question__id': 13, 'count': 1}, {'alternative': 2, 'question__id': 4, 'count': 1}, {'alternative': 2, 'question__id': 6, 'count': 1}, {'alternative': 2, 'question__id': 12, 'count': 1}, {'alternative': 2, 'question__id': 14, 'count': 1}, {'alternative': 3, 'question__id': 3, 'count': 1}, {'alternative': 3, 'question__id': 7, 'count': 1}, {'alternative': 3, 'question__id': 11, 'count': 1}, {'alternative': 3, 'question__id': 15, 'count': 1}, {'alternative': 4, 'question__id': 2, 'count': 1}, {'alternative': 4, 'question__id': 8, 'count': 1}, {'alternative': 4, 'question__id': 10, 'count': 1}, {'alternative': 4, 'question__id': 16, 'count': 1}, {'alternative': 5, 'question__id': 1, 'count': 2}, {'alternative': 5, 'question__id': 2, 'count': 1}, {'alternative': 5, 'question__id': 3, 'count': 1}, {'alternative': 5, 'question__id': 4, 'count': 1}, {'alternative': 5, 'question__id': 5, 'count': 1}, {'alternative': 5, 'question__id': 6, … -
django.db.utils.ProgrammingError: (1064, "You have an error in your SQL syntax;"
I've been trying to use Django's built in test module with no luck I've tried changing my database, running it locally, etc and keep getting hit with the same error: django.db.utils.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'error' at line 1") test.py module below from rest_framework.test import APITestCase from universal.models import * from django.urls import reverse # Create your tests here. class UPCImageSearchTestCase(APITestCase): def setup(self): self.url = reverse('UPCImageSearch') testUpc = Item.object.create(item_upc = '001100110011') print(self.url) def test_fetch_success(self): self.data = { 'upc':'' } response = self.client.get(self.url,self.data) self.assertEqual(200,response_status_code) def test_fetch_failed(self): self.data = { 'upc':'' } response = self.client.get(self.url,self.data) self.assertEqual(500,response_status_code) -
Update context processor on Ajax .done()
I've an ecommerce page, where user can add items to their shopping cart. And when a user adds an item, the counter should reflect this new added item. For now, I have a context processor variable called {{cart_items_counter}} that gets update everytime the page reloads. But the new requirement is to not refresh the hole page but only the navbar item that contains the {{cart_items_counter}}: <li class="nav-item active"> <a class="nav-link" href="{% url 'carrito_de_compras:cart_detail' %}"><i class="fas fa-shopping-cart" style="color:white !important;"></i> ( {{ cart_items_counter }})</a> </li> I think I can achieve this using AJAX, and calling not the context_processor but a counter view to update the counter. And my guess is that I need to call this new view in the done method of the AJAX post call. How do I go about updating that navbar item content on AJAX done method? So only this part gets updated. Original cart_items_counter - context processor: def cart_items_counter(request): cart_id = request.COOKIES.get("cart_id") cart_items_count = CartItem.objects.filter(cart_id=cart_id, step_two_complete=True).count() sample_items_count = SampleItem.objects.filter(cart_id=cart_id, step_two_complete=True).count() pack_items_count = PackItem.objects.filter(cart_id=cart_id, step_two_complete=True).count() unitary_product_items_count = UnitaryProductItem.objects.filter(cart_id=cart_id, step_two_complete=True).count() total_items = cart_items_count + sample_items_count + pack_items_count + unitary_product_items_count return {'cart_items_counter': total_items} New cart_items_counter view: def update_cart_items_counter(request): cart_id = request.COOKIES.get("cart_id") cart_items_count = CartItem.objects.filter(cart_id=cart_id, step_two_complete=True).count() sample_items_count = SampleItem.objects.filter(cart_id=cart_id, step_two_complete=True).count() pack_items_count … -
Django CSV upload UploadForm to database Clean
i would like to store the data from my uploaded CSV file, called data_file I cant loop over the rows by column name in my csv file. I get Encoding errors(UTF, ASCII), also when i use IO String. I am new to django so i dont know what i do wrong. I tried to do this in my view with: def upload(request): form = UploadForm(request.POST, request.FILES) if form.is_valid(): f = io.TextIOWrapper(form.cleaned_data['data_file'].file, enconding='utf-8') reader = csv.DictReader(f) for row in reader: print(row['customer']) the error i get is: utf-8' codec can't decode bytes in position 10-11: invalid continuation byte -
How to union basic queryset with a queryset with grouped data?
I want to union two django querysets where the first queryset is just basic queryset and the seconds one is the queryset with grouped data. Obviously the second queryset will have less fields and some extra fields. For example I have ReceivedNotification model and this model have 4 main fields. class ReceivedNotification(models.Model): receiver = FK(User) initiator = FK(User) event = Char(choices) created = DateTime() So my goal is to get a queryset of all received notifications for user and some of notifications should be grouped with other of the same event type. The first queryset will be: q1=ReceivedNotification.objects .filter(receiver=request.user, event__in=[list of some event types]) The second one will be: q2=ReceivedNotification.objects \ .filter(receiver=request.user, event__in=[list of different event types])\ .values('receiver', 'event')\ .annotate(created=Max(F('created')))\ .annotate(grouped_users=ArrayAgg(F('initiator'))) These querysets are pretty similar except that q1 doesn't have grouped_users column. So i added it: q1=q1.annotate(grouped_users=Values('', CharField()) At this point I am trying to union q1 with q2 but I got an error: django.db.utils.ProgrammingError: each UNION query must have the same number of columns Can it be a problem that q1 is a queryset with objects of ReceivedNotification model and q2 is like queryset with dict data? -
Unsuccessful to run Docker-Compose
$ docker version Client: 18.03.0-ce API version: go1.9.4 Git comFri Mar 23 08:31:36 2018 OS/Arch: falsews/amd64 Orchestrator: swarm Server: Docker Engine - Community Engine: 18.09.9 API version: go1.11.13imum version 1.12) Git commit: Wed Sep 4 16:55:50 2019 OS/Arch: false/amd64 Experimental: I am trying to build a Django project in Docker which is installed in my Windows 7 64bit machine. It failed. Please help. enter image description here -
How do I filter the created objects of a model by user, to apply an update, with two forms?
I have 2 forms (models.forms) which I am calling in my function, where I try to instantiate 2 related models for 1 foreign key (user). Through 2 forms, to which, I want to apply an update, but I want to call the object by user. what am i wrong please? views.py def update_permisos(request, pk, pk1): p = get_object_or_404(Permiso, pk=pk) form = Permiso_update(request.POST, instance=p) u = get_object_or_404(Users, pk1=pk) form2 = Users_up(request.POST, instance=u) if request.method == 'POST' and request.is_ajax(): if form.is_valid(): permiso = form.save(commit=False) permiso.usuario.d_pendientes = request.POST['d_pendientes']#valores, que van al campo permiso.usuario.h_pendientes = request.POST['h_pendientes']#valores, que van al campo permiso.save() return JsonResponse({'status':'true', 'msg':'Datos procesados correctamente'})#retornando JSon en jsConsole else: return JsonResponse({'status':'false', 'msg':'Datos procesados incorrectamente'})#retornando respuesta en jsConsole else: form = Permiso_update(instance=p) form2 = Users_up(instance=u) asrg = {'form':form, 'form2':form} return render(request, 'plantillas/permisos_update.html', asrg) I tried to do with the "Update View" class, but I still do not give, with what is wrong, thanks for everything views.py class PermisoUpdateView(UpdateView): model = Permiso second_model = Users template_name = 'plantillas/permisos_update.html' form_class = Permiso_update second_form_class = Users_up def get_context_data(self, **kwargs): context =super(PermisoUpdateView, self).get_context_data(**kwargs) pk = self.kwargs.get('pk', 0) p = self.model.objects.get(id=pk) u = self.second_model.object.get(id=p.pk) if 'form' not in context: context['form'] = self.form_class() if 'form2' not in context: context['form2'] = … -
Python Django: Sending a message from server to client on database save()
I want to notify the client when my model is saved. I started by creating a django-signal on post_save. @receiver(post_save, sender=Scooter) async def scooter_post_update(sender, instance, created, **kwargs): # Notify client here Next I created the AsyncConsumer class from django-channels and provided its routing. // routing.py application = ProtocolTypeRouter({ # Empty for now (http->django views is added by default) 'websocket': AllowedHostsOriginValidator( AuthMiddlewareStack( URLRouter( [ path('scooters/', ScootersUpdateConsumer) ] ) ) ) }) // consumers.py class ScootersUpdateConsumer(AsyncConsumer): async def websocket_connect(self, event): print("Connected!", event) await self.send({ "type": "websocket.accept" }) async def send_message(self): await self.send({ "type": "websocket.send", 'text': 'Oy, mate!' }) async def websocket_receive(self, event): print("Receive!", event) async def websocket_disconnect(self, event): print("Disconnected!", event) Now my question is how can I call send_message() from the scooter_post_update() method.