Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Filter those rows that have most rows in in a related table, while also doing a distinct query
I have a Media model that has a many-to-many relationship to Artist (one Media can have many artists and one Artist can belong to many media). Also each user can rate each Media through a relational table named UserMedia, one Media can have multiple UserMedia. I want to do a query where I order by most ratings (UserMedia), while also filter the queryset for distinct Artist, such that each artist appears only once in the queryset and that Media is returned with the most UserMedia related rows (or counts). I can do the two things separately, order by most counts or do a distinct artists filter. Here's the query that I have right now: distinct_artists = models.Media.objects.distinct("artists__id") queryset = ( models.Media.objects.annotate( count_ratings=Count("usermedia"), ).filter( count_ratings__gte=F("count_ratings") ) .order_by("-count_ratings") .filter( id__in=distinct_artists ) ) The resultset returns distinct Artist, but not the Media with the most counts of UserMedia for this artist. -
Django group by and order by
I have comment table with following fields. Here, first row means, 3rd comment in the database belongs to post 1. Second and third row means, 3rd and 4th comments belongs to post 1 and they are also replies to the 2nd comment and so on. id post_id comment_id date 2 1 ... 3 1 2 ... 4 1 2 ... 5 1 ... 6 1 5 ... I would like to do a django group by query so such that, to get all the comments of post 1 and group them by the replies to a comment. So I would expect groups like this group1: comment2: comment3,4 group2: comment5: comment6 The group query should also be ordered by date field. How can I do this? -
Add a new item to a related fields within a form
I want a user to be able to select from an existing list of options. If the option is not within the ones already in the database, though, they need to be able to add a new item, while remaining on the main form, because after having added the new item they need to be able to save the main form I was using the JQuery library select2, which allows a tags:True option, thanks to which users can add a new item to a list if not present. Nevertheless, Django validates that field and if it finds an item which is not in the database is raises an error. My initial plan was that of capturing the new value in the view and then (saving first the form with commit=False), if it was not in the database, save it. But this is not doable without forcing Django not to validate the field, which I haven't managed to do. Another option, which I'm currently investigating, is that of adding a modal pop-up containing the sub-form. Of course I'd like to avoid opening the sub-form in another page, which would work but would be quite non-user-friendly. models.py: class Venue(models.Model): venue_name = models.CharField(max_length=30) … -
Authentication view doesn't recognize html template
I'm using authentication views in my project https://docs.djangoproject.com/en/2.2/topics/auth/default/#module-django.contrib.auth.views path('accounts/', include('django.contrib.auth.urls')), in my urls My issue is when it comes to the PasswordChangeView the accounts/password_change url shows the django adminstration page instead of the template I have under posts\templates\registration\password_change_form.html -
How to use CLASS BASED VIEWS and tags + slug in urls with DJANGO 2,.1
I am not sure why but i am unable to access the ProductListView page. The terminal just throw the error below. django.urls.exceptions.NoReverseMatch: Reverse for 'products' with no arguments not found. 1 pattern(s) tried: ['products/(?P<tag>[-a-zA-Z0-9_]+)/$'] Full traceback below: Internal Server Error: / Traceback (most recent call last): File "/Users/macadmin/Documents/Django_fun4/practical_django/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Users/macadmin/Documents/Django_fun4/practical_django/lib/python3.7/site-packages/django/core/handlers/base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/macadmin/Documents/Django_fun4/practical_django/lib/python3.7/site-packages/django/core/handlers/base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/macadmin/Documents/Django_fun4/practical_django/practical_django/core/views.py", line 18, in home return render(request, 'core/home.html') File "/Users/macadmin/Documents/Django_fun4/practical_django/lib/python3.7/site-packages/django/shortcuts.py", line 36, in render content = loader.render_to_string(template_name, context, request, using=using) File "/Users/macadmin/Documents/Django_fun4/practical_django/lib/python3.7/site-packages/django/template/loader.py", line 62, in render_to_string return template.render(context, request) File "/Users/macadmin/Documents/Django_fun4/practical_django/lib/python3.7/site-packages/django/template/backends/django.py", line 61, in render return self.template.render(context) File "/Users/macadmin/Documents/Django_fun4/practical_django/lib/python3.7/site-packages/django/template/base.py", line 171, in render return self._render(context) File "/Users/macadmin/Documents/Django_fun4/practical_django/lib/python3.7/site-packages/django/template/base.py", line 163, in _render return self.nodelist.render(context) File "/Users/macadmin/Documents/Django_fun4/practical_django/lib/python3.7/site-packages/django/template/base.py", line 937, in render bit = node.render_annotated(context) File "/Users/macadmin/Documents/Django_fun4/practical_django/lib/python3.7/site-packages/django/template/base.py", line 904, in render_annotated return self.render(context) File "/Users/macadmin/Documents/Django_fun4/practical_django/lib/python3.7/site-packages/django/template/loader_tags.py", line 150, in render return compiled_parent._render(context) File "/Users/macadmin/Documents/Django_fun4/practical_django/lib/python3.7/site-packages/django/template/base.py", line 163, in _render return self.nodelist.render(context) File "/Users/macadmin/Documents/Django_fun4/practical_django/lib/python3.7/site-packages/django/template/base.py", line 937, in render bit = node.render_annotated(context) File "/Users/macadmin/Documents/Django_fun4/practical_django/lib/python3.7/site-packages/django/template/base.py", line 904, in render_annotated return self.render(context) File "/Users/macadmin/Documents/Django_fun4/practical_django/lib/python3.7/site-packages/django/template/defaulttags.py", line 442, in render url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app) File "/Users/macadmin/Documents/Django_fun4/practical_django/lib/python3.7/site-packages/django/urls/base.py", line 90, in reverse return iri_to_uri(resolver._reverse_with_prefix(view, … -
Django - Retrieve url origin from view - multiple urls to 1 view
I have several urls mapping to one view. Inside the url, I would like to know the url origin? It is to avoid writing multiple views (DRY). urlpatterns = [ path('path1/', views.IndexView.as_view(), name='index'), path('path2/', views.IndexView.as_view(), name='index') ] class IndexView(generic.ListView): url_origin = ... #would like path1 or path2 I looked for 'reverse' but it does not seem to be a solution to my problem. It returns an error. reverse('index') Thank you in advance -
After refresh the browser the curent user be the admin
I have a djanog project, my problem is in the first time the current user is the logged one but if I refresh the browser, in the request.user if found the admin user, how can the overcame this issue ? -
How to fix "Forbidden (CSRF cookie not set.)"
When I send some data from my front-end via axios, my API give error Forbidden (CSRF cookie not set.) I use csrf_exempt to avoid this error, however it doesn't help me views.py: @csrf_exempt def registration(request): if request.method == 'POST': data = json.loads(request.body.decode('utf-8')) if not is_user_data_valid_for_create(data): return HttpResponseBadRequest() user_role = Role.objects.get(pk=1) user = User.create( first_name=data['first_name'], last_name=data['last_name'], email=data['email'], password=data['password'], role=user_role ) return HttpResponse("Success,{} your account created!".format(user.first_name), status=201) return HttpResponseBadRequest() This is my code on React: constructor(props) { super(props); this.state = { first_name: '', last_name: '', email: '', password: '' } } changeHandler = event => { this.setState({[event.target.name]: event.target.value}) }; submitHandler = event => { event.preventDefault() console.log(this.state); axios .post('http://127.0.0.1:8000/api/v1/user/restration/', this.state) .then(response => { console.log(response) console.log(response.data) }) .catch(error => { console.log(error) }) }; <form onSubmit={this.submitHandler}> <div className="user-data"> <div className="form-group"> <label>First Name</label> <input type="text" placeholder="John" name="first_name" value={first_name} onChange={this.changeHandler} className="form-control"/> </div> ... <div className="sign-up-w"> <button type="submit" className="btn-primary sing-up">SIGN UP</button> </div> </form> When I send data from UI I have the error: Forbidden (CSRF cookie not set.): /api/v1/user/restration/ "POST /api/v1/user/restration/ HTTP/1.1" 403 2868 However, when I send data via Postman everything is okay. -
Display one Form for related models and saving it - Django
I have two related models (Sim and Payment). After searching the requisite Sim, i want to change the status of Sim (model) and using the same form where blank fields of Payment would also be displayed, i want to save data (Payment model). I want that user should be able to see and update the details of Sim including phone number, IMSI and status and from the same form he should be able to save data of payment. class Sim(models.Model): phone_number = models.CharField(max_length=20, blank=True, unique=True, verbose_name ='Phone Number') imsi = models.CharField(max_length=19, blank=True, unique=True, verbose_name ='IMSI') sim_status = models.IntegerField(blank=False, default='1', verbose_name ='Sim Status') def __str__(self): return self.phone_number class Payment(models.Model): deposit_date = models.DateField(blank=True, verbose_name='Deposit Date') sim = models.ForeignKey(Sim, on_delete=models.DO_NOTHING, null=False, blank=False) I am using django crispy-forms class UpdatePayment(forms.ModelForm): phone_number = forms.CharField( label='Phone Number', widget=forms.TextInput(attrs={'readonly': 'readonly'})) imsi = forms.CharField(label='IMSI', widget=forms.TextInput(attrs={'readonly': 'readonly'})) poc = forms.CharField(label='Point of Contact', widget=forms.TextInput(attrs={'readonly': 'readonly'})) sim_status = forms.CharField (label='Sim Status',help_text='Please select type', widget=forms.Select(choices=SIM_STATUS) ) class Meta: model = Sim fields = ('phone_number', 'imsi', 'poc','sim_status',) def __init__(self, *args, **kwargs): super(UpdatePayment, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( Div( Div('phone_number', css_class="col-md-6"), Div('imsi', css_class="col-md-6"), css_class='row' ), Div( Div('poc', css_class="col-md-6"), Div('sim_status', css_class="col-md-6"), css_class='row' ), ) I am unable to find out how would … -
URL Displaying Wrong Form and View in Django
I am attempting to render a form where the only field is a dropdown. I have the form, view, .html, url all set up. But when I access this url, it shows a different form and view and I suppose also a different .html. I am so confused on why this is happening as it had been working fine for quite some time so I obviously changed something. forms.py #this is the form for the dropdown class ManifestDropDown(forms.Form): References = forms.ModelChoiceField(queryset=Orders.objects.values_list('reference', flat=True).distinct(), empty_label=None) manifest_references.html <!--html for dropdown--> {% extends 'base.html' %} {% block body %} <div class="container"> <form method="POST" action="manifest"> {% csrf_token %} {{ reference_list }} <button type="submit" class="btn btn-primary" name="button">Submit</button> </form> </div> {% endblock %} views.py #view for dropdown def manifest_references(request): if request.method == 'POST': if form.is_valid(): reference_id = form.cleaned_data.get('References') form.save() query_results = Orders.objects.all() reference_list = ManifestDropDown() context = { 'query_results': query_results, 'reference_list': reference_list, } return render(request, 'manifest_references.html', context) urls.py url(r'^manifest_references', manifest_references, name='manifest_references'), base.html <!--showing the link to this url--> ... <a class="dropdown-item" href="{% url 'manifest_references' %}">Edit Manifests</a> When I access the url above - instead of showing the manifest_references view with the dropdown, it immediately jumps to a different view manifest which is referenced as the action in … -
__init__() got multiple values for argument 'crescator'
I have a ModelForm and in a ModelChoiceField I need to filter objects by request.user. When data is submitted, I got the error "init() got multiple values for argument 'crescator' ". How can I repair that? #My Form class AdaugaPereche(forms.ModelForm): boxa = forms.IntegerField(label="Boxa", min_value=1) sezon = forms.CharField(label="Sezon reproducere", initial=datetime.now().year) mascul = forms.ModelChoiceField(queryset=None, label="Mascul", empty_label="Alege mascul") femela = forms.ModelChoiceField(queryset=None, label="Femela", empty_label="Alege femela") serie_pui_1 = forms.TextInput() serie_pui_2 = forms.TextInput() culoare_pui_1 = forms.ModelChoiceField(queryset=None, label="Culoare pui 1", empty_label="Alege culoarea", required=False) culoare_pui_2 = forms.ModelChoiceField(queryset=None, label="Culoare pui 2", empty_label="Alege culoarea", required=False) data_imperechere = forms.DateInput() primul_ou = forms.DateInput() data_ecloziune = forms.DateInput() data_inelare = forms.DateInput() comentarii = forms.TextInput() # Functie pentru filtrarea rezultatelor dupa crescator def __init__(self, crescator, *args, **kwargs): super(AdaugaPereche, self).__init__(*args, **kwargs) self.fields['mascul'].queryset = Porumbei.objects.filter(crescator=crescator, sex="Mascul", perechi_masculi__isnull=True) self.fields['femela'].queryset = Porumbei.objects.filter(crescator=crescator, sex="Femelă", perechi_femele__isnull=True) self.fields['culoare_pui_1'].queryset = CuloriPorumbei.objects.filter(crescator=crescator) self.fields['culoare_pui_2'].queryset = CuloriPorumbei.objects.filter(crescator=crescator) class Meta: model = Perechi fields = "__all__" #My view def perechenoua(request): if request.method == "POST": form = AdaugaPereche(request.POST, crescator=request.user) if form.is_valid(): obj = form.save(commit=False) obj.crescator = request.user obj.save() return HttpResponseRedirect("/perechi/") else: form = AdaugaPereche(crescator=request.user) context = { 'form': form } template = loader.get_template("adauga-pereche.html") return HttpResponse(template.render(context, request)) May the problem be obj = form.save(commit=False) obj.crescator = request.user obj.save() ? -
how can I upload & play audio files in Django
I have a project where I can upload & view pdf files but i want to upload & play audio files instead . What changes do I need to make ? Please Help This is my models.py What changes do I need to make for audio files ? from django.db import models class PDF(models.Model): title = models.CharField(max_length=100) pdf = models.FileField(upload_to='books/pdfs/') def __str__(self): return self.title This is my views.py of the app . What changes do I need to make for uploading and playing audio files? from django.shortcuts import render, redirect, HttpResponseRedirect from django.views.generic import TemplateView, ListView, CreateView from django.core.files.storage import FileSystemStorage from django.urls import reverse_lazy from .forms import * from .models import * def upload(request): context = {} if request.method == 'POST': #when request method is POST , the files are being uploaded uploaded_file = request.FILES['document'] fs = FileSystemStorage() name = fs.save(uploaded_file.name, uploaded_file) context['url'] = fs.url(name) return render(request, 'upload.html', context) #this function shows the "list of pdfs" in the database on pdf_list.html def pdf_list(request): pdfs = PDF.objects.all() return render(request, 'pdf_list.html', { 'pdf': pdfs }) #this function ensures that the file being uploaded is PDF def upload_pdf(request): if request.method == 'POST': form = PDFForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('pdf_list') else: … -
How to fix TemplateSyntaxError?
I'm trying to render template, but it always get an TemplateSyntaxError error. For solve this I tried to change construction. Instead {% if value %} -some action {% else %} {% endif %} I tried: {% if value_1 %} - some action {% endif %} {% if value_2 %} - some action {% endif %} But it didn't bring success, always the same error. I thought, that I made mistake with '{' or '%', but I didn't found anything, that couldn't be properly. Then I tried to find solve my problem, but all the problems that were considered had problems with the wrong syntax, like '%{' or '{ %'. --- VIEW --- class HumanList(TemplateView): def post(self, request): search_type = request.POST.get('type', False) search_object = request.POST.get('object', False) def separate(search_type, search_object): try: if search_type == 'name': return Human.objects.all().get(name__exact=search_object) if search_type == 'surname': return Human.objects.all().filter(name__contains=search_object) if search_type == 'company': return Human.objects.filter(company=search_object) if search_type == 'position': return Human.objects.filter(position=search_object) if search_type == 'language': return Human.objects.filter(language=search_object) except ObjectDoesNotExist: return None search_result = separate(search_type, search_object) if search_result: context = { 'result': search_result, 'searched': search_object, } else: context = { 'empty': 'We couldn\'t find anything', 'searched': search_object, } return render(request, 'result.html', context) --- HTML TEMPLATE --- {% extends 'human_list.html' … -
django passenger_wsgi issue something went wrong
hosting done successfully but error:we are sorry something went wrong looks like there is error in passenger_wsgi.py file, working on Django framework website should be live -
Disable Delete and Edit on condition
I want my Django program to check if my my entry is authorized and if it's either Manual or Auto. If it is authorized, then I want to prevent it from being deleted so basically disable the delete option for it and if it is Automatic, I want to prevent it from being edited when I click on the model object in the Django admin. Here is an example of my model: class ModelName(models.Model): AUTO_ATT = "AU" MANUAL_ATT = "MA" ENTRY_TYPES = ( (AUTO_ATT, "Auto-Attendance"), (MANUAL_ATT, "Manual-Attendance"), ) AUTHORIZED = "AU" UNAUTHORIZED = "UA" ENTRY_STATUSES = ( (AUTHORIZED, "Athorized"), (UNAUTHORIZED, "Un-Authorized"), ) status = models.CharField(max_length=2, choices=ENTRY_STATUSES, default=WORK_ENTRY_STATUSES[1][0]) type = models.CharField(max_length=2,choices=ENTRY_TYPES) So everytime I click on the object in the Django Admin, I want the program to first see if the entry is authorized and if its auto and display me the functions accordingly. -
How to return a message and redirect users in Django middleware
In my Django application, I pull a user's IP address and set a local city. However, if a user is out of the geographical area that the app covers, I want to raise an error and redirect them to the geographical area that this app covers. I'm trying to do this with middleware, but not sure how to do this. class RestrictUserMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ipaddress = x_forwarded_for.split(',')[-1].strip() else: ipaddress = request.META.get('REMOTE_ADDR') ip = get_client_ip(request) reader = geoip2.database.Reader(path) try: location = reader.city(ip) except: location = True if not response.subdivisions.most_specific.iso_code in 'CA': # raise error message here that it's not available outside CA request.session['city'] = 'Beverly Hills' return HttpResponseRedirect(reverse('index')) response = self.get_response(request) return response -
I'm not understanding this part of the code, need some suggestions to understand it
This part is for street - ##Street street = entry['street'] if entry['street']!=None else '' if street!=''and [{'exportHint':'street','subcategory':'street','value':street}] not in street: street_names.append([{'exportHint':'street','subcategory':'Street','value':street}]) for st in street_names: category.append([st]) This part is for displaying its value in template - <div class="{%if not responses%}span-19 {%endif%} last componentName" style="{%if responses%}width:{{responseDim.totalWidth|add:750}}px;{%endif%}padding-top:5px;"> <b>{{category.label}}</b> {% for entry in category.entries %} {% for group in entry %} {% for kv in group %} But, I'm not understanding how this works. Confused... -
How to filter if a store(point) lies inside a specific rectangle?
I am making an API with django rest framework. The app need to take of 4 corner coordinates and i need to filter all my stores out whether if it is in this rectangle or not. As a result i will filter out stores which is in this rectangle and serve it. How to make it with Django how to filter? thank you in advance. -
Django Wagtail Deployment Static File Server
After deployment today, for some reason, the project no longer shows style from items that would have been collected during the collectstatic process. I have full access to the files from any browser. I have checked all permissions. I have browsed to the site from the development server, and other machines to eliminate software\font possibilities. No idea what's going on here. I serve the files from a different server. Other django projects are unaffected. No other django projects use anything like wagtail though. Pulling my hair out at this point and probably just missing something simple. What am I missing? base.py config STATIC_ROOT = '/var/www/html/static.xxxxxx.net' STATIC_URL = 'http://static.xxxxxx.net/' MEDIA_ROOT = '/var/www/html/media.xxxxxx.net' MEDIA_URL = 'http://media.xxxxxx.net/' Checking for file existence on server: -rw-rw-r-- 1 xxxxxx xxxxxx 13648 Aug 24 09:18 /var/www/html/static.xxxxxx.net/wagtailadmin/css/userbar.3d5222a7eba2.css Checking CSS relative references -rw-rw-r-- 1 xxxxxx xxxxxx 68812 Aug 24 09:18 /var/www/html/static.xxxxxx.net/wagtailadmin/css/../../wagtailadmin/fonts/opensans-regular.45f80416d702.woff2 -
How to serve an image in django without using <img> tag in django?
Recently I started learning Django and at the first actually I want to prepare an API in order to serve images. for this purpose, when anybody requests to access to an image, my program should read raw image data from local library and serve it and prepare an access to this image for anybody who requests that image. notice that i don't want to show image with tag in my html file. just prepare an access to raw data in order to manipulation that image or anything similar. -
How to sanitise image field content to make sure it doesn't contain html form in django?
I have included imagefield in my django app and in the documentation I read that the validation done by the ImageField is not sufficient. I wanted to validate the image content to make user doesn't submit any html form. Is there any way to make sure that the image content is valid that it is not any sort of html under image extension. -
Execute function and print result in template without refresh
I'm using django to develop my website. In this page I have x as input, when i press enter a function will be executed and then the page will refresh and the result will be displayed. I would like to make it dynamic: capture input, execute function and show the result then another tag appears etc.. I will be very thankful. This is my python code: def console (request): import paramiko import time import getpass import re ip = '192.168.43.10' username = 'osboxes' password = 'osboxes.org' ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(ip, username=username, password=password, look_for_keys=False, allow_agent=False) print('Successfully connected to %s' % ip) remote_conn = ssh.invoke_shell() time.sleep(.005) output = remote_conn.recv(65535) print (output) def escape_ansi(line): ansi_escape = re.compile(r'(\x9B|\x1B\[)[0-?]*[ -/]*[@-~]') return ansi_escape.sub('', str(line)) x=request.GET['x'] time.sleep(1) remote_conn.send(x+'\n') time.sleep(0.1) if remote_conn.recv_ready(): output = remote_conn.recv(5000) op=output.decode() oo=escape_ansi(op) return render(request,'shell.html', {'oo' : oo}) This is my html file: {% extends 'base.html' %} {% block content %} <div class="mb-3 card text-white card-body" style="background-color: rgb(51, 51, 51); border-color: rgb(51, 51, 51);"> <h5 class="text-white card-title">Console log to the gateway</h5> <form action="console"> <div class="position-relative form-group" > <input rows="15" style="color: #FFFFFF; background-color: rgb(51, 51, 51)" name="x" id="x" class="form-control"> </div> </form> </div> <h3>result : {{oo}}</h3> {% endblock %} -
Set session in DRF not called in other request
I try create session in Django Rest API request but session not stored and fail get session in other page. settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', ] 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', ] api.py class PersonApiView(viewsets.ViewSet): permission_classes = (AllowAny,) parser_class = (FormParser, FileUploadParser, MultiPartParser,) # Sub-action send email persons @action(methods=['post'], detail=False, permission_classes=[AllowAny], url_path='send-validation', url_name='send_validation') @transaction.atomic def send_validation(self, request): request.session['user_id'] = 123 # set session request.session.create() return Response('OK!', status=status.HTTP_200_OK) home.py class HomeView(View): template_name = 'web/home.html' context = {} def get(self, request): user_id = request.session.get('user_id', None) print(user_id) # Always None return render(request, self.template_name, self.context) The session always return None Where i missed? -
Python or java script Dynamic maps
please I need help building a map for a ride sharing app ,I will like to build an app that updates the positions of customer on the drivers screen and also shows potential drivers on the passengers screen; So this are what I need 1. A map api that can load maps canvasses dynamically 2. A guide on how to do 1 3. I would like to use python or js -
“Context must be a dict rather than type.” Cannot be resolved
I want to use the obtained URL parameter for filter, but the error cannot be solved. I understand that "context ['group'] = belong.objects.get (user = user) .group" is the cause, but I don't know what to do. "username" has been acquired. #error context must be a dict rather than type. #view def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) user = self.kwargs.get('username') print(user) try: context['group'] = belong.objects.get(user=user).group except belong.DoesNotExist: pass except: return HttpResponseBadRequest try: context['count'] = URC.objects.filter(user=user).count() except URC.DoesNotExist: pass except: return HttpResponseBadRequest context['username'] = user return context