Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Comments under Post
I created model Post and Comment, now I want to display comments from Post but I have a problem. In tutorial there is a line of code in html {% for comment in post.comments.all %} but isn't working in my app. If I set {% for comment in comments %} it works but displays all comments from models (I want only comments from the post). How to fix that? Below I pasted my code. models.py from django.db import models class Post(models.Model): title = models.CharField(max_length=64, blank=False, null=False) short_text = models.TextField(blank=False, null=False) text = models.TextField(blank=False, null=False) image = models.TextField(blank=False, null=False) date = models.DateTimeField(auto_now_add=True, blank=True) views = models.IntegerField(default=0) class Comment(models.Model): post = models.ForeignKey('main.Post', on_delete=models.CASCADE) author = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(auto_now_add=True, blank=True) approved_comment = models.BooleanField(default=False) def approve(self): self.approved_comment = True self.save() def __str__(self): return self.text views.py from django.shortcuts import get_object_or_404, render, redirect from .models import Post, Comment def index_pl(request): posts = Post.objects.all() return render(request, 'index_pl.html', {'posts': posts}) def single_article_pl(request, id): posts = get_object_or_404(Post, pk=id) posts.views = posts.views + 1 posts.save() comments = Comment.objects.all() return render(request, 'single_article_pl.html', {'posts': posts, 'comments': comments}) html {% for comment in post.comments.all %} <div class="comment"> <div class="date">{{ comment.created_date }}</div> <strong>{{ comment.author }}</strong> <p>{{ comment.text|linebreaks }}</p> </div> {% … -
celery beat and worker doesn't work as expected
I want to make two functions that update and show a global list named websites, and execute them by celery. To initialize websites, I made a file named config.py: # config.py # I have to declare global variables outside of the init(), # otherwise Django doesn't recognize these global variables outside of the `config.py` global websites global flag flag = True # this method should be executed just One time!!! def init(): global flag flag = False global websites websites = [] print("===========IN Config.init()==========") I made two functions to be executed, check_list() executes every 2 seconds and initializes and shows the websites content, and update_list() executes every 10 seconds and add some elements to websites. Here is my tasks.py: (I made some prints in order to make the finding bug process easy.) # tasks.py from celery import shared_task from .celeryapp import app from . import config @shared_task def check_list(): try: print("config.flag First : " + str(config.flag)) if config.flag: config.init() print("This should be seen one tiiiiiiiiiiiiiiiiiiiiime") print("config.websites check_list : ===> " + str(config.websites)) except Exception as e: print(e) @shared_task def update_list(): try: print("config.flag First : " + str(config.flag)) if config.flag: config.init() print("This should be seen one tiiiiiiiiiiiiiiiiiiiiime") urls = ['first', 'second', … -
How can i redirect to the same page when a function executed Django
I have a like function in views.py and whenever the function executes i want to return the user to the same page he/she was. what should i write in return of my function? -
ModelForm not rendering to page?
This is a strange one for me because this is not the only ModelForm I have in this project and the other one is perfectly fine. Could someone have a look and see why the 'bid_input' input field for my form is not showing up on the page? My views.py admittedly isn't quite complete and functioning the way I want it to but I was at least expecting the input box to show but only the 'Place Bid' is showing. models.py class Bid(models.Model): bidder = models.ForeignKey(User, on_delete=models.CASCADE, related_name="bidders") item = models.ManyToManyField(Listing, related_name="bid_item", default=None, blank=True) bid_input = models.DecimalField(max_digits=9, decimal_places=2, default=None) time = models.TimeField() forms.py class BiddingForm(forms.ModelForm): class Meta: model = Bid fields = ["bid_input"] widgets = { "bid_input": forms.NumberInput(attrs={'autocomplete':'off'}) } urls.py path("listing/<int:id>/bid", views.bidding, name="bidding") views.py def bidding(request, id): listing = get_object_or_404(Listing, id=id) if request.method == "POST": form = BiddingForm(request.POST or None) if form.is_valid(): newbid = form.save(commit=False) newbid.bidder = request.user newbid.item = listing newbid.time = timezone.now() bid = newbid.save() return redirect("listing", bid_id=newbid.id) else: return render(request, "auctions/listingPage.html", { "form": form}) else: form = BiddingForm() return render(request, "auctions/listingPage.html", { "form": form }) listingPage.html {% extends "auctions/layout.html" %} {% block body %} <div> <form action="{% url 'bidding' listing.id %}" method="POST" name="bid_input"> {% csrf_token %} {{ … -
Combine two querysets, common field with different values
I search in a model "ConsultantProfile", the relevance is represented by a field called "rank" in "queryset1". I Also search in related models and gather "ConsultantProfile" objects from that related models in "queryset2" and set rank manually "0.7" for them so i can union query sets. When i want to combine and merge queryset1 and queryset2, common objects have different rank values. The problem is in final "queryset" the "rank" field's value is a value of rank from first queryset and i can't choose the highest value for "rank" queryset1 = qs.filter(active=True).annotate( rank=SearchRank( vector, query, normalization=Value(2).bitor(Value(4)), ) ) ids: some "ConsultantProfile" objects ids queryset2 = ConsultantProfile.objects.filter(id__in=ids, active=True).annotate(rank=Value(5, FloatField())) queryset = queryset1 | queryset2 Failed solution I tried to solve the problem by iterate over both query sets and union manually but no thing changed! queryset = queryset1.none() for obj in queryset1: qs2_object_qs = queryset2.filter(id=obj.id) # object presents in queryset2 if qs2_object_qs.exists(): # obj from queryset1 has better rank than queryset2 obj if obj.rank >= qs2_object_qs.first().rank:k) queryset |= queryset1.filter(id=obj.id) queryset2 = queryset2.exclude(id=obj.id) else: queryset |= qs2_object_qs # object does not present in queryset2 else: queryset |= queryset1.filter(id=obj.id) for obj in queryset2: qs_object_qs = queryset.filter(id=obj.id) # object presents in queryset if qs_object_qs.exists(): … -
how to add initial value to Django IntegerField?
I want to add 20000 gift credit as a coustmer is created without using init function or calssMethod class Customer(models.Model): balance = models.PositiveIntegerField(null=True) -
JSONField doesn't allow null in Django 3.1
I'm trying to use a JSONField in Django, sometimes I need it be null so I defined it with null=True, blank=True, but when I'm validating with the Serializer I'm getting my_data: [This field can't be null]. Here is my code: models.py class MyModel(models.Model): my_data = models.JSONField('data', null=True, blank=True, editable=False) serializer.py class MyModelSerializer(serializers.ModelSerializer): my_data = serializers.JSONField() class Meta: model = MyModel fields = '__all__' view.py def save_my_data(self, request) info['my_data'] = None serializer = serializers.MyModelSerializer(data=info) # validate the data print( serializer.is_valid() ) #returns False print( serializer.errors ) #returns my_data: [This field can't be null] Any suggestions about this? Thanks in advance. -
While Uploading your Django Project to Cpanel Should we also include the Venv?
I had created a small django project. Now I need to upload it on my domain. While uploading should I include the Venv in it or not. These are the files: ``-Encrypt(folder) -.idea -fast(project) -decrypt(app) -fast -pages(app) -utils -db.sqlite3 -manage.py -venv -
How to Bulk update records in Django?
I have multiple fields in my database and I want to update all records on submit button, Please let me know how i can do it. Here is my models.py file... class Product(models.Model): name=models.CharField(default=None) type=models.CharField(default=None) father=models.CharField(default=None) model1=models.Foreignkey(Category, related_name='cat_product', on_delete=models.CASCADE) here is my views.py file... def display_data(request, id): test_display = Product.objects.all() context = { 'test_display': test_display } return render(request, 'page.html', context) here is my page.html file... <form method="POST" action={% url 'back:formupdate' %} {% csrf_token %} {% for test in test_display %} <p>{{ test.name }}</p> <p>{{ test.type }}</p> <p>{{ test.phone }}</p> <p><input type="text" name="father" value="{{test.father}}"></p> <p>{{ test.model1 }}</p> <button class='btn btn-success'>Update Record</button> {% endfor %} I want to update father record in all fields, I want to update bulk records... I want to update this record in all my database entries.... -
Python django.How to output a variable?
Js: <script> var interval function callAjax(){ $.ajax({ type: "GET", url: "../row_han_two", data: { 'id_group': $("#id_group").val(), }, cache : false, success: function(data){ rot_message = data interval = setTimeout(callAjax, 1000); } }); } callAjax() </script> views: from django.shortcuts import render from django.contrib.auth.models import User,Group from django.contrib.auth import models from create_group_handler.models import Parameters_User from django.contrib.auth.decorators import login_required from create_group_handler.models import UserProfile from django.http import HttpResponse, HttpResponseRedirect from rot.models import Rot_model from django.http import JsonResponse import time @login_required def row_han_two(request): rot_message = Rot_model.objects.filter(id_chat = request.GET['id_group']) return HttpResponse(rot_message) Please tell me how you can display the chat_message variable in html like this: {% for object in rot_message%} <div class="row"> <div class="col-xl-3 block_messeage"> <span class="span_block_messeage">{{object.name_author}} ,{{object.time_message}}</span> <br> {{object.text_message }} </div> </div> {% endfor %} Lorem, ipsum dolor sit amet, conctetur adipisicing elit. Амет, веритатис. Eveniet culpa eaque quisquam ducimus ut ratione quae ex reiciendis, rerum vel, Lorem, ipsum dolor sit amet, conctetur adipisicing elit. Амет, веритатис. Eveniet culpa eaque quisquam ducimus ut ratione quae ex reiciendis, rerum vel, Lorem, ipsum dolor sit amet, conctetur adipisicing elit. Амет, веритатис. Eveniet culpa eaque quisquam ducimus ut ratione quae ex reiciendis, rerum vel, -
Strange API response in DRF - works on server run, empties on reload
I'm trying to create a serializer and a view returning the amount of objects for two models : class Lieu(models.Model): nom = models.CharField(max_length=30, blank=False) adresse = models.CharField(max_length=200, blank=False) code = models.CharField(max_length=6, blank=False) ville = models.CharField(max_length=20, blank=False) pluscode = models.CharField(max_length=20, blank=False) class Meta: verbose_name_plural = "lieux" def __str__(self): return f'{self.nom} - {self.ville}' class Artiste(models.Model): nom = models.CharField(max_length=40, blank=False) type_artiste = models.CharField(max_length=20, blank=False) pays_origine = models.CharField(max_length=20, blank=False) ville_origine = models.CharField(max_length=20, blank=True) bio = models.TextField(blank=True) def __str__(self): return self.nom The result I expect is something like that : [ { "lieux_count": 3, "artistes_count": 2 } ] Here is the methodfield base serializer in serializers.py : from rest_framework import serializers from datamidi.models import Artiste, Lieu class AllStats(serializers.Serializer): lieux_count = serializers.SerializerMethodField('get_artistes_count') artistes_count = serializers.SerializerMethodField('get_lieux_count') class Meta: fields = ['lieux_count', 'artistes_count'] read_only_fields = [ 'lieux_count', 'artistes_count'] def get_artistes_count(self, obj): return Artiste.objects.all().count() def get_lieux_count(self, obj): return Lieu.objects.all().count() And here is the view : from itertools import chain from datamidi.models import Artiste, Lieu class AllStatsView(generics.ListCreateAPIView): aquery = Artiste.objects.all() lquery = Lieu.objects.all() queryset = chain(aquery, lquery) serializer_class = AllStats permission_classes = [IsAdminUserOrReadOnly] The result is quite strange, two problems When doing a run server, the values returned at http://127.0.0.1:8000/api/allstats/ are correct, but iterated as many times as the total … -
make django forgot password forms in the same page
django has 4 views for forgetting the password i want to use those views in one template so that the user don't have to go to a different URL to reset his password or type his email to send the link of resetting the password i think i just need 2 views which are the form views, first is "PasswordResetView" and the other is "PasswordResetConfirmView" the other two are views that renders templates telling the user that the email is sent successfully or the password has been reset , i don't need them i'll be replacing them with toasts i thought of copy pasting the source code of those views in my views.py but is there a more proper way to do that? for now this is how i'm rendring them each one in a diffrent path and template path('password_reset/', auth_views.PasswordResetView.as_view(template_name="main/password_reset.html",form_class=UserPasswordResetForm),name="reset_password"), path('password_reset_sent/', auth_views.PasswordResetDoneView.as_view(template_name="main/password_reset_sent.html"),name="password_reset_done"), path('reset_password/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name="main/reset_password.html",form_class=UserSetPasswordForm),name="password_reset_confirm"), path('reset_password_complete/', auth_views.PasswordResetCompleteView.as_view(template_name="main/reset_password_complete.html"),name="password_reset_complete"), -
Docker-Compose container continuosly exits with error code 247
I'm currently trying to create a Django web server using Docker. When I run the Django webserver locally, by using python manage.py runserver 0.0.0.0:8000, everything works fine. This problem occurs when running the server using docker-compose up. The container starts and dis "Watching for file changes with StatReloader" message than hangs up there for a minute or two then exits. I've tried adjusting the amount of RAM and CPU cores available to docker and that hasn't fixed the problem. Any ideas on what could be causing this and how to fix it? -
Error when working with PasswordChangeView
Please help me to solve one problem. I want to change my login, mail and password on one page. I was able to implement a change of login and mail, but I could not push the change of password there, I get an error( __init__() got an unexpected keyword argument 'user' file views.py: from django.contrib.auth.views import PasswordChangeView from .forms import ProfileUpdateForm from django.contrib.auth.forms import PasswordChangeForm class ProfilePage(UpdateView, PasswordChangeView): model=Profile template_name="market/profile.html" second_form_class=ProfileUpdateForm third_form_class=PasswordChangeForm def get_success_url(self): obj=Profile.objects.get(user__username=self.object) return reverse_lazy('profile',kwargs={'slug': obj.slug},) def get_context_data(self, **kwargs): ctx = super(ProfilePage,self).get_context_data(**kwargs) ctx['PasswordChangeForm'] = self.third_form_class( prefix='PasswordChangeForm', # data = self.request.POST if 'PasswordChangeForm-submit' in self.request.POST else None, # files = self.request.FILES if 'PasswordChangeForm-submit' in self.request.POST else None, instance=self.request.user.profile, ) ctx['ProfileUpdateForm'] = self.second_form_class( prefix='ProfileUpdateForm', data = self.request.POST if 'ProfileUpdateForm-submit' in self.request.POST else None, files = self.request.FILES if 'ProfileUpdateForm-submit' in self.request.POST else None, instance=self.request.user, ) return ctx def get_form_kwargs(self): kwargs = super().get_form_kwargs() kwargs['user'] = self.request.user return kwargs -
How to add column in django user table and access it directly from admin page?
I have seen many answers to this question but none worked out. class userLogin(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) isManager = models.BooleanField(default=True) I have executed the commands python manage.py migrate and python manage.py makemigrations. The commands were executed successfully. I got an ok and change log in the terminal. If I click on add user on the admin page I can not see the field isManager w.r.t the user. I have triend adding AUTH_USER_MODEL = 'app.userLogin' in settings.py. -
Django: NotImplementedError: aggregate() + distinct(fields) not implemented
I have a table called reviews. In the reviews a person can leave multiple reviews for a service. A review can have a total score. I am trying to get the average of the total scores for the distinct reviews. Here is what I have: reviews = Review.objects.distinct('pairing').aggregate(Avg('total_score')); I keep getting this error: NotImplementedError: aggregate() + distinct(fields) not implemented. Could someone help me? I am fairly new to Django and have no clue why I am getting this. Thanks! -
How to generate UUID paths in views.py in Django?
I would like to create an object in views.py with an ID using UUID and then enter its specific path directly from the views file where I have create it. The error that I get is: TypeError at /item/create_item _reverse_with_prefix() argument after * must be an iterable, not UUID So I wonder whether anyone knows a way how this could be done? models.py: class Item(models.Model): id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=100, blank=True) views.py def create_item(request): context = {} if request.method == 'POST': name = request.POST['name'] item = Item(name=name) item.save() return HttpResponsePermanentRedirect(reverse('item', args=(item.id))) return render(request, 'items/item.html', context) def item(request, pk): item = get_object_or_404(Item, pk=pk) #Code to be written -
Django modelformset how to redirect if the instances already exist
I am using a modelformset_factory to create multiple instances. Now when the user goes back to the page and the existing instances populate the forms, if the user clicks on submit, the error shows up that the instances already exist triggered by a unique_together constraint. formset_errors [{'__all__': ['course with this instructor, location, program already exists.']}, {'__all__': ['course with this instructor, location, program already exists.']}, {}] I'd like to redirect the user to a listview to display those instances and set a message that we did not create the instances as they already are in the database. How do I do that? Right now, I am using the following which is not the best: redirect_already_exists = True for form_error in formset_errors: # list of dictionaries if form_error.get('__all__'): error_message = form_error['__all__'][0] if 'already exists' not in error_message: redirect_already_exists = False if redirect_already_exists: redirect_page = reverse('course:list_courses', args = (program_id,)) return HttpResponseRedirect(redirect_page) -
Django UnicodeDecodeError While inserting arabic letters
i'm trying to input Arabic letters while using django command python manage.py createsuperuser and it gives me always this error, what should i do to solve this? Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/mohammed/PycharmProjects/PatientStatus/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/mohammed/PycharmProjects/PatientStatus/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/mohammed/PycharmProjects/PatientStatus/venv/lib/python3.8/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/home/mohammed/PycharmProjects/PatientStatus/venv/lib/python3.8/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 61, in execute return super().execute(*args, **options) File "/home/mohammed/PycharmProjects/PatientStatus/venv/lib/python3.8/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/home/mohammed/PycharmProjects/PatientStatus/venv/lib/python3.8/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 111, in handle input_value = self.get_input_data(field, message) File "/home/mohammed/PycharmProjects/PatientStatus/venv/lib/python3.8/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 176, in get_input_data raw_value = input(message) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xd8 in position 4: invalid continuation byte -
Enforce that only certain attributes can be changed using a PUT request in Django
I want to make it so a user is able to update only certain attributes with a PUT request in my Django Rest API. As an example, if I had the following model and only wanted the user to be able to update their first and last name, how would I go about doing this? models.py: class User(models.Model): email = models.EmailField('email address', unique = True) first_name = models.TextField(max_length = 10) last_name = models.TextField(max_length = 20) (noting that they should not be able to change the 'id' field either which is automatically set) serializers.py: class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['id', 'email', 'first_name', 'last_name'] views.py: class SingleUser(APIView): def put(self, request, user_id): user = User.objects.get(pk = user_id) serializer = UserEditSerializer(user, data = request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status = status.HTTP_200_OK) return Response(serializer.errors, status = status.HTTP_400_BAD_REQUEST) What is the best way to enforce that users can only change a subset of these attributes? Thanks, Grae -
Error during template rendering / Could not parse some characters
Im trying to get a bio info for each profile, when running server and going to accounts/profile y find this error: Could not parse some characters: |% with website=profile.website| | default:"" % {% extends 'base.html' %} {% block title %}Profile{% endblock %} {% block content %} <h1> {{ user.get_null_name }} (@{{ user.username }}) </h1> {% with profile=user.profile %} {% if profile %} <h2> {{ profile.persona }} </h2> <div> {{ profile.bio|default:"" }} </div> <div> {{ % with website=profile.website | default:"" % }} <a href="{{website}}">{{website}} </a> {% endwith %} </div> <br/> <div> Interest: {% for Interest in profile.interest.all %} <span> {{ interest.name }}{% if not forloop.last %}, {% endif %} </span> {% endfor %} </div> {% endif %} {% endwith %} {% endblock %} -
Invalid block tag on line 1: 'extends"base.html"'. Did you forget to register or load this tag?
I search the solution in internet and I found similar issue but those solution didn't match. {% extends "base.html" %} {% block title %}User Login{% endblock title %} {% block content %} <h1>Login</h1> <form method="post" action="{% url 'Login:user_login' %}"> {% csrf_token %} <label for="username">Username:</label> <input type="text" name="username" placeholder="Enter Username"> <label for="password">Password:</label> <input type="password" name="password"> <input type="submit" name="" value="Login"> </form> {% endblock content %} -
How to upvote or downvote a post on Django [closed]
I have a blog system, very simple one. I want users to be able to upvote and downvote posts. How to do it ? Like the youtube system, click on "like" or "dislike" Thank you -
Issue with vine.five in Django
I'm running on Ubuntu a Django project that started running on Windows. I've installed a venv with python3.6 and with the same requirements with pip. Installed the vine 1.3 version as many posts told to do. No broken requirements found. Same error: ModuleNotFoundError: No module named 'vine.five' Tried other python versions too. This is the exception: SyntaxError: invalid syntax (venv3.6.0) (venv3.6.0)codea@codea-Inspiron-5570:~/Workspace$ sudo python3 manage.py migrate Traceback (most recent call last): File "/usr/local/lib/python3.6/dist-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.6/dist-packages/django/core/management/base.py", line 361, in execute self.check() File "/usr/local/lib/python3.6/dist-packages/django/core/management/base.py", line 390, in check include_deployment_checks=include_deployment_checks, File "/usr/local/lib/python3.6/dist-packages/django/core/management/commands/migrate.py", line 64, in _run_checks issues = run_checks(tags=[Tags.database]) File "/usr/local/lib/python3.6/dist-packages/django/core/checks/registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "/usr/local/lib/python3.6/dist-packages/django/core/checks/database.py", line 9, in check_database_backends for conn in connections.all(): File "/usr/local/lib/python3.6/dist-packages/django/db/utils.py", line 216, in all return [self[alias] for alias in self] File "/usr/local/lib/python3.6/dist-packages/django/db/utils.py", line 213, in __iter__ return iter(self.databases) File "/usr/local/lib/python3.6/dist-packages/django/utils/functional.py", line 80, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/usr/local/lib/python3.6/dist-packages/django/db/utils.py", line 147, in databases self._databases = settings.DATABASES File "/usr/local/lib/python3.6/dist-packages/django/conf/__init__.py", line 79, in __getattr__ self._setup(name) File "/usr/local/lib/python3.6/dist-packages/django/conf/__init__.py", line 66, in _setup self._wrapped = Settings(settings_module) File "/usr/local/lib/python3.6/dist-packages/django/conf/__init__.py", line 157, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, … -
Django Combining Multiple Filters for ManytoMany Choice
I'm trying to filter a ManyToMany field in a form on Django so that it only includes choices for the current user logged in users associated to the logged in user (parent and children) forms.py class LessonsForm(forms.ModelForm): class Meta: model = models.Lessons fields = ['type_of_lesson','attendees','max_capacity','teacher','date_of_lesson','time_of_lesson'] class LessonAddForm(forms.ModelForm): def __init__(self, user, *args, **kwargs): super(LessonAddForm, self).__init__(*args, **kwargs) self.fields['attendees'].queryset = CustomUser.objects.filter(username=user) class Meta: model = models.Lessons fields = ['attendees'] Models.py class CustomUser(AbstractUser): date_of_birth = models.DateField() is_parent = models.BooleanField(verbose_name="Parent") children = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True) REQUIRED_FIELDS = ['date_of_birth', 'is_parent','email',] class Lessons(models.Model): type_of_lesson = models.CharField("Lesson Type", max_length=128) attendees = models.ManyToManyField(settings.AUTH_USER_MODEL,related_name="attendee_users") max_capacity = models.IntegerField() teacher = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,related_name="teaching_user",limit_choices_to={'is_staff': True}) date_of_lesson = models.DateField() time_of_lesson = models.TimeField() date_added = models.DateField(auto_now_add = True) the line below is where I am struggling, this brings back the current user but I am also trying to have the 'children' connect to the user also appear in the attendees choices. self.fields['attendees'].queryset = CustomUser.objects.filter(username=user) I have tried a few methods below is an example but I can't seem to figure how how to combine two filters self.fields['attendees'].queryset = CustomUser.objects.filter(username=user,user.children)