Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why am i getting the TypeError:context must be a dict rather than Context. Django
Trying to setup a webpage to list the tags for startups (following along in Django unleashed). The book uses Django 1.8, and Im using 3.0. There are spots where ive seen deprecated functions in the book and was able to find what the updated replacement was, but i cant figure out why django is giving me this error when loading the homepage. Still kinda new at Python and Django. I do have tags created, when executing Tag.objects.all() and one startup has been saved to the database which has its related tag. Views.py from django.shortcuts import render from django.http.response import HttpResponse from .models import Tag from django.template import Template, Context, loader def homepage(request): tag_list = Tag.objects.all() template = loader.get_template('organizer/tag_list.html') context = Context({'tag_list':tag_list}) output = template.render(context) return HttpResponse(output) Tag_list.html {% extends parent_template|default:"organizer/base_organizer.html" %} #An alternative reference to "base.html" {% block title %} {{ block.super }} - Tag List {% endblock %} {% block content%} <h2>Tag List</h2> <ul> {% for tag in tag_list %} <li> <a href=""> {{ tag.name|title }}</a> </li> {% empty %} <p><em>There are currently no Tags available.</em></p> {% endfor %} </ul> {% endblock %} TypeError at / context must be a dict rather than Context. Request Method: GET Request URL: … -
django smart selects on Django version 3.0.1 - error ImportError: cannot import name 'six' from 'django.utils'
Installed django-smart-selects (pip install django-smart-selects) and is not working on django version 3.0.1 I configured using the official installation guide. enter code here $ python manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib/python3.7/threading.py", line 917, in _bootstrap_inner self.run() File "/usr/lib/python3.7/threading.py", line 865, in run self._target(*self._args, **self._kwargs) File "/home/mxcloud3/Desktop/django/venv/lib/python3.7/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/home/mxcloud3/Desktop/django/venv/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/home/mxcloud3/Desktop/django/venv/lib/python3.7/site-packages/django/utils/autoreload.py", line 76, in raise_last_exception raise _exception[1] File "/home/mxcloud3/Desktop/django/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "/home/mxcloud3/Desktop/django/venv/lib/python3.7/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/home/mxcloud3/Desktop/django/venv/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/mxcloud3/Desktop/django/venv/lib/python3.7/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/home/mxcloud3/Desktop/django/venv/lib/python3.7/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/home/mxcloud3/Desktop/django/venv/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/mxcloud3/Desktop/django/polls/models.py", line 2, in <module> from smart_selects.db_fields import GroupedForeignKey File "/home/mxcloud3/Desktop/django/venv/lib/python3.7/site-packages/smart_selects/db_fields.py", line 6, in <module> from django.utils import six ImportError: cannot import name 'six' from 'django.utils' (/home/mxcloud3/Desktop/django/venv/lib/python3.7/site-packages/django/utils/__init__.py) Snippets of … -
In Django/Python, how can I check if a user is at a location (I.e. a store) in order to determine if they are allowed to update the app?
My Django app lets users update wait times and I would like only users at a physical store to be able to update my app. https://www.w3schools.com/html/html5_geolocation.asp I know there are libraries and tools to get lat/long but I guess my needs require more of a radius. -
Django ModelForms to generate unique ID/names for JQuery
Is there a way to get ModelForms to generate forms that share similarly-named attributes in their models, but with unique IDs for JQuery select purposes? Or, is there a way for JQuery to select an input based on the form name/ID? See example below: I am using ModelForms in Django to automatically create forms from my models. The forms allow a user to select food that they want to order from a website. For example, here are the models for Pasta and Salad. class Pasta(models.Model): menu = models.ForeignKey(Menu, on_delete=models.CASCADE, related_name="pasta") style = models.ForeignKey(PastaStyle, on_delete=models.CASCADE) price = models.DecimalField(max_digits=5, default=0.00, decimal_places=2) def __str__(self): return f"{self.menu} | {self.style} | {self.price}" class Salad(models.Model): menu = models.ForeignKey(Menu, on_delete=models.CASCADE, related_name="salad") style = models.ForeignKey(SaladStyle, on_delete=models.CASCADE) price = models.DecimalField(max_digits=5, default=0.00, decimal_places=2) def __str__(self): return f"{self.menu} | {self.style} | {self.price}" Here is the forms.py: class PastaForm(ModelForm): class Meta: model = Pasta exclude = ['menu', 'price'] class SaladForm(ModelForm): class Meta: model = Salad exclude = ['menu', 'price'] When the forms render, I get a form with id="Pasta" and a form with id="Salad". Both forms have a select with name="style" and id="id_style". <h1>Pasta</h1> <form action="/cart/" method="post" id="Pasta"> <input type="hidden" name="csrfmiddlewaretoken" value="Jvz241ldZest9pLlGJMOBGMmSVXJmqNWzU2TpzTUOL5ynycQg3qn32Krfi4hsnrm"> <input type="hidden" value="Pasta" name="menu_item" /> <p><label for="id_style">Style:</label> <select name="style" required … -
Adding attribute to all query objects using annotate?
Is there a way I could add an attribute to all query objects using annotate? I basically just need to get a value from an m2m relationship of the object and save it as an attribute of the object. Something like this: query.annotate(value_to_be_added=("value_from_m2m")) Basically I have two different queries of the same model, one query A needs to have a "value" changed or added for all of its objects (and that value comes from the m2m relationship). Query B doesn't need to have those values changed. How would I do this? -
docker entrypoint behaviour with django
I'm trying to make my first django container with uwsgi. It works as follows: FROM python:3.5 RUN apt-get update && \ apt-get install -y && \ pip3 install uwsgi COPY ./projects.thux.it/requirements.txt /opt/app/requirements.txt RUN pip3 install -r /opt/app/requirements.txt COPY ./projects.thux.it /opt/app COPY ./uwsgi.ini /opt/app COPY ./entrypoint /usr/local/bin/entrypoint ENV PYTHONPATH=/opt/app:/opt/app/apps WORKDIR /opt/app ENTRYPOINT ["entrypoint"] EXPOSE 8000 #CMD ["--ini", "/opt/app/uwsgi.ini"] entrypoint here is a script that detects whether to call uwsgi (in case there are no args) or python manage in all other cases. I'd like to use this container both as an executable (dj migrate, dj shell, ... - dj here is python manage.py the handler for django interaction) and as a long-term container (uwsgi --ini uwsgi.ini). I use docker-compose as follows: web: image: thux-projects:3.5 build: . ports: - "8001:8000" volumes: - ./projects.thux.it/web/settings:/opt/app/web/settings - ./manage.py:/opt/app/manage.py - ./uwsgi.ini:/opt/app/uwsgi.ini - ./logs:/var/log/django And I manage in fact to serve the project correctly but to interact with django to "check" I need to issue: docker-compose exec web entrypoint check while reading the docs I would have imagined I just needed the arguments (without entrypoint) Command line arguments to docker run will be appended after all elements in an exec form ENTRYPOINT, and will override all elements … -
Django Template Does Not Exis at /
I'm fallowing a tutorial and can't open 127.0.0.1:8000/ without error Template Does Not Exis at/ I put 'DIRS': ['templates'], like the tutorial but, nothing the file dose exist. enter image description here enter image description hereenter image description here -
my user authentification is not working only shows Logout link, else statement doesnt work
I cant get this to work. I am trying to authenticate users logged in but it only shows the log out link when logged in and when logged out. I am thinking theres something wrong with the else statement, I am doing this on django: <nav class="navbar navbar-expand-md navbar-dark bg-steel fixed-top"> <div class="container"> <a class="navbar-brand mr-4" href="{% url 'blog-about' %}">Django Blog</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarToggle" aria-controls="navbarToggle" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarToggle"> <div class="navbar-nav mr-auto"> <a class="nav-item nav-link" href="{% url 'blog-home' %}">Home</a> <a class="nav-item nav-link" href="{% url 'blog-about' %}">About</a> </div> <!-- Navbar Right Side --> <div class="navbar-nav"> {% if user.is_authenticated %} <a class="nav-item nav-link" href="{% url 'logout' %}">Logout</a> {% else %} <a class="nav-item nav-link" href="{% url 'login' %}">Login</a> <a class="nav-item nav-link" href="{% url 'register' %}">Register</a> {% endif %} </div> </div> </div> </nav> ``` -
How do i add other fields on Abstract User
This is my model. When i make migrations it is not showing up on my admin page. class User(AbstractUser): # TODO User will be associated with one or more chama accounts id_number = models.IntegerField(default=0) phone_number = models.IntegerField(default=0) active_chama = models.ManyToManyField("Chama") -
Passing multiple values per key into template via ajax
I'm wanting to pass information relating to orders into my template via an ajax call. The problem is that that I've got more than two values that I want to pass in. Key: Email address Values that pertain to each key that I want to pass in: Invoice Date Name Phone number I'm wondering what the best way to do this is. Does the dictionary value need to be a list? eg. order_dict[order.email] = ['order.invoice_date', 'order.name', 'order.phone'] If the dictionary value does need to be a list, how would I iterate over it in my template? Thanks for your help! -
Openshift online - no longer running collectstatic
I've got 2 Python 3.6 pods currently running. They both used to run collectstatic upon redeployment, but then one wasn't working properly, so I deleted it and made a new 3.6 pod. Everything is working perfectly with it, except it no longer is running collectstatic on redeployment (so I'm doing it manually). Any thoughts on how I can get it running again? I checked the documentation, and for the 3.11 version of openshift still looks like it has a variable to disable collectstatic (which i haven't done), but the 4.* versions don't seem to have it. Don't know if that has anything to do with it. -
Parsing Django CSRF token from response headers
First, I know there are many questions regarding CSRF tokens / Django, but I haven't found any that are useful for the scenario that I am in. I am attempting to use Django's built in password reset endpoints with a React frontend. My goal is to use the backend functionality (generating tokens, email responses, etc) while displaying the relevant forms through React instead of using Django templates. The front end and back end are hosted on two unique servers. In my front end code, I make a call to the password_reset endpoint when my React component mounts to fetch the CSRF token. componentDidMount() { let url = "http://(raw ip address)/accounts/password_reset/" fetch(url, { credentials: 'include', }) } The token is received in the Response headers as Set-Cookie: csrftoken=b...e; expires=Sun, 10 Jan 2021 21:50:20 GMT; Max-Age=31449600; Path=/; SameSite=Lax Here are where my issues begin - I am unable to inspect the token in my storage tab and the token value is not present in document.cookie. Ideally, I would like to use something like the getCookie method that is demonstrated in the Django docs function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for … -
PostgreSQL Full Text Search: Documents composed of multiple rows
I'm using PostgreSQL's Full Text Search in Django. My data is stored in a tree structure, like so: - note 100 #This is a tree - note 341 - note 422 - note 101 #This is another tree - note 218 - note 106 In the database, each note is just an individual row with a link to its parent: id | note_body | parent_id ----------------------------- 341 | "foo" | 100 422 | "bar" | 341 ... This makes it possible to retrieve a single tree (i.e. several individual notes) at once. My question is: How can I use full text where each document is a whole tree, rather than a single note? In this example, searching for "foo" or "bar" should return note 100, which is the root of the tree that contains that word. I would like to do this using Django's full text search API. -
password reset doesnt update password
I am trying to restore password from given link, but at the moment when I try to update the password it doesn't update in the database, however I check the database , and it keeps the same password and before , how can I fix this issue? I am using sqlite as database VIEWS class RestorePasswordView(View): def get(self, request,token): if verify_password_token(token): token = token else: token = None return render(request, "account/reset-password.html", {'token': token, 'form': RestorePasswordForm}) def post(self, request,token): form = RestorePasswordForm(request.POST) if form.is_valid(): user_password_obj = verify_password_token(token) if user_password_obj: this_user = User.objects.get(id=user_password_obj.email_id) if not this_user: return False this_user.save() user_password_obj.token = None user_password_obj.save() return JsonResponse({'message': user_password_obj.token}) return JsonResponse({"message":form.errors}) models.py class PasswordReset(models.Model): email = models.ForeignKey(User, on_delete=models.CASCADE) token = models.CharField(max_length=100, null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True, blank=True) updated_at = models.DateTimeField(auto_now=True, blank=True) ajax $('#process-reset').submit(function () { TOKEN = document.getElementsByName("token")[0].value; password1 = document.getElementById("exampleInputPassword1").value; password2 = document.getElementById("exampleInputPassword2").value; $.ajax({ type:"POST", url:'/account/account-recovery/process-reset/'+TOKEN, data:{ 'csrfmiddlewaretoken': CSRF_TOKEN, 'password1': password1, 'password2': password2, }, success : function(data){ console.log(data) } }); }); html <form id="process-reset" class='login-form' method="POST" onsubmit="return false;"> {% csrf_token %} <div class="form-group m-form__group"> <input class="form-control m-input" placeholder="New Password" type="password" id="exampleInputPassword1" autocomplete="off"> </div> <div class="form-group m-form__group"> <input class="form-control m-input" placeholder="Confirm New Password" type="password" id="exampleInputPassword2" autocomplete="off"> </div> <div class="m-login__form-action"> <input type="hidden" name="token" value="{{ token }}"> … -
User Azure JWT token for login in Django Rest Framework
My application authenticates users at front end using this ADAL.js Angular Wrapper, and so I receive a JWT token that contains data such as these: { "typ": "JWT", "alg": "RS256", "x5t": "...", "kid": "..."}. { "aud": "...", "iss": "...", "iat": 1578864904, "nbf": 1578864904, "exp": 1578868804, "aio": "...", "amr": ["wia"], "email": "john.doe@my.org.br", "family_name": "Doe", "given_name": "John", "ipaddr": "XXX.XXX.XXX.XXX", "name": "John Doe", "nonce": "...", "oid": "...", "onprem_sid": "...", "sub": "...", "tid": "...", "unique_name": "john.doe@MY.ORG.BR", "upn": "john.doe@MY.ORG.BR", "uti": "...", "ver": "1.0"}. [Signature] It also obtains an authorization token that I could use to recover further info from that user (such as groups and permissions) from MS-Graph. Now I'd like to send that to my Django back-end and get these done: Start an authenticated session for that user; Recover data from MS Graph in order to determine which REST API routes should be available for that user (depending on their profile and level in the organization). Is that possible? And, if it is, which libraries should I use to accomplish that? Or I would have to write the middleware from scratch? -
What is needed when using python requests to upload an image to a Django CreateView?
I have a django site for cataloguing images. I'm using a standard CreateView for the creation page. I'm trying to automate image upload by using requests to POST to the create url. I can upload images from my browser, so I'm assuming the problem is with my script. I know I'm missing something, because I'm not managing to upload through Postman either. When I submit the request I get a status code 200 and the creation page reloads (on success it should redirect to the object page). I'm using a signed in requests.Session, I'm getting the form's csrf token beforehand. Here's the relevant part of my code: def upload_single_artwork(session, create_url, artwork, image_file): """Upload a single artwork Parameters ---------- session: requests.Session signed in session create_url: string get/post url for artwork creation artwork: ArtworkData artwork metadata object image_file: file open file object for image Returns ------- (session, response) - Session object and Response object or None """ form_received_from_GET = session.get(artwork_create_url).text csrf_middleware_token = find_csrf_token_in_html(form_received_from_GET) request_data = { 'title': artwork.Title, 'year': str(artwork.Year), 'csrfmiddlewaretoken': csrf_middleware_token, } file_data = construct_single_image_upload_data( artwork['Image file name'], image_file) headers = create_headers(create_url, create_url) try: response = session.post(artwork_create_url, data=request_data, headers=headers, files=file_data) response.raise_for_status() except Exception as e: print(e) try: return (session, response) except … -
This site can't provide a secure connection ERR_SLL_PROTOCOL ERROR
I have a google appengine project running in localhost. Everything works fine until i go to the 'login' page. When i go there i get the following error: This site can’t provide a secure connection 127.0.0.1 sent an invalid response. Try running Windows Network Diagnostics. ERR_SSL_PROTOCOL_ERROR the appengine command i use to run the project is dev_appserver.py" --host 127.0.0.1 . This is run pycharm. This only occurs in the 'login' endpoint and no other endpoint. The console error i get is: default: "GET /signin HTTP/1.1" 301 - -
Python, get thread from id
I'm spawning threads with a Django model instance and I'm saving the thread's id in a field. I'd like to use a property to show in the admin interface if the thread is still running or not. Something like this: class SomeModel(models.Model): thread_id = models.CharField(max_length=255) def _somefunction(self): print("Hello World") def spawn_thread(self): t = threading.Thread(target=self._somefuction) t.start() self.thread_id = t.ident self.save() @property def is_alive(self): if threading.hypotetic_get_thread_by_id(self.thread_id): return True return False Does something like threading.hypotetic_get_thread_by_id(self.thread_id) exists? I can't figure out how to recover the thread using its id. I'm missing something. Actually, I'm doing a very stupid thing: touching a file (named with thread's id) when thread starts and deleting it when thread stops while the property checks file's extistence to detect if thread is alive, but I don't think this is a good solution. Thank you for your time. -
how to set more than one STATIC_URL in django?
Im trying using Django together with an already programmed Front-End. In the Front-End the static files are called with GET /static/images/example.png and also GET /someName/static/images/example1.png How can I serve the static files using Django withouth modifyng my Front-end? Is it possible to set more than one STATIC_URL in settings.py? -
Pop up first login (or till actively rejected) django
I wonder how I'd build a pop up window in django, that will display after every login until: The user actively click "Don't show again" The user completes all input fields in the popup The popup is a profile completion, so they don't have to go through massive amounts of fields before completing the first signup step. I use djangos build in login, newest version of both python and django. -
unable to solve Improperly Configuation error in django
I am developing a crud application using django,using Class based views, Create, retrieve, details functions are working properly but update function don't here is my code snippets kindly dont mark my question negative, i'm a beginner. ERROR views.py class Update(UpdateView): fields = ('age', 'email') models = models.CreateUser urls.py app_name='main' urlpatterns = [ url(r'^create/$', views.Create.as_view(), name='create'), url(r'^(?P<pk>\d+)/$', views.Details.as_view(), name='detail'), url(r'^update/(?P<pk>\d+)/$', views.Update.as_view(), name='update'), url(r'', views.UsersList.as_view(), name='allUsers'), ] models.py class CreateUser(models.Model): name = models.CharField(max_length=256) age = models.IntegerField() email = models.CharField(max_length=256) gender = models.CharField(max_length=50) def __str__(self): return self.name def get_absolute_url(self): return reverse('main:create', kwargs={'pk': self.pk}) From details page i'm calling that view on a button <!DOCTYPE html> {% extends 'mainApp/base.html' %} {% block body_block %} <div class="jumbotron container"> <h1>Welcome to the Users detail page</h1> <h2>User Details</h2> <p>Name : {{user_details.name}}</p> <p>Age: {{user_details.age}}</p> <p>Email: {{user_details.email}}</p> <p>Gender: {{user_details.gender}}</p> <p><a class="btn btn-warning" href="{% url 'main:update' pk=user_details.pk %}">Update this</a></p> </div> {% endblock %} -
How to annotate median value to django queryset
I have 2 models Puzzle and Play. for each play I have a rating. I would like to annotate to a Puzzle queryset the median rating value for all corresponding plays. class Puzzle(models.Model): name = models.CharField(max_length=255) class Play(models.Model): puzzle = models.ForeignKey(Puzzle, on_delete=models.CASCADE,related_name='plays') rating = models.IntegerField(default=-1) puzzle_completed = models.BooleanField(default=None, blank=False, null=False) I know how to count: Puzzle.objects.annotate(nb_sucesses=Count('plays', filter = Q(plays__puzzle_completed=True), distinct = True),) and I expected getting the median in a similar way: Puzzle.objects.annotate(rating_median=Median('plays__rating', filter = Q(plays__puzzle_completed=True), distinct = True),) however, apparently due to my Django development environnment database (sqlite), I'm not able to do that. From what I infered from the following info https://mariadb.com/kb/en/median/, in my production environment(MariaDB), this approach should work (but I didn't tested it yet) My current understanding (based on different internet searches) is that I should be able to use Django Func() function to use a custom Median function (following that model ?) that would either call Median if in production, or a more complicated sql raw query if in Development (based on this one ? or on this one?). But after a few hours, I must admit I am out of my depth here. Anyone could please help me connect the dots ? -
Django Contact form mail send
I made a Modal contact form named "get in touch" (Bootstrap) in Django and its working 100% but I'm busy setting it up to send a mail towards my email address with the content of the contact form. but I am getting an error saying settings.EMAIL_HOST_USER NameError: name 'settings' is not defined I have added the mail settings in the settings.py file and set it in my views.py but I am getting this error and I don't know why? views.py class MailSender(): host = settings.EMAIL_HOST_USER def sendMail(self, formData, message, sender): return send_mail(formData, message, self.host, sender, fail_silently = False) class ContactMe(View): template = "contact.html" context = { 'form': ContactForm() } def get(self, request): print("getting form") return render(request, self.template, self.context) def post(self, request): form = ContactForm(request.POST) if form.is_valid(): data = form.cleaned_data print(data) mailSender(ContactForm, data['message'], settings.EMAIL_HOST_USER, ['myemail@email.com']) MailSender.sendMail() if emailsent == True: returnData = { 'success': True, 'message': 'Email not sent, but data received' } else: returnData = { 'success': True, 'message': 'Email not sent, but data received' } # return JsonResponse(returnData, safe=False) next = request.POST.get('next', '/') return HttpResponseRedirect(next) def post_regularDjango(self, request): form = ContactForm(request.POST) if form.is_valid(): data = form.cleaned_data print(data['from_email'], data['subject'], data['subject']) return render(request, self.template, self.context) else: print("form invalid") self.context.form = form … -
ValueError [Object] needs to have a value for field "item_ptr" before this many-to-many relationship can be used
I am new to Python & Django, currently working on food delivery application. I get the following error in admin when trying to add new Pizza object: "" needs to have a value for field "item_ptr" before this many-to-many relationship can be used. I have the following: in models.py class Item(models.Model): name = models.CharField(max_length=64) price = models.DecimalField(decimal_places=2,max_digits=10, default=0) size = models.CharField(choices=SIZES, max_length=64, default="R") def __str__(self): return f"{self.name}, {self.size}, ${self.price}" class Pizza(Item, abstractToppingConfig): type = models.ForeignKey(pizzaType, on_delete=models.CASCADE) def save(self, *args, **kwargs): if not self.id: newItem = Item(name=self.name, price=self.price, size=self.size) newItem.save() self.item_ptr = newItem super(Pizza, self).save(*args, **kwargs) def __str__(self): return f"{self.type} {self.name}, {self.size}" I've looked up a few of the answers here and understand that the error is occurring due to the parent class not being saved at the time the Pizza object is created. For that purpose, I am trying to override the model save method to store the Item object first and add the relationship, however any of this seems to be working. Creating and saving the object in Python shell works just fine, but not happening when Pizza object is saved. Django Version: 2.2.6 Full traceback: https://gist.github.com/Michelle-lele/7b1e60a7a1cf804bd74cfdaae5091c4e -
Notification system for private messaging in django-channels
So I have followed a tutorial to make a private messaging system with django-channels. I was wondering how to extend that feature to make a notification system where there is a badge in the navbar in my base template with the number of notifications. I want to make it so where when the user has not read the messages, it would show, then when they clicked on the messages it would all clear. I want to also make sure that when they are actively chatting with someone, they do not receive notifications. I was really stumped by this so I was wondering if anyone in the django community can help. Here are my files: Consumers.py: class ChatConsumer(AsyncConsumer): async def websocket_connect(self, event): print("connected", event) other_user = self.scope["url_route"]["kwargs"]["username"] me = self.scope["user"] thread_obj = await self.get_thread(me, other_user) self.thread_obj = thread_obj chat_room = f"thread_{thread_obj.id}" self.chat_room = chat_room await self.channel_layer.group_add( chat_room, self.channel_name ) await self.send({ "type": "websocket.accept" }) async def websocket_receive(self, event): print("received", event) front_text = event.get("text", None) if front_text is not None: loaded_dict_data = json.loads(front_text) msg = loaded_dict_data.get("message") username = "default" user = self.scope["user"] if user.is_authenticated: username = user.username pfp = await self.get_image(user.username) other_user = self.scope["url_route"]["kwargs"]["username"] thread_obj = await self.get_thread(user, other_user) await self.update(thread_obj) time …