Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to remove date in pandas dataframe
How to remove date in datetimeformat 2022-06-20 14:59:02.559748+05:30 (14:59:02) #only time df = pd.DataFrame(queryset) df['duration'] = pd.to_datetime(df['stoptime']) - pd.to_datetime(df['starttime']) print(df['duration'] ) # "0 days 00:00:09.892016" TO 00:00:09 -
How to redirect after add/edit/delete in django
when i try to redirect after add/edit/delete operation i'm redirecting to the page i wanted but can not see the existing data, but after click on url section of browser and tap enter on it or go to other page and return to this one than it is showing me the data. Let me share a video link of deleting records. - https://drive.google.com/file/d/1Qyt_gxFoBe74DH_2rLbme9PD58Ll1z3I/view?usp=sharing and here is the code of deleting too. views.py def deleteuser(request, id): # user = get_object_or_404(AddContact, id = id) user = AddContact.objects.filter(id=id).delete() context = { 'user' : user } return render (request, "adduser.html", context) URL.py path('deleteuser/<id>', views.deleteuser, name="deleteuser"), html button <a href="/deleteuser/{{vr.id}}" class="btn btn-danger" data-target="success-modal-delete"><span class="fa fa-trash"></span> Delete</a> -
Why doesn't it print logs to the file?
Please tell me why it does not print a 404 error to a file? It is output to the console, but the file is empty Not Found: / [21/June/2022 11:52:02] "GET / HTTP/1.1" 404 2178 LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'formatters': { 'verbose': { 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s' }, 'simple': { 'format': '%(levelname)s %(message)s' }, }, 'filters': { 'special': { '()': 'project.logging.SpecialFilter', 'foo': 'bar', } }, 'handlers': { 'console':{ 'class':'logging.StreamHandler', 'formatter': 'simple' }, 'file': { 'class':'logging.FileHandler', 'formatter': 'verbose', 'filename': 'information.log' }, }, 'loggers': { 'main': { 'handlers':['console','file'], 'propagate': True, 'level':'INFO', } } } -
Django 4: problem with auth.authenticate, it returns None
I continue my progression with Django 4. But I have a new problem. my login code does not work, yet I followed the doc (I believe). The problem is at this level in my view.py. user=auth.authenticate(email=email, password=password) it returns none Could someone explain to me why the code does not work. Did I forget something? Here is my html code {% extends 'base.html' %} {% block content %} <section class="section-conten padding-y" style="min-height:84vh"> <div class="card mx-auto" style="max-width: 380px; margin-top:100px;"> <div class="card-body"> <h4 class="card-title mb-4">Sign in</h4> {% include 'includes/alerts.html' %} <form action="{% url 'login' %}" method="POST"> {% csrf_token %} <div class="form-group"> <input type="email" class="form-control" placeholder="Email Address" name="email"> </div> <!-- form-group// --> <div class="form-group"> <input type="password" class="form-control" placeholder="Password" name="password"> </div> <!-- form-group// --> <div class="form-group"> <a href="#" class="float-right">Forgot password?</a> </div> <!-- form-group form-check .// --> <div class="form-group"> <button type="submit" class="btn btn-primary btn-block"> Login </button> </div> <!-- form-group// --> </form> </div> <!-- card-body.// --> </div> <!-- card .// --> <p class="text-center mt-4">Don't have account? <a href="{% url 'register' %}">Sign up</a></p> <br><br> </section> {% endblock %} and my view code def login(request): if request.method == 'POST': email = request.POST['email'] password = request.POST['password'] user = auth.authenticate(email=email, password=password) if user is not None: auth.login(request, user) # messages.success(request, … -
Django Rest Framework: generics.RetrieveUpdateDestroyAPIView not working for the given below condition
In this generic APIView when I'm trying to log in through a non-admin user it is giving "detail": "You do not have permission to perform this action." but working fine for the admin user. I don't whether the problem is in code or permission.py I've shared my Views.py, permissions.py, and models.py for the same. If there is any mistake in my def get_queryset(self): please do let me know. Thank you!! class BookingRetrtieveUpdateDestroyAPIView(generics.RetrieveUpdateDestroyAPIView): permission_classes = [IsUserOrIsAdmin] # queryset = Booking.objects.all() # serializer_class = BookingSerializer def get_queryset(self): if self.request.user.is_admin == False: user_data= self.request.user book = Booking.objects.filter(user= user_data) return book else: book = Booking.objects.all() return book serializer_class = BookingSerializer permissions.py from django.contrib.auth import get_user_model from rest_framework.permissions import BasePermission User = get_user_model() class IsUserOrIsAdmin(BasePermission): """Allow access to the respective User object and to admin users.""" def has_object_permission(self, request, view, obj): return (request.user and request.user.is_staff) or ( isinstance(obj, User) and request.user == obj ) views.py class User(AbstractBaseUser): email = models.EmailField(verbose_name='Email',max_length=255,unique=True) name = models.CharField(max_length=200) contact_number= models.IntegerField() gender = models.IntegerField(choices=GENDER_CHOICES) address= models.CharField(max_length=100) state=models.CharField(max_length=100) city=models.CharField(max_length=100) country=models.CharField(max_length=100) pincode= models.IntegerField() dob = models.DateField(null= True) # is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name','contact_number','gender','address','state','city','country','pincode','dob'] def … -
Need help in asinging values for Choices in Choice Field in Django
models.py class Survey_Answer(models.Model): CHOICES = [('Disagree Strongly', 'Disagree Strongly'), ('Disagree', 'Disagree'), ('Undecided', 'Undecided'), ('Agree', 'Agree'), ('Agree Strongly', 'Agree Strongly')] question = models.ForeignKey(Survey_Question, on_delete=models.CASCADE) answer_text = models.CharField(max_length=20, choices=CHOICES, default='Undecided') date_published = models.DateTimeField('date published', auto_now_add=True) created_at = models.DateTimeField('created at', auto_now_add=True) def __str__(self): return self.answer_text + ' - ' + self.question.question_text This is my models.py. I need help in assigning value for a particular option in CHOICES( Eg: 5 points for Agree Strongly option). If a user selects an option from choices, he should be getting points based on the option he selected -
I could not return soap response
I need to write a soap service which gets soap request and return soap response. I could handle sending soap request with zeep client library, everythin correct. But i couldnt send any soap response it shows the same error:) import logging from datetime import datetime from spyne import Application, rpc, ServiceBase, AnyDict from spyne.protocol.soap import Soap11 from spyne.server.django import DjangoApplication from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt from invoice.api.russian_webservice.complex_models import Consignor, Request1Type, Request31Type, Request91Type, CertificateMaximumType, CertificateMinimumType, Response91Type from exim.models import ExportFSS, ImportFSS class RussianIntegrationApiView(ServiceBase): @rpc(Request91Type, _returns=AnyDict, _out_variable_name="Response91") def getResponse91(ctx, request91type): try: logging.info( f'Initialized objects {str(Request91Type).encode("utf-8")}') error_message = None error_code = None import_fss = ImportFSS.objects.create( number=request91type.certificate.number, given_date=datetime.strptime( request91type.certificate.date, '%d.%m.%Y'), exporter_name=request91type.certificate.consignor.name, exporter_country=request91type.certificate.departure_country, exporter_address=request91type.certificate.consignor.place, importer_name=request91type.certificate.consignee.name, importer_country=request91type.certificate.destination_country, importer_address=request91type.certificate.consignee.place, transport_method=request91type.certificate.transport.declared_type, transport_number=request91type.certificate.transport.number, disinfected_date=datetime.strptime( request91type.certificate.disinfection.date, '%d.%m.%Y'), treatment_method=request91type.certificate.disinfection.method, chemical=request91type.certificate.disinfection.chemical, duration_and_temperature=request91type.certificate.disinfection.temperature_times, concentration=request91type.certificate.disinfection.concentration, extra_info=request91type.certificate.additional_info, ) return { "GUID": CertificateMinimumType.guid_generate(), "SendDateTime": "2022-04-11T19:50:11 ", "Certificate": CertificateMinimumType.generate(), "Status": "Выдан", "StatusCode": "1601", "Inspector": "" } except Exception as e: logging.info(f'Exception occurred: {str(e)}') def on_method_return_string(ctx): ctx.out_string[0] = ctx.out_string[0].replace(b'soap11env', b'soapenv') ctx.out_string[0] = ctx.out_string[0].replace(b'tns', b'mun') ctx.out_string[0] = ctx.out_string[0].replace(b'GUID', b'm:GUID') ctx.out_string[0] = ctx.out_string[0].replace( b'SendDateTime', b'm:SendDateTime') ctx.out_string[0] = ctx.out_string[0].replace(b'Act', b'm:Act') ctx.out_string[0] = ctx.out_string[0].replace(b'Date', b'm:Date') ctx.out_string[0] = ctx.out_string[0].replace(b'Number', b'm:Number') ctx.out_string[0] = ctx.out_string[0].replace(b'Blanc', b'm:Blanc') ctx.out_string[0] = ctx.out_string[0].replace(b'OldDate', b'm:OldDate') ctx.out_string[0] = ctx.out_string[0].replace( b'CountryCode', b'm:CountryCode') ctx.out_string[0] = ctx.out_string[0].replace( b'ExpirationDate', b'm:ExpirationDate') ctx.out_string[0] = … -
Can I use ContentType.objects.get in templatetags?
I kept get this error while attempting to use contenttype in the templatetags. django.contrib.contenttypes.models.ContentType.DoesNotExist: ContentType matching query does not exist. I am trying to get an object by passing the modelname and pk as string to the simple_tag. Below is the codes. I have other custom filters in the same file that work fine. # in templatetags\srrp_tags.py from django import template from django.contrib.contenttypes.models import ContentType register = template.Library() @register.simple_tag def get_object(modelname, id): ctype = ContentType.objects.get(model=modelname) # this line trigger the error model = ctype.model_class() return model.objects.get(pk=id) In my html, model and primary are both string value # in templates\srrp\index.html {% load srrp_tags %} ... {% get_object modelname|title primary %} I have use the exact same code for the Contenttype in the view.py and it retrieve the required model with no issue. # in view.py class srrpListView(LoginRequiredMixin, PermissionRequiredMixin, ListView): ... def get_queryset(self): modelname = self.kwargs.get('modelname') ctype = ContentType.objects.get(model=modelname) # same code self.model = ctype.model_class() return self.model.objects.select_related().values() Any advice is much appreciated. Thank you -
How to prefetch or use select related in reverse generic relation in django?
Assume i have two models: class A: content_type = models.ForeignKey(ContentType, on_delete=models.PROTECT, null=True, blank=True) object_id = models.PositiveIntegerField(null=True, blank=True) attached_object = fields.GenericForeignKey('content_type', 'object_id') class B: some_field = GenericRelation(class A) Now I have a scenario where i need to list all of class B instances, and in that result list, i need to include some of class A which is related to class B. While trying to do that, obviously it is leading to as many query hits as there are instances of class B. I have searched all online forums to try and reduce queries in this case. instances_of_b = B.objects.all() for instance in instances_of_b: some_list.append(instance.related_instance_of_class_A.some_field_of_class_A) To get related_instance_of_class_A, i am using ContentType.objects.get_for_model(content_object) Is there any way to use select_related/prefetch related in this case? -
Add view in admin panel with same design as others
I'm trying to create a documentation part in my admin panel, and for that I created a custom admin site. I've overriden the get_app_list and get_urls methods in order to display a new line in the navigation bar and the dashboard, and I created a view to which this line redirects : class MyAdminSite(admin.AdminSite): def get_app_list(self, request): app_list = super().get_app_list(request) app_list += [ { "name": "Documentation", "app_label": "my_test_app", "models": [ { "name": "Scripts modification", "object_name": "Scripts modification", "admin_url": "/admin/documentation/modif/", "view_only": True, } ], } ] return app_list def get_urls(self): urls = super().get_urls() my_urls = [ path('documentation/modif/', self.admin_view(self.modif)), ] return my_urls + urls def modif(self, request): context = { 'title':"Documentation", } return render(request, "documentation/scripts_modification.html", context) Everything works correctly and when clicking on the new line, I'm redirected to the new view I created. However, I want my view to have the same design as the rest of the admin panel, which I didn't how to do. I extended admin/base_site.html but I only get the top of the page, and not the view site log out panel nor the navigation sidebar : I have no idea what I should change/configure in order to have the same display as the other admin pages. … -
Django/apache NLTK Permission denied: '/var/www/nltk_data'
I'm using NLTK with my Django/Apache application, however when loading a page it returns Permission denied: '/var/www/nltk_data' error. I made my user (not root) the owner of /var/www and gave permissions with sudo chmod -R 770 /var/www/. What else can I do to remove this error? -
How to write unit test for user-detail with router.register base name
this error appears when I write a test for user-detail, I thought the error from response = self.client.get(reverse('user-detail',kwargs={'pk':1})), I used router.register to config ulrs base name, and that makes me confused when writing the test. So in this case, where the point in my code was wrong? Thank you so much! def test_list_user_detail(self): """ List user detail """ self.client.post(self.url, self.data, format='json') resp = self.client.post( '/auth/token/login/', data={'email': 'Foo@gmail.com', 'password': 'Boo'}, format='json') token = resp.data['auth_token'] self.client.credentials(HTTP_AUTHORIZATION='token '+token) response = self.client.get(reverse('user-detail',kwargs={'pk':1})) print(response.data) self.assertEqual(response.status_code, status.HTTP_200_OK) ====================================================================== FAIL: test_list_user_detail (sellHouse.tests.UserTest) List user detail ---------------------------------------------------------------------- Traceback (most recent call last): File "D:\code\restfullapi\example\sellHouse\tests.py", line 68, in test_list_user_detail self.assertEqual(response.status_code, status.HTTP_200_OK) AssertionError: 404 != 200 ---------------------------------------------------------------------- try print response.data : {'detail': ErrorDetail(string='Not found.', code='not_found')} -
FormatException: Invalid character (at character 12) in flutter after changing the URL from http to https
I have a project; frontend using Flutter and the Backend using the Django framework. The project was working for a long time very well, but now I had to change the URL from HTTP to HTTPS and I got the following error: Now I have a couple of questions? first, why am I getting this error? second, should I change all URLs in my code for example http.Url('url') to https.Url('url'), and what should I do in the following example: final response = await http.get( url, // url is hammbwdsc02/visoon-backend headers: {"Authorization": "Bearer $authToken"}, ); Should I change again HTTP to HTTPS? -
Periodic Tasks Django that update state
I created a Django server. I have a class instance that loads its data from the database, once it is loaded (i.e. once the Django dev server starts). What I want to achieve is that there is a recurring task, such that the instance reloads from the database, once every day. I.e. <instance>.load_db() should be called, once a day. I tried to configure a cron job that calls the function once a day using crontab package. However, this only spawns a new instance of the server, does a reload there, but does not update the state of the running instance of the server. I would need the server to simply execute the tasks itself, not spawn a new instance of the server. Any ideas on how you can achieve this? -
Django Graphene filter date field with startswith using year and month
I am using Django and Graphene and have created a GraphQL query to return purchase orders from my database. All orders have a date field associated with it to represent when the order was created. The values in this column are formatted like 2022-05-01 08:38:17+01 - I know this is a datetime field and will rename the column at some point. I am trying to create a filter for the user to only return data from a particular month in a given year. The filter value is represented like 2022-05 for year and month. I would like the GraphQL to filter the data returned for that year and month. I am trying to use the startswith value to do this but getting an error that it is not a date. I understand that it is not a valid date, but I can't figure out how to filter the date field using only the year and month. Schema class Purchases(DjangoObjectType): id = graphene.ID(source='pk', required=True) class Meta: model = purchase_orders interfaces = (relay.Node,) filter_fields = {'date': ['startswith']} connection_class = ArtsyConnection GraphQL Query { Purchases(first: 15, after: "", date_Startswith: "2022-05") { ... Response { "errors": [ { "message": "Argument \"date_Startswith\" has invalid value … -
Django update user POST HTTP/1.1 302 0
Help me, please. What am I doing wrong? I'm trying to update the user, I send a request, but I get 302 in response. My request: https://skr.sh/sEYdKhpyf1w [21/Jun/2022 10:54:24] "GET /clients/client_1/update HTTP/1.1" 200 8884 [21/Jun/2022 10:54:29] "POST /clients/client_1/update HTTP/1.1" 302 0 [21/Jun/2022 10:54:29] "GET /clients/client_1 HTTP/1.1" 200 11527 views.py class UpdateClient(UpdateView): model = Profile form_class = ClientForm template_name = 'admins/admin_update_client.html' context_object_name = 'client' def get_context_data(self, **kwargs): cl = Profile.objects.get(pk=self.kwargs['pk']) c = json.loads(cl.CategoryVU) ctx = super(UpdateClient, self).get_context_data(**kwargs) ctx['cats'] = c return ctx def post(self, request, pk): lis = request.POST.getlist('CategoryVU') res = dict((i, lis.count(i)) for i in lis) data = json.dumps(res) form = ClientForm(request.POST) cl = Profile() if (form.is_valid()): cl= Profile.update_client(cl, request, pk, data) return redirect('admin_client', pk) forms.py class ClientForm(forms.ModelForm): class Meta: model = Profile fields = ('name', 'phone', 'email') -
Access javascript variables in python function file(views.py) using django
I want to access javascript array variable into python function file(views.py). I stored data in array using javascript and want to get that data into python function for further process. show.html function getvalues() { var val = []; $(':checkbox:checked').each(function (i) { val[i] = $(this).val(); }); } views.py def show(request): selected = val[i] return render(request, "show.html", {}) I want to use val[i] into views.py show() function. If I need to use AJAX then how I can use AJAX? or there is some other way to access data -
Django template if expression not correct?
My Django template returns error as: (error at line 26 )Unused 'item' at end of if expression. I checked the reported lines as below and didn't where's the error in my code. Could anyone help me? In which line 26 is {%if cur_prj and item == cur_prj %} The whole snippet is as: {%for item in PROJS %} {%if cur_prj and item == cur_prj %} <option value={{item}} selected>{{item}}</option> {%elif not cur_prj item == my_case.project_name%} <option value={{item}} selected>{{item}}</option> {%else%} <option value={{item}}>{{item}}</option> {%endif%} {%endfor%} -
Page not found (404) in Django Output
my url.py urlpatterns = [ path("", views.index, name="blogHome"), path("blogpost/<int:id>/", views.blogpost, name="blogHome") ] my views.py django.shortcuts import render from .models import Blogpost # Create your views here. def index(request): return render(request, 'blog/index.html') def blogpost(request, id): post.Blogpost.objects.filter(post_id = id)[0] print(post) return render(request, 'blog/blogpost.html') my models.py from django.db import models class Blogpost(models.Model): post_id = models.AutoField(primary_key=True) title = models.CharField(max_length=50) head0 = models.CharField(max_length=500, default="") chead0 = models.CharField(max_length=10000, default="") head1 = models.CharField(max_length=500, default="") chead1 = models.CharField(max_length=10000, default="") head2 = models.CharField(max_length=500, default="") chead2 = models.CharField(max_length=10000, default="") pub_date = models.DateField() thumbnail = models.ImageField(upload_to='blog/images', default="") def __str__(self): return self.title Error Error Image which i see in output Error in cmd Not Found: /blog/blogpost [21/Jun/2022 12:29:33] "GET /blog/blogpost HTTP/1.1" 404 2678 Please help me to solve this problem as soon as possible -
Django: Get average rating per user
Given the following, how can I make a query which returns a list of the average rating per user in friendlist? models.py class Beer(models.Model): id = models.BigIntegerField(primary_key=True) name = models.CharField(max_length=150) ... class Checkin(models.Model): id = models.IntegerField(primary_key=True) rating = models.FloatField(blank=True, null=True) ... class FriendList(models.Model): user = models.OneToOneField(User, on_delete=CASCADE, primary_key=True) friend = models.ManyToManyField(User, related_name="friends") database (postgresql) user beer rating 1 1 4.2 1 1 3.5 1 1 4.0 2 1 4.1 2 1 3.7 My current query to get all friends checkins: Checkin.objects.filter(beer=1, user__in=friends.friend.all()) Which gives me something like: [{user: 1, rating: 4.2}, {user: 1, rating: 3.5},...,{user: 2, rating: 4.1}...] What I want is: [{user: 1, avg_rating: 4.1}, {user: 2, avg_rating: 3.8}] -
Python group a list of years, months to remove duplication of years
I have a table that contains orders, in which contains the date column. I am getting back the aggregate of the years, and months from that column so that I can use that data in a filter on the front end. I have managed to get this data back, however it is not formatted in the way I would like. Python years = purchase_orders.objects.filter(user_id=info.context.user.id).annotate(year=ExtractYear('date'), month=ExtractMonth('date'),).order_by().values_list('year', 'month').order_by('year', 'month').distinct() Data Returned <QuerySet [(2020, 3), (2021, 4), (2022, 1), (2022, 2), (2022, 3), (2022, 4), (2022, 5)]> Ideal Format <QuerySet [(2020, (3)), (2021, (4)), (2022, (1, 2, 3, 4, 5))]> -
NoReverseMatch at / Reverse for 'register_request' not found. 'register_request' is not a valid view function or pattern name
this is a shopping website my login and registration form is not working it is showing that no reverse path found error. this is my navbar template <div class="container py-5"> <p class="text-center">If you already have an account, <a href="{% url 'sweet:register_request' %}">login</a> instead.</p> </div> <div class="container py-5"> <p class="text-center">Don't have an account? <a href="/register">Create an account</a>. </p> </div> login.html this is my login template {% extends "base.html" %} {% load static %} {% block content %} {% csrf_token %} {{ login_form }} Login {% endblock %} home.html this is my registration template {% extends "base.html" %} {% load static %} {% block content %} Register {% csrf_token %} {{register_form}} {% endblock %} views.py register_request is function defined to register the form and login_request is to login into my website def register_request(request): if request.method == "POST": form = NewUserForm(request.POST) if form.is_valid(): user = form.save() login(request, user) messages.success(request, "Registration successful.") return redirect('login_request') messages.error(request, "Unsuccessful registration. Invalid information.") form = NewUserForm() return render(request,"home.html",{"register_form": form}) def login_request(request): if request.method == "POST": form = AuthenticationForm(request, data=request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username, password=password) if user is not None: login(request, user) messages.info(request, "You are now logged in as {username}.") return redirect("base.html") … -
chrome makes null endpoint request in django service
My env is django backend , vuejs from vite frontned. also using django-vite package in backend and nginx for proxy server. But when I depolyed all code to server, now I am getting null endpoint request. I can only see it in chrome browser. It doesn't appear in IE edge. Why does it happend? Do you guys have any idea? I left screenshot and service url http://3.35.61.148/ Can it be related to not using SSL(https) ? -
django allauth multiple custom forms for social sign up
I want to build 2 different custom forms, one for google sign up accounts, and one for facebook sign up accounts. Yet allauth only allow one custom form for all social sign up via the settings.py: SOCIALACCOUNT_FORMS = {'signup': 'accounts.forms.SignupFormSocial'} Is there a way to this ? Like pass in two different form to the overriden forms so I can choose which one to show based on the current provider. -
How to add extra per-Feed fields to a Django Feed (Specifically, a Django-iCal feed)
I am generating a per-user calendar feed. As part of the URL, I'm allowing event filters. I am struggling to figure out how to save that filter (or any arbitrary variable) to the specific Feed I am generating from the specific call. The method I thought would work is (coming from a C++ world) making a static variable that is shared amongst all Feed callers, which would lead to inconsistency when Feeds are being generated simultaneously. What is the proper way to do this? Reading through the Feed libraries, I see methods like feed_extra_kwargs() and item_extra_kwargs(), but I can't find examples or documentation on them that show how to use them. My URL: re_path(r'^ics/(?P<user_id>\d+)/(?P<params>[\w=;]+)/ical.ics$', EventFeed(), name='ics'), My Feed attempt: class EventFeed(ICalFeed): """ A simple event calender """ product_id = '-//icevite.com//Schedule//EN' timezone = 'UTC' file_name = "icevite.ics" filter = [] alarms = [] def get_object(self, request, user_id, params, *args, **kwargs): self.filter = [] try: split = params.split(";") for s in split: item = s.split("=") match item[0]: case "f": self.filter = list(item[1]) case "n": mins = int(item[1]) if mins: self.alarms.append(mins) return Player.objects.get(id=user_id) except: return None def items(self, player): responses = Response.objects.filter(mate__player=player) if self.filter: filtered = responses.exclude(response__in=self.filter) else: filtered = responses return filtered.select_related('game', …