Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'player.Player' that has not been installed
I couldn't find any solution, that's why I must make a new thread here. The app player is of course installed and I didn't forget about putting AUTH_USER_MODEL = 'player.Player' in settings.py. Obviously I tried to delete DB and migrations and it didn't work neither. models.py code based on tutorial made by CodingWithMitch below: from django.db import models from django.contrib.auth import get_user_model from django.contrib.auth.models import AbstractBaseUser, BaseUserManager User = get_user_model() class MyPlayerManager(BaseUserManager): def create_user(self, email, username, password=None): if not email: raise ValueError('Users must have an e-mail address') if not username: raise ValueError('Users must have a username') user = self.model( email=self.normalize_email(email), username=username, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, password): user = self.create_user( email=self.normalize_email(email), username=username, password=password, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class Player(AbstractBaseUser): # USER FIELDS email = models.EmailField( verbose_name='email', max_length=100, unique=True, ) username = models.CharField(max_length=50, unique=True) date_joined = models.DateTimeField( verbose_name='date joined', auto_now_add=True, ) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email', ] objects = MyPlayerManager() def __str__(self): return self.username def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, app_label): return True -
Django timezone.now()'s value is not changing
I'm trying to annotate a queryset with a certain value. This is my annotation: def annotate_time(self, name='time'): annotation = { name: Case( When( datetime_submitted__isnull=False, then=((F('datetime_submitted') - F('datetime_started')) / 1000000) ), When( task__end_time__lt=timezone.now(), then=((F('task__end_time') - F('datetime_started')) / 1000000) ), default=((timezone.now() - F('datetime_started'))), output_field=IntegerField() ) } return self.annotate(**annotation) The first two When cases are already working, but I'm not sure why, if the default case is the selected case, the value is always constant no matter how many times this function runs. Am I doing something wrong here? -
How to use partialmethod with Django Jinja2
I am following this guide to generate a method similar to get_FOO_display() to display the help_text for a named field in a template (which I define as get_FOO_help_text()): class MyModel(models.Model): def __init__(self, *args, **kwargs): # Call the superclass first; it'll create all of the field objects. super(MyModel, self).__init__(*args, **kwargs) # Again, iterate over all of our field objects. for field in self._meta.fields: # Create a string, get_FIELDNAME_help_text method_name = "get_{0}_help_text".format(field.name) # We can use partialmethod to create the method with a pre-defined argument partial_method = partialmethod( self._get_FIELD_help_text, field=field.name ) # And we add this method to the instance of the class. setattr(self, method_name, partial_method) def _get_FIELD_help_text(self, field): value = getattr(self, field.help_text) return str(value) However, when I use the Jinja2 template engine to render the template using {{ object.get_FOO_help_text() }} I get the following error: TypeError at /display/ 'partialmethod' object is not callable It needs to be callable in the template as otherwise Jinja displays: functools.partialmethod(<bound method MyModel._get_FIELD_help_text of <object: instance>>, , field_name='FOO') Any ideas? -
How can i add a "like" button in a Django class ListView
I am pulling my hair out trying to add a "like" button in my site´s post app, but as i want to add it in a ListView that contains the rest of the posts entries and everyone has the option to be commented I have added a Formixin to do so, so, now i cannot add another form for the like button as it would mean two posts requests....so I am not finding a clear solution... I have read here and there about using AJAX or Json techs but as im new programing im kind of stuck in it... has anyone any tip to offer? -
For Loop HTML Django
I have a for loop within my Django project, what I'am trying to do is the following : If morning_recess == True lunch_recess == True afternoon_recess == True then the bootstrap tag in that field should be <td><span class="badge badge-success">Success</span></td> else <td> None </td> Here is my current code: <table style="width:100%"> <tr> <th>Student Name</th> <th>Morning Recess</th> <th>Lunch Recess</th> <th>Afternoon Recess</th> <th>Earned At</th> </tr> <tr> {% for i in students_recess_today %} {% if i.morning_recess == True %} <td>{{i.student_ps }}</td> <td><span class="badge badge-success">Success</span></td> <td>{{i.lunch_recess}}</td> <td>{{i.afternoon_recess}}</td> <td>{{i.created_at}}</td> {% else %} <td>{{i.student_ps }}</td> <td>None</td> <td>{{i.lunch_recess}}</td> <td>{{i.afternoon_recess}}</td> <td>{{i.created_at}}</td> {% endif %} </tr> {% endfor %} </table> </div> The morning_recess works fine, however if i do another if statement after the following one, the order of my table gets all messed up. How do I write this correctly? Thank you -
user is not iterable
art, admin = saveArt=(request.POST, art=t_object_type, art_form, request.user)# = I am running app in django 2.2 and python 3.6.9 , I am getting that error and still couldnt find a fix. PLease help thank you -
Apache doesn't restart because of syntax error
I got this: Apache is not restarting because a syntax error. This is a screenshot of error. I installed recently apache and have not done any configuration. This is my virtual host code: <VirtualHost *:80> ServerAdmin informaticoerma@minag.cu ServerName www.erma.minag.cu <Directory /srv/ermaweb> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess erma python-path=/srv/ermaweb WSGIProcessGroup erma WSGIScriptAlias / /srv/ermaweb/ermaweb2/wsgi.py DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static/ /srv/ermaweb/static/ Alias /media/ /srv/ermaweb/media/ <Directory /srv/ermaweb/static/> Require all granted </Directory> <Directory /srv/ermaweb/media/> Require all granted </Directory> </VirtualHost> NOTE: Apache is installed recently and any configuration has been done. -
Django successful migrate but didn't create table on MYSQL
Could anyone help me. At first, I created a sqlite DB for my APP , but now need to migrate it into MYSQL. in SQLITE all are working fine but when I migrated to MYSQL it's not creating table Thanks in advance for those who will help. models.py from django.db import models class sslDomain(models.Model): domain = models.CharField(max_length=20, default='') expiration = models.TextField(max_length=50, default='') date_now = models.TextField(max_length=50, default='') status = models.IntegerField(max_length=50, default=0) daysleft = models.TextField(max_length=50, default='') def __str__(self): return self.domain class logsTable(models.Model): logs_field = models.TextField(max_length=100, default='') def ___str__(self): return self.id auth_db.py(my DBrouter) from .apps import * class AuthSslDB: """ A router to control all database operations on models in the auth application. """ def db_for_read(self, model, **hints): """ Attempts to read auth models go to auth_db. """ if model._meta.app_label == SsldomainsConfig.name: return 'argus_v2_db' return None def db_for_write(self, model, **hints): """ Attempts to write auth models go to auth_db. """ if model._meta.app_label == SsldomainsConfig.name: return 'argus_v2_db' return None def allow_relation(self, obj1, obj2, **hints): """ Allow relations if a model in the auth app is involved. """ if obj1._meta.app_label == SsldomainsConfig.name or \ obj2._meta.app_label == SsldomainsConfig.name: return True return None def allow_migrate(self, db, app_label, model_name=None, **hints): """ Make sure the auth app only appears … -
ModuleNotFoundError: No module named 'twochekout'
I want to make payment gateway integration method for my e-commerce website.I follow the statement on github. But it gives an error please help me to solve this error. views.py: from django.shortcuts import render import twochekout from twocheckout import TwocheckoutError # Create your views here. def home(request): twocheckout.Api.auth_credentials({ 'private_key': 'sandbox-private-key', 'seller_id': 'sandbox-seller-id', 'mode': 'sandbox' }) # Setup arguments for authorization request args = { 'merchantOrderId': '123', 'token': request.form["token"], 'currency': 'USD', 'total': '1.00', 'billingAddr': { 'name': 'Testing Tester', 'addrLine1': '123 Test St', 'city': 'Columbus', 'state': 'OH', 'zipCode': '43123', 'country': 'USA', 'email': 'example@2co.com', 'phoneNumber': '555-555-5555' } } # Make authorization request try: result = twocheckout.Charge.authorize(args) return result.responseMsg except TwocheckoutError as error: return error.msg return render(request,'index.html') -
Django rest one-to-many Got AttributeError
Error Got AttributeError when attempting to get a value for field participant_set on serializer MatchSerializer. The serializer field might be named incorrectly and not match any attribute or key on the Match instance. Original exception text was: 'Match' object has no attribute 'participant_set'. Models.py class TournamentTeam(models.Model): tournament = models.ForeignKey(Tournament, on_delete=models.SET_NULL, null=True) team = models.ForeignKey(TeamPlayer, on_delete=models.SET_NULL, null=True) class Match(models.Model): name = models.TextField(blank=False, null=False) participant = models.ManyToManyField(TournamentTeam, through='MatchParticipant') class MatchParticipant(models.Model): match = models.ForeignKey(Match, on_delete=models.SET_NULL, null=True, blank=True) team = models.ForeignKey(TournamentTeam, on_delete=models.SET_NULL, null=True, blank=True) score = models.CharField(max_length=255, null=True, blank=True) Serializers.py class MatchParticipantSerializer(serializers.ModelSerializer): class Meta: model = MatchParticipant fields = '__all__' class MatchSerializer(serializers.ModelSerializer): participant_set=MatchParticipantSerializer(many=True) class Meta: model = Match fields = ('name','participant_set') Views.py class MatchAPIView(ListAPIView): queryset = Match.objects.all() serializer_class = MatchSerializer -
Django, persistance without serialization
I'm working on a Django project that uses a flatbed scanner. It takes a long time to connect to the scanner. So I'm looking for a way to re-use the scanner instance. Serialization seems to be the go to solution for this problem. Unfortunately I can not serialize or pickle the scanner instance. I keep running into errors that tell me that that serialization failed. Is there an alternative way to re-use the same scanner instance for multiple scans? A back-end trick or maybe some front-end magic? (Note, I know nothing about front-end development.) We can cheat a little! The project will be running offline on a local computer, there is no internet or network connection at all. This might give options that are otherwise insecure. Stuff I'm using for scanning sane, packages for accessing scanners python3-sane, a Python wrapper for sane Image Scan, drivers for scanners -
How to go back to a DetailView page by grabbing it's slug?
I've made a "like" feature to like a blog post, but I don't know how to redirect to the same DetailView page after pressing the like button. The "like" button will trigger a view which is at "likes/" URL. But I don't know how to come back to the same blog post page again. I'm stuck. Here is the code for reference. posts_detail.html <body style="width: 60%; margin: 0 auto; background-color: rgb(205, 249, 255);"> <div class="box-style"> <h1 class="heading-text">{{ posts.title }}</h1> <br> <div class="poem-text"> <pre>{{ posts.content }}</pre> </div> <br> <div class="footer-text"> <p>Author: {{ posts.author.first_name }} {{ posts.author.last_name }} <br> Posted On: {{ posts.published_time }} </p> <br> </div> <!-- <a href=" {% url 'like' %} " class="btn btn-danger">Like {{ posts.likes.count }} </a> --> {% if request.user.is_authenticated %} <form action="{% url 'like' %}" method="POST" id= "like_form"> {% csrf_token %} <button type="submit" class="btn btn-danger" id="post_id" name="post_id" value="{{ posts.id }}">Like {{ posts.likes.count }}</button> </form> {% else %} <a href="{% url 'login' %}" class="btn btn-primary">Like {{ posts.likes.count }}</a> {% endif %} </div> </body views.py def likeToggle(request, *args,**kwargs): if request.POST: slug= kwargs.get('slug') print(slug) post= get_object_or_404(Posts, id= request.POST.get('post_id')) print(post) user= request.user print(user) if user in post.likes.all(): post.likes.remove(user) else: post.likes.add(user) else: pass return redirect('postlist') urls.py urlpatterns= [ path('create/', views.PostCreate.as_view(), name='createpost' … -
Django Serializer nested relation where 2 models are not directly related?
I want to get nested results for cases where 2 models are not directly related but indirectly related through a table. below is just to replicate the situation i am in and not the actual code that i am using. class ArtistSerializer(serializers.ModelSerializer): class Meta: model = Artist fields = ['name', 'age'] class TrackSerializer(serializers.ModelSerializer): artist = ArtistSerializer(read_only=True) class Meta: model = Track fields = ['order', 'title', 'duration', 'artist'] class ConcertSerializer(serializers.ModelSerializer): artist = ArtistSerializer(read_only=True) tracks = TrackSerializer(many=True, read_only=True) class Meta: model = Concert fields = ['concert_name', 'artist', 'tracks'] Artist and Track are related. Also, Artist and Concert are related. But I want to get tracks using TrackSerializer to get tracks with same artist for a concert when they are not directly related. Is this possible? There will be multiple tracks for a concert. -
Application deployment through pythonanywhere
Please anyone who can help me in the area of deploying my blog application. I have installed github and pythonanywhere on system,I currently following django girls tutorial as a guide as a beginner. I have actually followed the tutorial accordingly up to the deploying the app but I can't go further because of the error I got from the pythonanywhere console. Attached is the copy of what I did,enter link description herehaving done the needfulpythonanywhere console error. -
Pc does not see the django?
I am trying to install django as said on the official page py -m pip install Django But for some reason, such a warning was displayed during installation WARNING: The script virtualenv.exe is installed in 'C: \ Users \ user \ AppData \ Local \ Programs \ Python \ Python37 \ Scripts' which is not on PATH. Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location. AND WARNING: You are using pip version 19.2.3, however version 20.0.2 is available. You should consider upgrading via the 'python -m pip install --upgrade pip' command. But I have pip version 20.0.2 and when I try to find out which version I have django he's writing C: \ Users \ user \ AppData \ Local \ Programs \ Python \ Python37 \ python.exe: No module named Django what am I doing wrong Python version 3.7.6 -
Django save methode collide with signal on model change
I want to save a postcover and a correspondending postcover thumbnail in a smaller resolution. In the end users can also change the postcover. To accomplish a proper file handling im working with model.signals. this seems to work pretty fine until i try to change the postcover of my Post object. When i try to save the Post object with a changed postcover i get the following error: ValueError: The 'postcover' attribute has no file associated with it. initiali creating and deleting the Post object works as expected. models.py class Post(models.Model): ... postcover = models.ImageField( verbose_name="Post Cover", blank=True, null=True, ) postcover_tn = models.ImageField( verbose_name="Post Cover Thumbnail", blank=True, null=True, ) ... def save(self, *args, **kwargs): super(Post, self).save(*args, **kwargs) if self.postcover: if os.path.exists(self.postcover.path): image = Image.open(self.postcover) outputIoStream = BytesIO() baseheight = 600 hpercent = baseheight / image.size[1] wsize = int(image.size[0] * hpercent) imageTemproaryResized = image.resize((wsize, baseheight)) imageTemproaryResized.save(outputIoStream, format='PNG') outputIoStream.seek(0) self.postcover = InMemoryUploadedFile(outputIoStream, 'ImageField', "%s.png" % self.postcover.name.split('.')[0], 'image/png', sys.getsizeof(outputIoStream), None) image = Image.open(self.postcover) outputIoStream = BytesIO() baseheight = 100 hpercent = baseheight / image.size[1] wsize = int(image.size[0] * hpercent) imageTemproaryResized = image.resize((wsize, baseheight)) imageTemproaryResized.save(outputIoStream, format='PNG') outputIoStream.seek(0) self.postcover_tn = InMemoryUploadedFile(outputIoStream, 'ImageField', "%s.png" % self.postcover.name.split('.')[0], 'image/png', sys.getsizeof(outputIoStream), None) elif self.postcover_tn: self.postcover_tn.delete() super(Post, self).save(*args, **kwargs) signals.py … -
resetting password of user django rest auth
Good day, I am trying to override the password_reset_email of Django allauth. the issue is that it successfully overrides, but the data (password reset link, site name, and domain name) does not get passed to the email which eventually means that the user is not able to reset password because no link was sent. In my PasswordResetSerializer ###################### password reset serializer ###################### class PasswordResetSerializer(serializers.Serializer): ''' override of the reset password serializer so the html representation of the email reset password would work ''' email = serializers.EmailField() password_reset_form_class = PasswordResetForm def validate_email(self, value): self.reset_form = self.password_reset_form_class(data=self.initial_data) if not self.reset_form.is_valid(): raise serializers.ValidationError(_('Error')) ###### FILTER YOUR USER MODEL ###### if not User.objects.filter(email=value).exists(): raise serializers.ValidationError(_('Invalid e-mail address')) return value def save(self): request = self.context.get('request') opts = { 'use_https': request.is_secure(), 'from_email': getattr(settings, 'DEFAULT_FROM_EMAIL'), ###### USE YOUR TEXT FILE ###### 'email_template_name': 'account/email/password_reset_key.html', 'html_email_template_name': 'account/email/password_reset_key.html', 'request': request, } self.reset_form.save(**opts) In my templates/registration/password_reset_email.html {% load i18n %} {% autoescape off %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Confirm Your E-mail</title> <style> .body { background-color: #f6f6f6; padding: 30px; display: flex; flex-direction: row; justify-content: center; align-items: center; } .content { background-color: #FFFFFF; color: #4d4d4d; max-width: 400px; padding: 20px; margin: auto; } .title … -
"manage.py runserver" gives me an error I haven't been able to solve for 3 days now
I have seen other people in here with this issue but I couldn't seem to get any of the solutions to their problems to work for me. I am developing a todoapp in python, and I have reached a point at which, whenever I run the "manage.py runserver" command in CMD(yeah I'm using cmd. I'm pretty cool like that) I get the following error: TypeError: _getfullpathname: path should be string, bytes or os.PathLike, not function To my understanding, the issue is most likey in my settings.py-file, which looks like this: import os import mimetypes mimetypes.add_type("text/css", ".css", True) # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static') STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage' # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'S U C C' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'todolist', ] 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.storage.CompressedManifestStaticFilesStorage', 'whitenoise.middleware.WhiteNoiseMiddleware', ] ROOT_URLCONF = 'todoapp.urls' TEMPLATES = [ { 'BACKEND': … -
How can insert in queryset?
I'd like to make if payer is not in the dutch_payer, I'd like to same payer name user checked in dutch_payer. So payer is always checked in dutch_payer as a default. how can I make it? class UpdateMoneylogForm(forms.ModelForm): class Meta: model = models.Moneylog fields = ( "pay_day", "payer", "dutch_payer", "price", "category", "memo", ) widgets = { "pay_day": forms.DateTimeInput(attrs={"style": "width:100%"}), "dutch_payer": forms.CheckboxSelectMultiple, "memo": forms.Textarea(attrs={"rows": 3, "style": "width:100%"}) } def save(self, *args, **kwargs): payer = self.cleaned_data.get("payer") dutch_payer = self.cleaned_data.get("dutch_payer").filter(name=payer) if dutch_payer.count() == 0: clean_dutch_payer(self) moneylog = super().save(commit=False) return moneylog def clean_dutch_payer(self): data = self.cleaned_data['dutch_payer'] data = data+self.cleaned_data.get( "dutch_payer").filter(name=payer) return data and the moneylog>models.py is payer = models.ForeignKey( tempfriend_models.Tempfriend, on_delete=models.CASCADE, related_name="payer") dutch_payer = models.ManyToManyField( tempfriend_models.Tempfriend, related_name="dutch_payer", blank=True) user>models.py ... username = models.CharField(max_length=10, blank=False, unique=True) tempfriends>models.py class Tempfriend(core_models.TimeStampedModel): name = models.CharField(max_length=30) belongs_to = models.ForeignKey( user_models.User, on_delete=models.CASCADE, related_name="belongs_to") -
re-render part of the website with django and leave the old part like this [duplicate]
i have a tag based output in an html. there is also a button on the html. i would now like to do a new django database query and display new elements under the butts without reloading the whole page. Is that possible? So quasi an update of the page -
how to pass a primary key to a view in django?
I am trying to implement a class based view that should create a update form to update my model form but I don not know how to pass the pk from my base.html to my view: viewvs.py: from artdb.models import * class UpdateForm(UpdateView): print('updateform') model=Date fields=['activity'] template_name='updateForm.html' updateForm.html: {% extends "artdb/base.html" %} {% block upd %} <form action="" method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Update"> </form> {% endblock upd %} base.html: <p><a class="btn btn-secondary" href="{% url 'artdb:updateform' %}" role="button">update form &raquo;</a></p {% block upd %} {% endblock upd %} urls.py: urlpatterns = [ path('<pk>/updateform/',views.UpdateForm.as_view(),name='updateform'), ] I think that pk should be passed in the base.html but I am not shure how. Any suggestions? -
How to get the project root of django project
I am using django 3 I want to get root directory of project. I googled around and found that I should use this SITE_ROOT = os.path.dirname(os.path.realpath(__file__)) in settings.py though, I can't figure out how to use SITE_ROOT in other script. Maybe this is quite silly and newbee question though,, -
What does the following note in Django's documentation mean?
While browsing the docs for Django's UUIDField, I saw the following Lookups on PostgreSQL Using iexact, contains, icontains, startswith, istartswith, endswith, or iendswith lookups on PostgreSQL don’t work for values without hyphens, because PostgreSQL stores them in a hyphenated uuid datatype type. Is this something related to using UUIDField? Or is this a general note for any string values? If so, can someone provide an example of where these operations don't work with strings without hyphens? -
Django Rest Framework - re-using models as much as possible when deserializing responses in a python client
When developing a REST API using django and django rest framework, it seems to me that there's a step missing at the very end of this chain: define the model of your resources in django use DRF's serializers to send your resource over HTTP missing: deserialize your resource back in a python model Let me give a simple example. I declare the following django model with a bit of business logic: class Numberplate(models.Model): number = models.CharField(max_length=128) country_code = models.CharField(max_length=3) def __repr__(self): return f"{self.number} ({self.country_code})" DRF is super powerful when it comes to building the API around that model. However, if I call that API from a python client, it seems that the best I can get as a response from that API will be a simple json without all the logic I might have written in my model (in this case, the __repr__ method), and I'll have to navigate through it as such. Continuing my example, here is the difference with and without a proper deserializer: # the best we can do without rewriting code: >> print(api.get(id=3)) {"numberplate": "123ABC", "country_code": "BE"} # instead of re-using my __repr__, which would be ideal: >> print(api.get(id=3)) 123ABC (BE) Is there a clean way … -
Combine Two Variable Filters Django
I have two filters in my code here, students filters everyone in that particular class and students_wr is another filter that quieres my table K8Recess which logs all the students in the school who got recess for that day. What I want to do is combine these filters. So show everyone in my class who got recess for the day . How do i do that ? Here is my Code def K8_Recess_Report(request, classid): if request.method == "GET": date = datetime.date.today() class_name = TeacherClass.objects.get(id=classid) getstudents = Student.objects.filter(class_name=classid) students = getstudents.all().order_by('student_name') students_wr = K8Recess.objects.filter(created_at__date = date ) my_class_id = request.session['my_class_id'] context = ({'students': students, 'class_name': class_name, 'my_class_id': my_class_id, 'date': date,}) return render(request, 'points/k8_recess_report.html', context)