Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
from rest_framework.filters import SearchFilter generates error as cannot import name 'ORDER_PATTERN' from 'django.db
I found out that the line from rest_framework.filters import SearchFilter generates me an error as from django.db.models.sql.constants import ORDER_PATTERN ImportError: cannot import name 'ORDER_PATTERN' from 'django.db.models.sql.constants' (E:\anaconda\envs\AHG_web\lib\site-packages\django\db\models\sql\constants.py) I used that as below: class op_ViewSet(viewsets.ModelViewSet) : # permission_classes = (permissions.IsAuthenticated,) queryset = Op.objects.all().filter() serializer_class = op_Serializer # authentication_classes = [TokenAuthentication , SessionAuthentication , BasicAuthentication] # pagination_class = PageNumberPagination # pagination_class = StandardResultsSetPagination filter_backends = [DjangoFilterBackend , SearchFilter] filter_class = op_filter ordering_fields = ['close_date' , ] ordering = ['close_date'] search_fields = ['website' , 'title' , 'description' , 'organization__name'] @action(detail=True , methods=['Get']) def attachments(self , request , pk) : op = self.get_object() links = Attachments.objects.filter(op_id=op.id) serializer = attachments_Serializer(links , many=True) return Response(serializer.data) previously it was working fine, can anyone help me with the solution. -
Looping through wagtail contents
I’m using wagtail to manage content in my Django app. In my model, I used a structured block like so: class SectionBlock(blocks.StructBlock): header = blocks.CharBlock() content = blocks.RichTextBlock() My page is expected to have multiple distinct headers like introduction, conclusion, etc however the template iteration keeps looping through the first header (introduction). The question is do I rename each item in my SectionBlock class so I can directly access it in the template or there is a simpler solution? class SectionBlock(blocks.StructBlock): header1 = blocks.CharBlock() content1 = blocks.RichTextBlock() header2 = blocks.CharBlock() content2 = blocks.RichTextBlock() {% for block in blocks %} {{ block.value.header1 }} {{ block.value.header2 }} {% endfor %} -
Django Graphene testing - Variable "$input" of required type "PostInput!" was not provided
I have a blog application with Django and Graphene. I'm trying to test a GraphQL mutation query that creates a Post with PostInput fields. When I test the said mutation with a hardcoded query, it works. However, when I use $input, I am facing an issue - Variable "$input" of required type "PostInput!" was not provided.. Here are my schema and test cases. schema.py ... User = get_user_model() # Types class PostType(DjangoObjectType): class Meta: model = Post ... # Input object types class PostInput(graphene.InputObjectType): title = graphene.String(required=True) publish_date = graphene.DateTime() author = graphene.ID(required=True) content = graphene.String(required=True) ... # Mutations class CreatePost(graphene.Mutation): class Arguments: input = PostInput() # Reponse ok = graphene.Boolean() post = graphene.Field(PostType) @classmethod def mutate(cls, root, info, input=None): post_instance = Post( title = input.title, author_id = input.author, content = input.content ) post_instance.save() ok = True return cls(ok=ok, post=post_instance) ... class Mutation: create_post = CreatePost.Field() ... test.py post_create_query = ''' mutation createPost($input: PostInput!) { createPost(input: $input) { ok post { title content } } } ''' class TestPostMutations(GraphQLTestCase): def setUp(self): self.client = Client(schema) self.user = User.objects.create( username = "testuser", password = "tE$tp@$$d0)", email = "test@example.net" ) def test_post_create(self): """ Querying postCreate should create post and return post instance and … -
One-to-many relationship in django models (Relation of one Model with another two Models)
I want to save all the likes in a Like Table. Likes of both Comments and Post, in one table. Is their something like this to achieve this thing: Class Post: ... Class Comment: ... Class Like(models.Model): '''Either of Post or Comment will have to be selected in this field''' post_or_comment = models.Something([Post, Comment], on_delete=models.CASCADE) -
How to display django generic detail view inside a modal with ajax
I want to display the content of an announcement inside a modal when a user clicked on the announcement list. This will be the trigger for the modal in my announcement_list.html: <form name="form" action="#" id="form_have_product_{{y.id}}" method="POST"> {% csrf_token %} <a href="#" id="{{ announcement.pk }}" type="button" class="btn btn-info view-announcement" data-url="{% url 'announcement-detail' pk=announcement.id %}" style="float: right;">View</a> </form> This is my function in my views.py: def get_announcement(request, pk): announcement = Announcement.objects.filter(announcement_id=pk) context = { 'title': announcement.title, 'about': announcement.about, 'author': announcement.author, 'post_date': announcement.post_date } return render(request, 'announcement-details-modal.html', context) For the urls.py: urlpatterns = [path('announcement/<int:pk>/', get_announcement, name='announcement-detail'),] And this is the function for when the user clicks on the announcement list: $(".view-announcement").on("click", function() { var target_url = $(this).attr("data-url"); var csrftoken = $("[name=csrfmiddlewaretoken]").val(); $.ajax({ url: target_url, headers:{ "X-CSRFToken": csrftoken }, success: function(data) { $("#modal").modal("toggle"); $("#modal-content").html(data); } }); }); Currently this code returns the server responded with a status of 500 (Internal Server Error) -
Django+JS: Can't track likes on posts. Bad request 400
Little background: I'm creating twitter like app from the tutorial on youtube. So, I am a beginner in django and just know syntax of JS. Several days ago, I faced the problem where likes of a post are not counting. I think the problem is with serializers or with my environment (django 2.2; python 3.8.5; using VS Code). my action handling view: import random from django.conf import settings from django.http import HttpResponse, Http404, JsonResponse from django.shortcuts import render, redirect from django.utils.http import is_safe_url from rest_framework.authentication import SessionAuthentication from rest_framework.decorators import api_view, authentication_classes, permission_classes from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from .forms import TweetForm from .models import Tweet from .serializers import TweetSerializer, TweetActionSerializer ALLOWED_HOSTS = settings.ALLOWED_HOSTS @api_view(['POST']) @permission_classes([IsAuthenticated]) def tweet_action_view(request, *args, **kwargs): ''' id is required. Action options are: like, unlike, retweet ''' serializer = TweetActionSerializer(data=request.data) if serializer.is_valid(raise_exception=True): data = serializer.validated_data tweet_id = data.get("id") action = data.get("action") content = data.get('content') qs = Tweet.objects.filter(id=tweet_id) if not qs.exists(): return Response({}, status=404) obj = qs.first() if action == "like": obj.likes.add(request.user) serializer = TweetSerializer(obj) return Response(serializer.data, status=200) elif action == "unlike": obj.likes.remove(request.user) elif action == "retweet": new_tweet = Tweet.objects.create( user=request.user, parent=obj, content = content) serializer = TweetSerializer(new_tweet) return Response(serializer.data, status=200) return Response({}, status=200) … -
How to write DateField in django models?
How to write DateField in django models ? without use auto_now_add & forms. class Education(models.Model): e_id=models.AutoField(primary_key=True) University=models.CharField(max_length=90) College_Name=models.CharField(max_length=90) Specialisation=models.CharField(max_length=10) From=models.DateField() To=models.DateField() doc_clinic = models.ForeignKey(to=DoctorProfile, related_name='educationdoctor_clinic', on_delete=models.CASCADE) def __str__(self): return (self.doc_clinic_id) -
Unable to import 'ali.book.models'
Where is the problem with this code that I can not import the Book class? this code in views and The class I want to import is in Models: from django.http import HttpResponse, Http404 from django.shortcuts import render from .book.models import Book def search(request): if 'q' in request.GET and request.GET['q']: q = request.GET['q'] book = Book.objects.filter(title__icontins=q) return render(request, 'search_results.html', {'book' : book, 'query' : q}) else : return HttpResponse('please submit a search term.') class Book: class Book(models.Model): title = models.CharField(max_length=100) authors = models.ManyToManyField(Author) publisher = models.ForeignKey(Publisher, on_delete = models.CASCADE) publication_date = models.DateField(null = True ,blank=True) def __str__(self): return self.title my package: ali/ ali/ views.py book/ models.py -
Onchange event in Django Forms?
I want to make a project which takes 4 documents from a user and I created a model, Model form, and a view. I want that when the user selects 1st field and tab to 2 fields means on change then it shows all validation error which is coming from the backend. Thanks -
what is the "complete" argument in Django and How can I use it?
I'm following a tutorial that works on a project and during he creates some code I see him use that: Order.objects.get_or_create(customer=customer, complete=False) I searched about "complete" argument on the internet but didn't find anything talking about that point, I actually don't know why he used this arg. also, I faced a problem and I didn't know what is that problem wants me to solve but I tried to add this argument in the get method in Django ORM, and when it placed this argument the error has gone. from here, why I should use this arg and when I have to use it? -
token verification fails although I sent correct token generated by view in django rest-frame work
Previously it was working fine and my token could be verified but,I don't know what happend , it returns me always as a token invalid. by using /register and email is sent for verification using these codes. view.py class RegisterView(generics.GenericAPIView) : serializer_class = RegisterSerializer renderer_classes = (UserRenderer ,) def post(self, request) : user = request.data serializer = self.serializer_class(data=user) serializer.is_valid(raise_exception=True) serializer.save() user_data = serializer.data user = User.objects.get(email=user_data['email']) token = RefreshToken.for_user(user).access_token current_site = get_current_site(request).domain relativeLink = reverse('email-verify') absurl = 'http://' + current_site + relativeLink + "?token=" + str(token) email_body = 'Hi ' + user.username + \ ' Use the link below to verify your email \n' + absurl data = { 'email_body' : email_body, 'to_email' : user.email, 'email_subject' : 'Verify your email' } Util.send_email(data) return Response(user_data , status=status.HTTP_201_CREATED) serializers.py class RegisterSerializer(serializers.ModelSerializer): password = serializers.CharField( max_length=68, min_length=6, write_only=True) default_error_messages = { 'username': 'The username should only contain alphanumeric characters'} class Meta: model = User fields = ['email', 'username', 'password'] def validate(self, attrs): email = attrs.get('email', '') username = attrs.get('username', '') if not username.isalnum(): raise serializers.ValidationError( self.default_error_messages) return attrs def create(self, validated_data): return User.objects.create_user(**validated_data) urls.py path('register/', RegisterView.as_view(), name="register"), utils.py from django.core.mail import EmailMessage import threading class EmailThread(threading.Thread): def __init__(self, email): self.email = email threading.Thread.__init__(self) … -
How to model by database for a one-to-many relationship
I am learning backend development in Django and came across this problem. Say I am designing a travel app: I have two databases USER and TRIP with one-to-many relationship. i.e., each user can have multiple trips and each trip can be taken by only one user. TRIP has a column trip-number. I would like to auto-increment this column for every row added into the TRIP database BUT the increment should be independent for each user starting from 1 TRIP table user trip-number 1 1 2 1 1 2 1 3 2 2 3 1 Something like that? I cannot auto-increment the whole column as it has to be unique for each trip taken by the user BUT the numbers can be same across different users. Ideally I prefer to this automatically on the server-end (sql) instead of writing a logic in the client. Any help would be appreciated. Thank you -
clone a Django model instance object and save it to the another model with same fields
obj = Foo.objects.get(pk=<some_existing_pk>) obj.pk = None obj.save() This method works if we are cloning objects to same model What to do if we have another model Foo2 Which is inherited from Fooconsisting of same fields of Foo I want to save obj to Foo2. Is there a shortcut to do this? -
Django: Why is it then when I put "readonly" in my input, the form becomes invalid and not submitted?
Django: Why is it then when I put "readonly" in my input, the form becomes invalid and not submitted? But when i remove the "readonly", everything works? I'm trying to make it such that users cannot edit those readonly fields. Also, after the form is submitted, I still want them to be able to view the form they have submitted but not be able to edit it. views.py @login_required(login_url=reverse_lazy("must_authenticate")) def submit_interest_view(request, slug): context = {} form = SubmitInterestForm() user = request.user blog_post = get_object_or_404(BlogPost, slug=slug) num_blogpost = BlogPost.objects.filter(author=user).count() if blog_post.author.email == user.email: return HttpResponse('You cannot submit interest to your own post.') #print(blog_post.author, user) interest_requests = Interest.objects.filter(interestsender=user, interestreceiver=blog_post.author, is_active=True, blog_post=blog_post) readonly = False if interest_requests.exists() and request.method=="POST": # This is where you could view the submitted form return HttpResponse('You have already submitted your interest to this post.') elif interest_requests.exists(): form = SubmitInterestForm(instance=interest_requests.first()) readonly=True if request.method == 'POST': # use request.method == 'POST' to submit POST request (like submitting a form) form = SubmitInterestForm(request.POST, request.FILES) if form.is_valid(): obj = form.save(commit=False) author = Account.objects.get(email=user.email) # use 'author = user.account' if there is OneToOne relation between user and account obj.author = author obj.blog_post = blog_post #interest_request = Interest.objects.get(interestsender=Account.user, interestreceiver=blog_post.author, is_active=True) #obj.interestsender=user #obj.interestreceiver=blog_post.author obj.interestsender = … -
Django Channels group send only sends the message to last channel
I'm working on django channels-3.0.3, the group_send only sends my message to the last connected channel to the connected users times. settings ... INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "chat", "channels", ] ASGI_APPLICATION = "cfehome.routing.application" CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [("127.0.0.1", 6379)], }, }, } chat/consumers.py import asyncio import json from django.contrib.auth import get_user_model from channels.consumer import AsyncConsumer from channels.db import database_sync_to_async from .models import Thread, ChatMessage class ChatConsumer(AsyncConsumer): @database_sync_to_async def get_thread(self, user, other_username): return Thread.objects.get_or_new(user, other_username)[0] async def websocket_connect(self, event): other_user = self.scope['url_route']['kwargs']['username'] me = self.scope['user'] # print("connect!") # print(me, other_user) thread_obj = await self.get_thread(me, other_user) # print(me, thread_obj) chat_room = f"thread_{thread_obj.id}" self.chat_room = chat_room await self.channel_layer.group_add( chat_room, self.channel_name ) print(f"{self.channel_name}, {self.chat_room}, {me} - connected!") await self.send({ "type": "websocket.accept" }) async def websocket_receive(self, event): print("msg recevied!", event) front_text = event.get("text", None) if front_text is not None: loaded_dic_Data = json.loads(front_text) msg = loaded_dic_Data.get("message") # print(msg) user = self.scope['user'] username = "default" if user.is_authenticated: username = user.username myResponse = { "message": msg, "username": username } # brodcast msg to chatroom await self.channel_layer.group_send( self.chat_room, { "type": "chat_message", "text": json.dumps(myResponse), } ) # sends the actual msg async def chat_message(self, event): await self.send({ "type": "websocket.send", … -
how i can set verbose name from pip module?
i using django-defender (pip install django-defender).this module contain "Access attempts" model. but it installed in virtuelenv.how i can to set verbose name to this models. -
django No module named 'project.settings' in separate directory(vscode)
Django version: 3.1.3 Python version: 3.8 My Project tree:\ Project: project settings.py mydirect(not app, a set of tool functions which called by my apps) myfunc.py my apps The django config in myfunc.py: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) if BASE_DIR not in sys.path: sys.path.append(BASE_DIR) os.environ.setdefault("DJANGO_SETTINGS_MODULE", 'project.settings') django.setup() My problem is that when I execute myfunc.py in vscode, it gives errors below: Traceback (most recent call last): File "d:/Desktop/project-dev/venv_idc_ops/dms/common/common.py", line 12, in <module> django.setup() File "D:\Desktop\project-dev\venv_idc_ops\lib\site-packages\django\__init__.py", line 19, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "D:\Desktop\project-dev\venv_idc_ops\lib\site-packages\django\conf\__init__.py", line 83, in __getattr__ self._setup(name) File "D:\Desktop\project-dev\venv_idc_ops\lib\site-packages\django\conf\__init__.py", line 70, in _setup self._wrapped = Settings(settings_module) File "D:\Desktop\project-dev\venv_idc_ops\lib\site-packages\django\conf\__init__.py", line 177, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "c:\program files\python36\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'project.settings' But when I run runserver, everything just goes well. That means that if I want to test myfunc.py, I must test it through the api instead of just executing 'run' in vscode Does anybody know what the problem is? It has confused my for a long time -
How do I fix my test case for a view in DRF?
I'm trying to write tests for my new app and this is the first time I try to so I'm running into many errors. This is my view: from rest_framework import generics, filters from todo import models from .serializers import TaskSerializer from django_filters.rest_framework import DjangoFilterBackend #lists, creates and filters tasks class ListTask(generics.ListCreateAPIView): queryset = models.Task.objects.all() serializer_class = TaskSerializer filter_backends = [DjangoFilterBackend, filters.SearchFilter] filterset_fields = ['date'] search_fields = ['description'] #allows to see detail of a task class DetailTask(generics.RetrieveUpdateDestroyAPIView): queryset = models.Task.objects.all() serializer_class = TaskSerializer I took a model from many tutorials to test that view and ended up with a very faulty code that looks like this: from django.test import TestCase from django.urls import reverse from rest_framework.test import APIRequestFactory from todo.views import ListTask, DetailTask class ListTaskViewTest(TestCase): def setUp(self): self.data = {'title':'Any title', 'description': 'Any description', 'Completed':False, 'date':'Any date'} self.factory = APIRequestFactory() def create_task(self, title='Read'): return Task.objects.create(title=title) def test_list_task(self, title='Read'): list_url = reverse('tasks-api:list') obj = self.create_task() request = self.factory.get(list_url) response = ListTaskAPIView.as_view()(request) self.assertEqual(response.status_code,200) class DetailTaskTest(TestCase): def setUp(self): self.data = {'title':'Any title', 'description': 'Any description', 'Completed':False, 'date':'Any date'} self.factory = APIRequestFactory() def test_retrieve_task(self): detail_url = reverse('tasks-api:detail', kwargs={'slug':obj.slug}) request = self.factory.get(detail_url) response = DetailTaskAPIView.as_view()(request, slug=obj.slug) self.assertEqual(response.status_code, 200) def test_update_task(self): obj = self.retrieve_task() update_url = … -
Django Multiple Form Processing in same View
I am looking for some assistance in two areas for django forms processing. I have a class view that overrides post and checks the name of the form in request.POST to determine which form has been submitted. based on the form submitted, I perform the appropriate actions for that form and save to the model. That part works correctly. I am not using a model form, just a custom html form created in the template with input fields. See the below view and html for reference. Is this the correct way to handle this or is there a best practice I should be following that makes use of model forms? Code seems a bit heavy to me and non-standardized, like there should be a better way... Being that I am not using model forms, the error processing has me a little confused. How do you handle error processing on a normal html form that does not make use of django model forms? See below in the view where notated # ERROR HANDLING FOR FORM NEEDED in code, specifically on the username field which is unique and validated on the model level. views.py class ProfileView(View): def get(self, request, *args, **kwargs): if … -
Django/Python: Filter for objects with two foreign keys and two attributes
get_messages returns messages shared between two users. def get_messages(self, sender, recipient): messages = Message.\ objects.\ filter(sender_id=sender.id, recipient_id=recipient.id) return messages This works fine, but sometimes User A will be the recipient instead of the sender or User B will the sender instead of the recipient. How can I use filter both ways more eloquently (without calling this function twice with the parameters switched)? -
can anyone find errors why the form fields is not showing in model from in djanog
Can anyone tell me why in my home page the for is not showing ,the model form to signup user , i make it using django UserCreationForm but home page it is not showing my views.py file def signup(request): if not request.user.is_authenticated: fm=signUpForm() if request.method == 'POST': fm = signUpForm(request.POST) if fm.is_valid(): fm.save() return redirect('home.html') else: fm = signUpForm() return render(request,"home.html" ,{'signupforms':fm}) home.html here i just use bootstrap model and display form to signup use using model in <div class="modal fade modelform" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header text-center "> <h5 class="modal-title text-dark" id="exampleModalLabel">Login using your credentials </h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <form action ='' method ='POST' > {% csrf_token %} <form action = '' method ='POST' novalidate > {% csrf_token %} {% for fm in signupforms %} <div class="form-group mt-0"> {{fm.label_tag}} {{fm}} <small class = 'text-danger'>{{fm.errors|striptags}}</small><br></div> {% endfor %} <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <input class="btn btn-primary my-3" type="submit" value="Submit"> </div> </form> </div> </div> </div> </div> forms.py where i create form and passing it to display from .models import loginForm from django.contrib.auth.forms import UserCreationForm # AuthenticationForm ,UsernameField create default form from django.contrib.auth.models import User … -
could not translate host name to "db" to address: Unknown host
I'm attempting to follow the guide provided by: https://docs.docker.com/compose/django/ Whenever I attempt to makemigrations, it gives me the Unknown host error given in the title. I'm trying to use PostgreSQL with Django and Wagtail as its CMS My docker-compose.yml looks like: version: "3.9" services: db: image: postgres environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db and my settings in the settings.py file look like: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'db', 'PORT': 5432, } } Am I missing anything? -
Django MYSQL Lite
I am trying to learn to write a program where i need to try and find the distance between 2 points using Django with MYSQL Lite. I have tried previous ones posted on this website, however, cannot find anything that works. Currently, my HTML is set up where a user would enter the postcode (Calendar.postcode), and i need it to measure the distance from a set point. Currently, i have a file with all postcodes and longitudes and latitudes like below: GB AL3 8QE Slip End England ENG Bedfordshire Central Bedfordshire E06000056 51.8479 -0.4474 6 GB AL5 3NG Harpenden England ENG Bedfordshire Central Bedfordshire E06000056 51.8321 -0.3829 6 GB AL5 3NS Hyde England ENG Bedfordshire Central Bedfordshire E06000056 51.8333 -0.3766 6 I would like the output to be on the main part of the website (rota.html) e.g. Distance is X miles/KM please can someone show me how this would be coded? thanks -
Django MariaDB-Galera Perfermance on K8s
I'm currently trying to find a good database solution for my app that runs on K8s at a "massive scale". So I started to experiment with MariaDB Galera without having any further experiences with it. I noticed that the write performance is quite slow. On a single instance MariaDB I can write 500 rows each with 7 field in about 2,75 Seconds (Single Table). Using Galera I need about 12-15 seconds for the same insert. Sometimes even more than 20 sec. Why that? Im running on High-End Hardware with NVMe drives, 10 Gbit Network and Epyc CPUs. Overhead should be small as everything run in Containers. Is this "issue" just the nature of Galera or is my config just faulty?! please see here: https://pastebin.com/mvb3Ndww I already experimented with query_cache_type and query_cache_size but without any real success so far ... My CSI is openebs-hostpath for maximum performance through a locally attached disk for each container/Pod. Thanks in advance -
Django | formfield_for_manytomany - name display in admin
I am just learning Django, please forgive any ignorance here. Here's my models.py: from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) admin = models.BooleanField("Admin Status") class Team(models.Model): name = models.CharField("Team Name", max_length=20, default="") admins = models.ManyToManyField(User, related_name="admins") members = models.ManyToManyField(User, related_name="members") Here's my admin.py from django.contrib import admin from .models import Team, Profile from django.contrib.auth.models import User class ProfileAdmin(admin.ModelAdmin): list_display = ('user', 'admin') admin.site.register(Profile, ProfileAdmin) class TeamAdmin(admin.ModelAdmin): list_display = ('name',) def formfield_for_manytomany(self, db_field, request, **kwargs): print(db_field) if db_field.name == "admins": kwargs["queryset"] = Profile.objects.filter(admin=True) return super(TeamAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs) admin.site.register(Team, TeamAdmin) This works perfect, but the admins on my admin page are showing as "Profile object (1)," "Profile object (2)," etc... What am I doing wrong? Or where do I change the way those display?