Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DRF - Prevent users from referencing objects that do not belong to them
I have two models like so with a parent child relation: models.py class Bank(...): user = models.ForeignKey('User', ...) class Account(...) bank = models.ForeignKey('Bank', ...) user = models.ForeignKey('User', ...) I am using DRF and want to provide API access to these models. I want to ensure that Users can only access their own data. On the viewsets I can retrict the querysets to just the objects the user "owns" like so: views.py class BankViewSet(...): def get_queryset(self): return self.queryset.filter( user = request.user ) And I can do the same for Accounts. However, how can I stop a user from creating an Account via POST request with a Bank that they do not own? I want to ensure that users can only create Accounts that belong to a Bank that they own. How can I enforce/check that the Bank in the Account POST request contains the same user as the requestor? -
Updating parent form with a select2 field when closing another modal form django
I am trying to add this functionality to my django app. I have a select2 field as a ForeignKey data type field in my main form. Now, I also got an "add" button right next to it that when clicked, opens a modal with another form. That form creates another instance for the select2 to look for, another entry, so that's good and settled. But, I want it to, when submitting the form in the modal, instead of the main form page being refreshed and having to refill all other fields again, it automatically selects the instance it has just created on the select2 field. I am fairly new to the front-end aspect of it all so it would be great to have some guidance. -
Django - populate data in update form with Bootstrap Modal
I'm creating a simple app with 2 models. Unit & Note. In Note model, there is a field with Foreign Key (Unit). Now I'm trying to edit each note inside Unit's detail view (not Note detail view) with Bootstrap Modal. I don't know how to get note_id so that I can use it for Note's form instance. Right now, I only get empty form and if I save it, it overwrite the original data with empty data. Here is a code. I'd really appreciate your help since I've been stuck with this for quite long time. models.py class Unit(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) number = models.CharField(max_length=10) def __str__(self): return self.number class Meta: ordering = ('number',) def get_absolute_url(self): return reverse("unit-detail", args=[str(self.id)]) class Note(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) unit = models.ForeignKey(Unit, on_delete=models.CASCADE, related_name="notes") title = models.CharField(max_length=30) note = models.TextField() created_date = models.DateField() def __str__(self): return self.title views.py def unit_detail(request, pk): unit = Unit.objects.prefetch_related('notes').get(id=pk) # How do I pass instance for note_form ??? note_form = NoteModelForm(instance=???) context = { "unit":unit, "note_form":note_form, } return render(request, "units/unit_detail.html", context) # Update note class NoteUpdateView(generic.UpdateView): template_name = "units/note_update.html" form_class = NoteModelForm def get_queryset(self): queryset = Note.objects.all() return queryset def get_success_url(self): unit_id = self.object.unit.id return reverse("unit-detail", … -
hello I am a beginner Django developer I am facing issue in Payment integration with stripe
I'm creating an ecommerce web app in django everything is working fine without payment integration (stripe) Now when i integrated stripe the only thing I'm facing is that i cannot pass the total amount in cart to my charge.py function which will simply charge the card the amount in cart views.py from locale import currency from django.urls import reverse import stripe import datetime from django.shortcuts import redirect, render from django.http import JsonResponse from .models import * import json from .utils import cookieCart,cartData,guestOrder stripe.api_key = "sk_test_51LGVvZLOhjoxBBs0eMasEkak6VRuemLVz7KEHubNhiFwiGwMPO20RNLiDXJEkQwiCU7eGIuBawvSjpSKX8ImI7S600soefS68W" # Create your views here. def home(request): data=cartData(request) cartItems=data['cartItems'] products = Product.objects.all()[:3] context = {'products': products, 'cartItems': cartItems} return render(request, 'Home.html',context) def aboutUs(request): return render(request, 'aboutUs.html') def contactUs(request): return render(request, 'contactUs.html') def terms(request): return render(request, 'Terms.html') def store(request): data=cartData(request) cartItems=data['cartItems'] products = Product.objects.all() context = {'products': products, 'cartItems': cartItems} return render(request, 'store.html', context) def productDetails(request,id): data=cartData(request) cartItems=data['cartItems'] products = Product.objects.get(id=id) context = {'products': products, 'cartItems': cartItems} print(products) return render(request, 'productDetails.html', context) def cart(request): data=cartData(request) cartItems=data['cartItems'] order=data['order'] items=data['items'] context = {'items': items, 'order': order, 'cartItems': cartItems} return render(request, 'cart.html', context) def checkout(request): data=cartData(request) cartItems=data['cartItems'] order=data['order'] items=data['items'] print(order.get_cart_total) context = {'items': items, 'order': order, 'cartItems': cartItems} return render(request, 'checkout.html', context) def update_item(request): data = json.loads(request.body) productId = … -
Django generic.UpdateView NOT updating values upon successful POST
Below I am trying to update a specific form (OrganizationForm): Template is Rendering with the form fields and existing values in the fields. Upon Submission of the form the POST request is successful. ISSUE: The changes are not being saved to the DB. # Views.py class OrganizationDetails(LoginRequiredMixin, UpdateView): login_url = '/user/login/' redirect_field_name = 'redirect_to' model = Organization form_class = OrganizationForm template_name = 'organization/org_details.html' success_url = reverse_lazy("organization") def get_object(self): queryset = super().get_queryset() return queryset.get(pk=self.request.user.organization.pk) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) curr_org = self.request.user.organization heading = TermsHeading.objects.filter(organization=curr_org) content = TermsContent.objects.filter(heading__organization=curr_org) context['headings'] = heading data = dict() for item in heading: x = [] for desc in content: if desc.heading == item: x.append(desc) data[item] = x context['data'] = data return context What I have tried: I have overrided the 'POST' method in the class with the following: # def post(self, request): # print(request.POST) # form = OrganizationForm(request.POST) # if form.is_valid(): # form.save() # print("Valid and Saved") # else: # print(form.errors) # return super(OrganizationDetails, self).post(request) Terminal Output: [16/Jul/2022 02:44:15] "GET /user/myorganization/ HTTP/1.1" 200 29699 Not Found: /favicon.ico [16/Jul/2022 02:44:15] "GET /favicon.ico HTTP/1.1" 404 5037 [16/Jul/2022 02:44:25] "POST /user/myorganization/ HTTP/1.1" 302 0 [16/Jul/2022 02:44:25] "GET /user/myorganization/ HTTP/1.1" 200 29699 Not Found: /user/myorganization/Roboto-Regular.ttf [16/Jul/2022 02:44:25] "GET … -
Django Evaluate Queryset of ManyToMany relationship early to use in async function
I'm using a Django-Channels consumer for websocket async communication. I have something like this below class Command(UUIDModel): owner = models.ForeignKey(AUTH_USER_MODEL, default=None, on_delete=models.SET_DEFAULT, null=True, blank=True, related_name='commands') name = models.CharField('Name', default='New Command', max_length=128, blank=True, null=True) class Secret(UUIDModel): owner = models.ForeignKey(AUTH_USER_MODEL, default=None, on_delete=models.SET_DEFAULT, null=True, blank=True, related_name='secrets') command = models.ManyToManyField(Command, blank=True, related_name='secrets') @sync_to_async def get_command(pk): command = Command.objects.get(id=pk) return command class CommandConsumer(AsyncWebsocketConsumer): @log_exceptions async def command(self, event): log.debug(event) command = await get_command(event.get('command').get('id')) log.debug(command) log.debug(command.secrets) log.debug(command.secrets.all()) # Fails here return I get a SynchronousOnlyOperation error when running this, right when it evaluates the queryset for Secrets in the ManyToMany field. Is there a way to force the queryset to evaluate ahead of time in the synchronous get_command function, instead of in the async websocket? That way I can easily access the secrets via command.secrets. -
React-django on cpanel - MIME type ('text/html') is not a supported stylesheet
I am developing a react-django application. My application runs locally. When I install it on a server running on cpanel, it just shows a blank page. My provider checked it and made the following statements: The python application is installed correctly on cpanel The cause of the error should be found on the developer side. I made the simplest possible application: Simpletest Local mode: "Simple Test" text appears in the title and under the react logo (see attached image) enter image description here cpanel: Python application: the text "Simple Test" appears only in the title and sends the following error message enter image description here Does anyone have any idea where I can look for the error? The application can be cloned from github: enter link description here I would like to ask someone to try and install it on a server running cpanel. Does it have an application running? Many thanks from Tipti. -
Can I build a full-stack site using only django
New into web dev Wondering if you can build a full-stack site with only django no html no css only django -
Django; getattr(): attribute name must be string while saving django model
Whenever i submit this form, i get this error and the form does not submit successfully. what is possible the error and how do i go about fixing this? class Product(models.Model): category = models.ForeignKey(ProductCategory, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) image = models.ImageField(upload_to=user_directory_path, default='default-product.jpg') title = models.CharField(max_length=1000) status = models.CharField(max_length=100, choices=PRODUCT_PUBLISH_STATUS, default="in_review") content = RichTextUploadingField(null=True, blank=True) price = models.DecimalField(max_digits=1000000000, decimal_places=2) file = models.FileField(upload_to=user_directory_path, blank=True, null=True) views = models.IntegerField(default=0) slug = models.SlugField(unique_for_date=True) def __str__(self): return self.title -
Flask Error Use 'FLASK_APP=pushup:name' to specify one
I am trying to build my first flask application and I keep getting the error when I typed '''flask run''' My folder is called pushup and it is on my desktop Error: Failed to find Flask application or factory in module 'pushup'. Use 'FLASK_APP=pushup:name' to specify one. -
How to display model attributes in django on web app
I am creating a portfolio site with djnago. Now suppose i have a blog and i want to show the blog title,small summary and the link. I've created a model as below: class Blog(models.Model): blog_title=models.CharField(max_length=50) summary=models.TextField(blank=False) blogLink=models.URLField() def __str__(self): return self.blog_title def get_summary(self): return self.summary def get_link(self): return self.blogLink I can fill these values in the admin page but how can i show it in the web app so that other people can access the links. I also have a context processor to user details like first name etc. Should i have different context processors for different classes that I create. Just a beginner and trying out projects to skill myself I -
How can I make update form without modelForm?
I've made a Feedback form where people can share their views. Then I created an update form using the HTML. What will be the views for def UpdateFeedback()? I tried many ways but I couldn't perfectly. Please help me... Note: The feedBack form and UpdateFeedback will be on the same page. views.py: def feedBack(request,quick_view_id): quick_view = get_object_or_404(Products, pk=quick_view_id) if request.method == "POST" and request.user.is_authenticated: try: ProductREVIEWS.objects.create( user=request.user, product=quick_view, feedBACK=request.POST.get('feedBACK'), ) return redirect('quick_view', quick_view_id) except: return redirect('quick_view', quick_view_id) else: return redirect('quick_view', quick_view_id) def UpdateFeedback(): What will be the relevant code here? models.py: class ProductREVIEWS(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='userREVIEW',on_delete=models.CASCADE) product = models.ForeignKey(Products, related_name='productREVIEWrelatedNAME',on_delete=models.CASCADE) feedBACK = models.TextField(blank=True, null=True) urls.py: path("feedBack/<int:quick_view_id>/", views.feedBack, name="feedBack"), Update feedback html form: <form action="{% url 'feedBack' quick_view_id=quick_view.id %}" method="POST" autocomplete="off"> {% csrf_token %} <select name="UpdateRating" style="font-size: 13px;" id="UpdateRating" class="form-control"> <option value="{{feedBack.rating}}" style="font-size: 13px;">{{feedBack.rating}}</option> <option value="1" style="font-size: 13px;">1</option> <option value="2" style="font-size: 13px;">2</option> </select> <textarea id="UpdateFeedBack" rows="6" style="font-size: 13px;" class="form-control" name="UpdateFeedBACK" value="" required>{{feedBack.feedBACK}} <button type="submit" class="btn ms-auto btn-success" style="font-size: 13px;">Update</button> </form> -
Django - AttributeError at / 'function' object has no attribute 'objects'
I been getting this error. I dont know why my view and model names are different still im getting that error in django. This is my models.py from django.db import models class data(models.Model): id = models.IntegerField(default=1, unique=True, primary_key=True) name = models.CharField(max_length=50) location = models.CharField(max_length=50) date = models.DateField() class Meta: verbose_name_plural = 'datas' def __str__(self): return self.name This is my views.py from appplus.models import data def dashboard(request): last_added = data.objects.order_by('date')[:5] context_dict = { 'last_added' : last_added } return render(request, 'appplus/home.html', context_dict) -
How do you implement input( or form) dependent on a select menu(drop down list)?
I'm working on grading system and I'm currently working on the form that's deals with the user entering the students results now the form I have, has 2 drop-down list(classroom, students) that are dependent. The issue and where I'm stuck is When the user select the classroom the second drop-down menu will only show the students in that class, I have already figure that out..the issue is I want the input fields for how much subject the student is doing to appear so that the user can enter the grades for each subject specific to that student in the class Eg if I select classroom 1b and selected student Mary.. if Mary is doing 5 subjects then 5 input field should appear so that I can enter the mark for the subjects Link with a video showing what I'm talking about video showing an examplehttps://drive.google.com/file/d/11FoCZyOBVdUhTcvCqA1Ke0fEgRmMVC-G/view?usp=drivesdk **Models.py** Class Classroom(models.Models): name = models.charfield() Class marks (models.Models): classroom = models.foreignkey(Classroom) Grade = models.Floatfield() **Html form** <div class="container-fluid"> <form id="result-form" method="post"> {% csrf_token %} <!-- Modal --> <div class="modal-header"> <h5 class="modal-title" id="staticBackdropLabel"> {% block modal-title%} Add Result {% endblock%}</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> <div class="row"> <div class="col-md-12" id="msg8" style="font-size: 2rem; … -
Create Alert Message Before Saving Page
I am trying to create a alert message before saving the page in django, how i can do it .I need to create a message that after saving the page you can not edit the page . -
installing mysqlclient locking failed
I am using python3.9 in django framework, for that I have to install mysqlclient. But error is coming when I try pipenv install mysqlclient output like this as error: Courtesy Notice: Pipenv found itself running within a virtual environment, so it will automatically use that environment, instead of creating its own for any project. You can set PIPENV_IGNORE_VIRTUALENVS=1 to force pipenv to ignore that environment and create its own instead. You can set PIPENV_VERBOSITY=-1 to suppress this warning. Installing mysqlclient... Adding mysqlclient to Pipfile's [packages]... Installation Succeeded Pipfile.lock (06f36b) out of date, updating to (f95eff)... Locking [dev-packages] dependencies... Locking [packages] dependencies... Resolving dependencies... Locking Failed! CRITICAL:pipenv.patched.notpip._internal.resolution.resolvelib.factory:Could not find a version that satisfies the requirement django (from versions: none) [ResolutionFailure]: File "C:\Users\meghd\anaconda3\lib\site-packages\pipenv\resolver.py", line 743, in _main [ResolutionFailure]: resolve_packages(pre, clear, verbose, system, write, requirements_dir, packages, dev) [ResolutionFailure]: File "C:\Users\meghd\anaconda3\lib\site-packages\pipenv\resolver.py", line 704, in resolve_packages [ResolutionFailure]: results, resolver = resolve( [ResolutionFailure]: File "C:\Users\meghd\anaconda3\lib\site-packages\pipenv\resolver.py", line 685, in resolve [ResolutionFailure]: return resolve_deps( [ResolutionFailure]: File "c:\users\meghd\anaconda3\lib\site-packages\pipenv\utils.py", line 1377, in resolve_deps [ResolutionFailure]: results, hashes, markers_lookup, resolver, skipped = actually_resolve_deps( [ResolutionFailure]: File "c:\users\meghd\anaconda3\lib\site-packages\pipenv\utils.py", line 1106, in actually_resolve_deps [ResolutionFailure]: resolver.resolve() [ResolutionFailure]: File "c:\users\meghd\anaconda3\lib\site-packages\pipenv\utils.py", line 884, in resolve [ResolutionFailure]: raise ResolutionFailure(message=str(e)) [pipenv.exceptions.ResolutionFailure]: Warning: Your dependencies could not be resolved. You likely … -
Referring foreign key in a FormModel query all model instances
I'm creating a registration system for programming classes, at some point I want people to choose which batch they want to enroll in, the Batch model is haveing a foreign key to Program model model.py class Program(models.Model): id = models.AutoField(primary_key=True) name_english = models.CharField(max_length=64, null=False) name_arabic = models.CharField(max_length=64, null = False) def __str__(self): return(self.name_arabic) class Batch(models.Model): id = models.AutoField(primary_key=True) program = models.ForeignKey(Program, on_delete=models.CASCADE) number = models.SmallIntegerField() starting_at = models.DateField() def __str__(self): return (f"{self.program}") Then I'm creating a formset from the Batch model form.py class new_program_formset(ModelForm): class Meta: model=Batch fields = "__all__" new_program_formset = modelformset_factory(model=Batch, fields="__all__") Then I'm passing it through the view to the template views.py return render(request, "registration/program_registration.html", { "forms": new_program_formset(), "progress": 40, "quote": quote, }) HTML template <div class="form-outline text-center"> {% for form in forms %} <label class="form-label">{{ form.program }}</label> <div> <p>{{form.starting_at}}</p> </div> {% endfor %} </div> The problem is when I'm referring form.program it queries all instances in the program model I want to get the one program associated with the selected Batch. -
Is it possible to fill out the fields of Django's UserCreationForm in python function?
I already have a Registration form on my ecommerce site. Now i would like to use Django's inbuilt validation system. Therefore, as far as i understood, i have to use a form that is provided by Django, e.g. UserCreationForm. But since i already have a form, i thought i could transfer the user information from my own form into some Django form in the backend. I have tried the following: forms.py: from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class RegistrationForm(UserCreationForm): email = forms.EmailField(max_length=60) class Meta: model = User fields = ("username", "email", "password1", "password2", "first_name", "last_name") utils.py, containing the function, that is going to be called in views.py: # does not return anything, since form.save() handles registration def signup(request): form = RegistrationForm() # transfer the data from my_custom_view to Django's UserCreationForm form.fields["username"].value = request.POST["username"] form.fields["first_name"].value = request.POST["firstname"] form.fields["last_name"].value = request.POST["lastname"] form.fields["email"].value = request.POST["email"] form.fields["password1"].value = request.POST["password"] form.fields["password2"].value = request.POST["password_val"] if form.is_valid(): # some message form.save() function above is called within views.py as follows: home_view(request): # some code if request.method == "POST" and "signupbtn" in request.POST: signup(request) register.html: <form class="px-4 py-3" method="POST"> {% csrf_token %} <div class="container"> <input required class="form-control" type="text" name="firstname" placeholder="First Name"> <input required … -
Stripe: Python You must update your Connect branding settings with icon
Currently integrating Stripe Connect and I keep getting the same error stripe.error.InvalidRequestError: Request ********541g: You must update your Connect branding settings with icon in order to create an account link. You can set the missing fields at https://dashboard.stripe.com/settings/connect I have completed everything on Stripe's Dashboard and updated all the branding requirements but I'm now getting this error on my test data. Here is the code below account = stripe.Account.create( country="US", type="express", capabilities={ "card_payments": {"requested": True}, "transfers": {"requested": True}, }, business_type="individual", ) return stripe.AccountLink.create( account=account['id'], refresh_url='https://localhost:3000/', return_url='https://localhost:3000/', type="account_onboarding", ) Is there anything else I need to add? -
converter text to hex and than to base64 using Django-python
I'm using Django I want to convert text to hex and than base64 I tried to do like this: # create text or number and convert them to integer # txt = "ABC" txt_to_int = int(txt,16) print(txt_to_int) >> 2748 # convert them to hex txt_to_hex = hex(txt_to_int) print(txt_to_hex) >> 0xabc # convert to base64 hex_encode = txt_to_hex.encode('utf-8') hex_to_base64 = base64.b64encode(hex_encode) base64_decode = hex_to_base64.decode("utf-8") print(base64_decode) >> MHhhYmM= I am using Online Text To Hex Converter Tool I want result as: https://string-functions.com/string-hex.aspx after Converter : text to hex: (ABC) to hex (414243) https://base64.guru/converter/encode/hex after Converter : Hex to Base64 (414243) to base64 (QUJD) I want to do them by django-python any help I will appreciate -
object has no attribute 'is_active' Django
AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', 'oauth2.auth.DiscordAuthenticationBackend', ] I have two backends, and when I try to go to localhost:8000/admin, 'oauth2.auth.DiscordAuthenticationBackend' backend works, not 'django.contrib.auth.backends.ModelBackend', how to fix this? -
How to apply select_related to the objects of a m2m relationship in Django?
Lets say there is a structure like this: class Aaaaa(models.Model): b = models.ManyToManyField('b') class Bbbbb(models.Model): c = models.ForeignKey('c') class Ccccc(models.Model): x = models.CharField(max_lenght="3") Now I'm in the DetailView of Aaaaa. I do prefetch_related('b'). But how can I let django know to get all the "Ccccc" as well? Sorry, I'm sure this has been asked a lot, but for some reason I just can't find it. -
Django Admin: Populate admin fields based on table row selection
I need some help to import values of items (saved on database from previous orders) based on client search by id. This must happen after the user click a button inside admin panel. So, when button 'Importar do histórico' is clicked Fields that need to be filled one window will open with all history of items of that client (presented as a table with django_tables2) Table with results of query based on client id So, when I click one of the rows of the table that values must fill the fields inside the admin panel. Below part of my 'admin.py'. The model 'pedido_item' is an inline of model 'pedido'. class itensInline(admin.StackedInline): form = pedidoItemForm model = pedido_item formfield_overrides = { models.CharField: {'widget': TextInput(attrs={'size':'10'})}, models.Choices: {'widget': Select(attrs={'size':'20'})}, } raw_id_fields = ('cd_pedido',) radio_fields = {'cd_tipo_fixacao_encosto': admin.HORIZONTAL, 'cd_tipo_fundo_encosto': admin.HORIZONTAL, 'cd_tipo_cor_fundo_encosto': admin.HORIZONTAL,'id_montagem': admin.HORIZONTAL} fieldsets = ( ('Dados Obrigatórios', { 'fields': (('quantidade'),('modelo_ar','modelo_a'),('modelo_er','modelo_e'),'tecido','cd_tipo_fundo_encosto','cd_tipo_cor_fundo_encosto','cd_tipo_costura','cd_tipo_fixacao_encosto','fixacao_encosto') } ), ('Tipo de Montagem',{ 'fields' : ('id_montagem',) } ), ('Montada em base',{ 'classes' : ('base','pretty'), 'fields' : ('base', 'opcao_braco','braco') } ), ('Somente Estofamento',{ 'classes' : ('est','pretty'), 'fields' : ('porca_garra',) } ), ) class Media: js = ('admin/js/vendor/jquery/jquery.js','admin/js/jquery.init.js','js/admin.js','js/importar.js','js/autorizarPedido.js','js/importarPopup.js') extra = 0 def has_edit_permission(self, request): return False class processoInline(admin.StackedInline): model = pedido_historico exclude = … -
Related field not populating in the response in Django rest framework
Have two models: class Topic(Base): name = models.CharField(max_length=100, unique=True) display_name = models.CharField(max_length=100) class SubTopic(Base): name = models.CharField(max_length=100, unique=True) display_name = models.CharField(max_length=100) topic = models.ForeignKey(Topic, on_delete=models.CASCADE) and have two serializers: class SubTopicSerializer(serializers.ModelSerializer): class Meta: model = SubTopic fields = ('topic', 'name', 'display_name') class TopicSerializer(serializers.ModelSerializer): sub_topics = SubTopicSerializer(many=True, read_only=True) class Meta: model = Topic fields = ('id', 'display_name', 'sub_topics') the subtopics are not populating in the response of the Topic serializer. -
Django Channels - Get a list of all active sessions, or execute something when a session is "closed"
I'm using WebsocketConsumer, and storing data user-related on the cache, I'm tying this to both, user and session user = self.scope["user"] session = self.scope["session"] and when the WebsocketConsumer disconnected, I clean all the data related to this session and user from channels.generic.websocket import WebsocketConsumer class MyConsumer(WebsocketConsumer): def connect(self): self.store_session_data() def disconnect(self, _): self.clean_session_data() def websocket_disconnect(self, _): self.clean_session_data() I'm doing this because a user may have multiple tabs opened on the same application, and so have multiple sessions, and I don't want a tab to clean something that might be valuable for the second tab If the user disconnects as expected, everything goes right But if the browser is closed, neither the disconnect nor the websocket_disconnect are called. And the data related to the previous session remains untouched Questions A) Is there a way to execute something no matter how the WebsocketConsumer is closed? B) An alternative way would be to get all active sessions and clean anything related to a non-active session Is it feasible? I couldn't find how to do it either Any thought?