Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
REGEXP for matching or finding only Streetname and housenumber without additionals
This is a regexp specific something that I need to do in the backend to strip the address. I need the streetname + number to be cleaned to a Streetname + housenumber without any additional letters or any other characters with other numbers. For example: Teststreet 123 (correct) Teststreet 123F needs to be stripped to Teststreet 123 Teststreet 12 and 3 needs to be stripped to Teststreet 12 Teststreet 123,5 needs to be stripped to Teststreet 123 Street name long 122 (correct) Street name long 122 - A needs to be stripped to Street name long 122 And so on... I have a function that gets the address from the model and sometimes the addresses could be with some additional characters etc which a API that I have to read does not work with it, so I have split/trim it in python to only a streetname and a housenumber. Does anyone have an idea how I can do this? And anyone an idea what the correct REGEXP for this can be? -
Django I have added an href parameter to my url but it does not work
I have a field in my datatable which represent product url and I have display it in my django template as href in order to enable the user to get the product page by clicking on this link. this is my code in django template : <td><a href="/Productlinks/">{{product.Productlinks }}</a></td> But when I click the url it gives me an error page . -
Why is my sign up button in Django not working?
I have been following a Django blog tutorial where a user can register an account, however my 'sign up' button should be redirecting to the homepage and creating the user, however it does neither. I have extensively searched online for an answer, yet can't seem to resolve the issue. Any help would be much appreciated. Here is my register.html file: {%block content%} <div class="content-section" <form method ="POST" > {%csrf_token%} <!django required security> <fieldset class="form-group"> <legend class="border-bottom mb-4">Join Today</legend> {{form.as_p}} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit" value="submit">Sign Up</button> </div> </form> <div class="border-top pt-3"> <small class="text-muted"> Already Have An Account? <a class="ml-2" href="#">Sign in</a> </small> </div> </div> {%endblock content%} and here is my views.py file: from django.contrib.auth.forms import UserCreationForm from django.contrib import messages def register (request): if request.method == 'POST': form = UserCreationForm(request.POST) #creates instance of form with POST data if there's a POST request if form.is_valid(): #validation of form form.save() username=form.cleaned_data.get('username') messages.success(request, f'Account created for {username}.') return redirect ('requests-home') #redirecting to home page after account creation else: form = UserCreationForm() #creating instance of user creation form (empty) return render(request, 'users/register.html', {'form': form}) I also get this error when running the views.py file in VsCode: ** "ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, … -
I Want to get card rate in response to card category
What I am trying to do is that once I select a card category, the corresponding card rate should appear, I have three models: Giftcard, Category, and CardRate, which I link together using ForeignKey. Here are my models class Giftcard(models.Model): name = models.CharField(max_length=100, unique=True) card_image = models.ImageField(upload_to='Giftcard/', blank=False) date = models.DateTimeField(auto_now_add=True) publish = models.BooleanField(default=False) class Category(models.Model): category = models.CharField(max_length=250) card = models.ForeignKey(Giftcard, on_delete=models.CASCADE) class CardRate(models.Model): rate = models.IntegerField() card_category = models.ForeignKey(Category, on_delete=models.CASCADE) Here is my view: def giftcard(request): giftcards = Giftcard.objects.filter(publish=True) categories = Category.objects.all() context = { 'giftcards': giftcards, 'categories': categories, } return render(request, 'dashboard/giftcard.html', context) Here is my template, i thinking here were my mistake is coming from: {% for giftcard in giftcards %} <!-- Card --> <div class="col-lg-4 gift__card col-6 p-0"> <a type="button" class="btn"> <img class="img-fluid gift__card-img" src="{{ giftcard.card_image.url }}"> </a> <div class="container d-flex align-items-center justify-content-center"> <div class="gift__card-modal-container py-5"> <div class="card__container"> <div class="gift__card-overlay"></div> <div class="container-fluid bg-light gift__card-modal shadow-lg"> <div class="pop p-5"> <div class="row d-flex align-items-center justify-content-between"> <div class="col-lg-5 col-12 p-0 m-0"> <img class="img-fluid gift__card-img" style="width: 40rem;" src="{{ giftcard.card_image.url }}"> <p class="text-muted">Select the card category and the amount.</p> </div> <div class="col-lg-6 col-sm-12 card-details"> <form class="card-form"> <div class="form-group py-2"> <label for="card-category">Card category</label> <select id="category" class="form-select py-2" aria-label="Default select example"> {% … -
OrderForm not saving data to django database
i'm creating a webapp that allows a user to enter information in a form which then saves the data into django. Everything works well, I can add information to the form in the template and press submit however the data is not saved into the database (I cannot see it in my admin panel inside 'Order' table. I have the if form.is_valid() form.save() in my views.py file which should POST the data to my database but its not. Anyone know what i'm doing wrong? Order model from models.py class Order(models.Model): STATUS = ( ('Pending', 'Pending'), ('Out for delivery', 'Out for delivery'), ('Delivered', 'Delivered'), ) # on_delete = If customer is delete, we dont delete child (orders), customer just becomes null without deleting order customer = models.ForeignKey(Customer, null=True, on_delete= models.SET_NULL) product = models.ForeignKey(Product, null=True, on_delete= models.SET_NULL) date_created = models.DateTimeField(auto_now_add=True, null=True) status = models.CharField(max_length=200, null=True, choices=STATUS) forms.py OrderForm class is inherited by CreateOrder views.py from django.forms import ModelForm from .models import Order class OrderForm(ModelForm): class Meta: model = Order fields = '__all__' createOrder function from views.py: def createOrder(request): form = OrderForm() if request.method == 'POST': #print('Printing POST:',request.POST) form = OrderForm(request.POST) #form handles the process of saving to database/ if form.is_valid(): form.save return … -
writing to mariadb causes non-UTF-8-endocing
I am using mariadb with Server charset: UTF-8 Unicode (utf8mb4) and python 3.7.3 and for some reason beyond me, a CSV file read in and written to the database is saved in some weird encoding: models.py: class Product(models.Model) data = models.JSONField() store = models.ForeignKey(Store, on_delete = models.CASCADE) number = models.PositiveIntegerField() and when reading in a csv file: with open(filename, encoding = "utf-8") as f: reader = csv.reader(f) for row in reader: d = {header[i]: row[i] for i in range(1, len(row))} logging.error(f"{row[0]} - {d}") # prints "123 - süden" product = Product.objects.get(store = store, number = row[0]) product.data = d product.save() but in my database the line reads as "number": 123, "data": "s\u00fcden". So my struggles here: csv file is encoded in UTF-8 csv file is opened with UTF-8 encoding console prints the charset correctly phpmyadmin shows, "ü" saved as "\u00fc" printing the line in django shell prints "ü" correctly I already tried setting the an encoder for the JSONField: from django.core.serializers.json import DjangoJSONEncoder ... data = models.JSONField(encoder = DjangoJSONEncoder) and then ran migrations again. A simple test can be done in the admin, when searching for products süden returns zero hits. But when manually altering the value to süden in … -
Django uses untranslated strings instead of translations
I have a small Django application, which I tried to localize. In the urls.py I have urlpatterns += i18n_patterns( path('add_request/',AddRequest.as_view(),name='add_request'), path('add_offer/', AddOffer.as_view(), name='add_offer'), ) In the settings.py I have MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] and LANGUAGES= [ ('en', 'English'), ('de', 'German') ] In my models.py I used gettext (also tried gettext-lazy) for the verbose_name arguments of my fields. I extracted po files via django-admin makemessages -l en django-admin makemessages -l de Translated them and ran django-admin compilemessages Now I have the prefixes de/ and en/ for my urls, but all field names are the untranslated verbose_names from my models. How do I get Django to use the translations? -
when i am deploying on heroku i get Page not found (404)
Page not found (404) Request Method: GET Request URL: https://blogapp85.herokuapp.com/ Using the URLconf defined in blog.urls, Django tried these URL patterns, in this order: admin/ blogapp/ The empty path didn’t match any of these. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. settings.py from pathlib import Path import dj_database_url import os import django_heroku # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-@88uzl)swhs9@api7_%qj#vw=wa0!jf3+)l5-mmlch@t5%%^fl' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['0.0.0.0', 'localhost', '127.0.0.1', 'blogapp85.herokuapp.com'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blogapp', 'django_social_share', 'whitenoise.runserver_nostatic' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', ] ROOT_URLCONF = 'blog.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR/'templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'blog.wsgi.application' # Database # https://docs.djangoproject.com/en/4.0/ref/settings/#databases #DATABASES = { # 'default': { # 'ENGINE': 'django.db.backends.sqlite3', … -
POST method not working in django, where i use Formview
I have class where is use both, FormView and DetailView. when i send post request i see this log in terminal [06/Apr/2022 14:44:16] "POST /profile/question/1/ HTTP/1.1" 200 6327, but not working post, form_valid and form_invalid methods. does not call these 3 functions and therefore the form is not stored this is my code -> class QuestionDetail(FormView, DetailView): model = Question form_class = CommentForm template_name = "Profile/question_detail.html" context_object_name = "detail" def dispatch(self, request, *args, **kwargs): try: self.object = self.get_object() except: return redirect('Profile:error') self.get_object() return super(QuestionDetail, self).get(request, *args, **kwargs) def get_success_url(self): return self.request.path def get_context_data(self, *args, **kwargs): like_exist=bool(Like.objects.filter(user=self.request.user, question=self.get_object())) dislike_exist=bool(DisLike.objects.filter(user=self.request.user, question=self.get_object())) self.object=self.get_object() context = super(QuestionDetail, self).get_context_data(**kwargs) try: question = Question.objects.get(id=self.kwargs["pk"]) context['detail'] = question context['like_ex'] = like_exist context['dislike_ex'] = dislike_exist except Http404: return reverse("Profile:error") return context def post(self, request, *args, **kwargs): print("Not working post method") def form_invalid(self, form): print("Error") return super(QuestionDetail, self).form_invalid(form) def form_valid(self, form): print("It's here") form.instance.user = self.request.user form.instance.question = self.get_object() form.save() return super(QuestionDetail, self).form_valid(form) i don't understand what happened. -
ManytoManyField Django : how to call models in methods?
I need help for something, I want to call models with ManyToManyField. I want to have method to get Class A from Class B, and another in Class B to get Class A. here's my (shortened) code : class Licence(models.Model): name = models.CharField(max_length=64) picture = models.ImageField(upload_to='finder/static/finder/img/licence/',null=True, blank=True) description = models.TextField(null=True, blank=True) #returns a list of games from this license def getGamesOnThisLicence(self): #i don't know how to proceed class Game(models.Model): name = models.CharField(max_length=64) description = models.TextField() release_date = models.DateField(null=True, blank=True) licence = models.ManyToManyField(Licence, blank=True, null=True) #return name of licence to which the game belongs def getLicenceName(self): return self.licence.name -
How to load images using JavaScript in Django in a Jinja format?
Basically what I am doing is here there is a emotion detection model running in background which will detect the emotion and create an emoji in .svg format. This svg file keeps on changing as the emotion changes. Like if emotion="Happy" then an image with a happy face will be generated in a svg file format. Now I want this generated image to be displayed in by Django template but I am getting error. This is my view.py def epred(emotion): global ep ep = emotion def res(request): global sc_id,cc_id,hc_id,ht_id,a_id,fht_id,ct_id, ep sc_id = request.GET.get('skincolor') cc_id = request.GET.get('clothingcolor') hc_id = request.GET.get('haircolor') ht_id = request.GET.get('hairtype') a_id = request.GET.get('accessory') fht_id = request.GET.get('facialhairtype') ct_id = request.GET.get('clothingtype') update(fht_id, ct_id, cc_id, a_id, hc_id, ht_id, sc_id, ep) return render(request, 'result.html') def gen(camera): while True: frame = camera.get_frame() update(fht_id, ct_id, cc_id, a_id, hc_id, ht_id, sc_id, ep) yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n') def video_feed(request): return StreamingHttpResponse(gen(VideoCamera()), content_type ='multipart/x-mixed-replace; boundary=frame') This is my result.html file where I need the image to be displayed <body style="background-color:#9ADCFF"> <h1 id="mh1">LOOK AT THE CAMERA</h1> <div class="row"> <div class="column" id="cols"> <img src = "{% url 'video_feed' %}"> </div> <div class="column" id="cols"> <img id="resimg" src="{% static 'output/emoji1.svg' %}"> <div id="resbtn"> <a href="#"><button class="btn btn-primary" … -
How can I truncate serializer CharField value if it exceeds a certain length
I have a model field that I want to restrict to a certain length (max_length=200). I however want the serializer to truncate any value that exceeds that length (max_length=200). How can I achieve this model field description = models.CharField(max_length=2000) serializer field description = serializers.CharField( max_length=2000, required=False, allow_blank=True, default="" ) -
How to allow users to input in only 5 fields out of 10 in django model form
I have developed a django project to test 10+2 students online. I used django model forms.In the question paper, there will be 90 questions. In each subject 30 questions. Out of 30 , in each subject, first 20 are multiple choice. In that I don't have any problem. But in the remaining 10, students have to input integer values . But only 5 out of 10. How to restrict them not to input more than 5 in that 10 questions in each subject. Pls advice me. I am not rendering questions, only form to collect options and integers. Pls advice me -
How to get top n rows in django rest framework serializers using serializers relations
I have a serializer that is working fine for all of the data, which is getting from the Database. I want to get top n numbers of rows sorted by some value. Below is my code in views.py: @api_view(['GET']) def org_api(request, org_id): if request.method == 'GET': try: org = Organization.objects.prefetch_related('team').get(org_id=org_id) except Organization.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) serializers = OrgSerializers(org) return Response(serializers.data) And here is my serializers.py code: class OrgSerializers(serializers.ModelSerializer): team = TeamSerializer(many=True, read_only=True) class Meta: model = Organization fields = ['org_id','name', 'team'] And here is my TeamSerializers Code: class TeamSerializer(serializers.ModelSerializer): ticker = serializers.PrimaryKeyRelatedField(queryset=Team.objects.all()) class Meta: model = Team fields = ['name', 'resignation', 'org_id'] It is returning all of the team members of the same organization like below: { "org_id": "ABC", "name": "Stocks Telegraph", "team": [ { "name": "Mr. Timothy D. Cook", "title": "CEO & Director", "org_id": "ABC" }, { "name": "Mr. Luca Maestri", "title": "CFO & Sr. VP", "org_id": "ABC" }, { "name": "Mr. Jeffrey E. Williams", "title": "Chief Operating Officer", "org_id": "ABC" }, { "name": "Ms. Katherine L. Adams", "title": "Sr. VP, Gen. Counsel & Sec.", "org_id": "ABC" }, { "name": "Ms. Deirdre O'Brien", "title": "Sr. VP of People & Retail", "org_id": "ABC" }, { "name": "Mr. Chris Kondo", "title": "Sr. … -
Adding a 'show all' to django search with js/ajax if results > 5
I have a simple django search functionality using js/ajax. I want to add functionality so that when the queryset is greater than 5 a 'Show all' href will appear in the search results and it will redirect to a page with all the queryset. This is for the case when a queryset returns a large number of results, rather than have them in one big box. I thought I could just add a dictionary to my queryset, e.g. data.append({'pk': <add number to querset>, 'name': 'Show all results'}) but then I think this will mess around with the js logic with the forEach loop. I'd want each search result up to 5 to link to the detail view, but then the last one should link to a completely different view. I'm not sure what the best option is here. My search in views.py: def search_results(request): """ Handles search logic """ if request.is_ajax(): res = None quote = request.POST.get('quote') qs = Quote.objects.filter(name__icontains=quote) if len(qs) > 0 and len(quote) > 0: data = [] for pos in qs: item = { 'pk': pos.pk, 'name': pos.name, 'image': str(pos.image.url) } data.append(item) res = data else: res = 'No quotes found...' return JsonResponse({'data': res}) return JsonResponse({}) … -
How to return Google Login URL via REST api using django-allauth library?
There is a project with connected and working Google authorization using the django-allauth library. The problem is that django-allauth returns an html template with a redirect button to Google Auth by url .../account/google/login. How to return NOT a TEMPLATE, but a link to Google Auth? The provider_login_url variable is inserted only into the template and there is no access to it. -
Django import my app models AppRegistryNotReady
I will import my models in celery.py. But when I import and run the runserver command, I get the following error: raise AppRegistryNotReady("Apps aren't loaded yet.") My import code line: from app.models import model1, model2 -
Django admin form fields are all on one line
I have an admin action which is followed by a form where users can choose several dates. class AddReportDateForm(forms.Form): _selected_action = forms.CharField(widget=forms.MultipleHiddenInput) date = forms.DateField(required=False, widget=forms.SelectDateWidget(years=[timezone.now().year, timezone.now().year-1, timezone.now().year-2])) date1 = forms.DateField(required=False, widget=forms.SelectDateWidget(years=[timezone.now().year, timezone.now().year-1, timezone.now().year-2])) date2 = forms.DateField(required=False, widget=forms.SelectDateWidget(years=[timezone.now().year, timezone.now().year-1, timezone.now().year-2])) But on the admin form all these datewidgets are inline. Is there an easy way to get them all on a separate line. Without creating an admin template. Thanks in advance -
Django didn't create test database
I have a postgresql database defined in settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'blog', 'USER': 'blog', 'PASSWORD': 'blog', 'HOST': 'postgres', 'PORT': '5432', }} Also I have a dummy test that creates a few objects in db class LogicTestCase(TestCase): @classmethod def setUp(cls): User.objects.create(username='test_user') Tag.objects.create(name='test_tag') Post.objects.create(title='test_title', post_text='test post text', author=User.objects.get(username='test_user')) def test_home(self): self.view = Home() print(self.view.get_context_data()) But when I run the tests - Django does not create a test database, instead of it Django uses my main DB to create objects. What have I done wrong with configuring my project? Django version==3.2.9 I run tests in a docker container, here is my docker-compose version: '3' services: blog: build: . command: bash -c 'python manage.py runserver 0.0.0.0:8000' ports: - "8000:8000" container_name: blog volumes: - .:/usr/src/blog restart: always depends_on: - postgres redis: image: redis restart: always postgres: image: postgres volumes: - '/tmp/postgres:/var/lib/psql/data' environment: POSTGRES_DB: 'blog' POSTGRES_USER: 'blog' POSTGRES_PASSWORD: 'blog' PGDATA: 'var/lib/psql/data/postgres' celery: restart: always build: . container_name: 'blog_celery' command: bash -c 'celery -A justblog worker -l INFO -E -B' -
Error while trying to switch the identifier to email in Django User model
I want to change the unique identifier of Django's User model from Username to Email so I write this: models.py: from django.db import models from django.contrib.auth.base_user import BaseUserManager from django.contrib.auth.models import AbstractUser # Create your models here. class CustomUserManager(BaseUserManager): ''' Custom user model manager where email is the unique identifier for authentication instead of username.' ''' def create_user(self, email, password, **extra_fields): ''' Create and save a User with the given email and password. ''' if not email: raise ValueError('The Email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() return user def create_superuser(self, email, password, **extra_fields): ''' Create and save a SuperUser with the given email and password. ''' extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self.create_user(email, password, **extra_fields) class CustomUser(AbstractUser): username = None email = models.EmailField('email address', unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() def __str__(self): return self.email admin.py: from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .models import CustomUser # Register your models here. class CustomUserAdmin(UserAdmin): model = CustomUser list_display = ('email', 'is_staff', 'is_active') list_filter = ('email', 'is_staff', 'is_active') fieldsets = … -
How to migrate specific models in another database in django?
I have two databases in my Django project settings (app1_db, app2_db) and I have a model in app1 that I want to migrate to app1_db. How can I do this? I tried to use Django routers but it didn't work for me. the router goes to sync all models in an app to a specific database but I want that just a specific model goes to that database. -
How do I get the oldest item in an SQLite3 database with django [closed]
Using Django, how would I get the oldest object in my SQLite3 database and delete it if a specific condition is true? I am hoping to do this from the views.py file in my app. -
NameError: name 'model_object' is not defined
I'm trying to get all model operations in my django app with the following code but it returns an error. I get the error NameError: name 'model_object' is not defined def admin_main(request): logs = LogEntry.objects.log_action( user_id=request.user.id, content_type_id=ContentType.objects.get_for_model(model_object).pk, object_repr=unicode(obj), object_id=obj.id, message="", action_flag=ADDITION if create else DELETION) logs = logs.order_by('-action_time')[:40] return render(request,'history.html', {"logs":logs}) -
DJANGO : How to filter the last data collected for each type of object in a model?
Let's say I have this model class TreeCensus(models.Model): name = models.CharField() #Oak, elm, ... identified_at = models.DateTimeField(auto_now_add=True) I want to get a QS with the last Census of each tree. I tried naively this TreeCensus.object.order_by('name').last() But It obviously returned me the last of all the TreeCensus objects. So what is the best way (or at least a good one) to do this? For example if there are 2 Oak in the QS I want to get the first one filtered -
Terminate previous Celery task with same task id and run again if created
In my django project, I have made a view class by using TemplateView class. Again, I am using django channels and have made a consumer class too. Now, I am trying to use celery worker to pull quearyset data whenever a user reflesh the page. But the problem is, if user again reflesh the page before the task gets finished, it create another task which causes overload. Thus I have used revoke to terminate the previous running task. But I see, the revoke permanently revoked the task id. I don't know how to clear this. Because, I want to run the task again whenever user call it. views.py class Analytics(LoginRequiredMixin,TemplateView): template_name = 'app/analytics.html' login_url = '/user/login/' def get_context_data(self, **kwargs): app.control.terminate(task_id=self.request.user.username+'_analytics') print(app.control.inspect().revoked()) context = super().get_context_data(**kwargs) context['sub_title'] = 'Analytics' return context consumers.py class AppConsumer(AsyncJsonWebsocketConsumer): async def connect(self): await self.accept() analytics_queryset_for_selected_devices.apply_async( args=[self.scope['user'].username], task_id=self.scope['user'].username+'_analytics' )