Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
My for loop does not work as expected - Data does not show up in my django template
I am trying to use a for loop in my Django template to show the data stored in the models of a table but for some reason , the data does not show up in the template. Views.py def add_part(request): parts = Parts.objects.all() context = { "parts": parts } return render(request, 'admintemplate/add_parts_template.html', context) def add_part_save(request): if request.method != "POST": messages.error(request, "Method Not Allowed!") return redirect('add_part') else: part_name = request.POST.get('part_name') part_type = request.POST.get('part_type') supplier_id = request.POST.get('suppliers') suppliers = Suppliers.objects.get(id=supplier_id) try: part = Parts(part_name=part_name, part_type=part_type, supplier_id=supplier) part.save() messages.success(request, "Part Added Successfully!") return redirect('add_part') except: messages.error(request, "Failed to Add Part!") return redirect('add_part') models.py The parts and the services model are exactly the same with different column names, so I think the functionality for both should be the same. Suppliers models class Suppliers(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=20) Parts model class Parts(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=20) part_type = models.CharField(max_length=20) supplier_id = models.ForeignKey(Suppliers, on_delete=models.CASCADE) Services model class Services(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=20) service_type = models.CharField(max_length=20) supplier_id = models.ForeignKey(Suppliers, on_delete=models.CASCADE) Part template {% extends 'admintemplate/base_template.html' %} {% block page_title %} Add Parts {% endblock page_title %} {% block main_content %} {% load static %} <section class="content"> <div class="container-fluid"> <div class="row"> <div … -
Django 3.2.3 I'm trying to serialize object with its fields and properties methods
I'm new to django framework, I simply want to return a model object with its attributes and properties back to an ajax call as a Json response. I have an Item model with a property balance which returns an integer value. Here is my code: models.py class Item(models.Model): entered_by = models.ForeignKey(User, on_delete=models.PROTECT) name = models.CharField(max_length=50, blank=True) @property def balance(self): return Stock.objects.filter(item_id=self.id).aggregate(Sum('quantity')).get('quantity__sum') class Stock(models.Model): item = models.ForeignKey(Item, on_delete=models.PROTECT) name = models.CharField(max_length=50, blank=True) quantity = models.PositiveIntegerField() serializers.py from rest_framework import serializers from .models import Item class ItemSerializer(serializers.ModelSerializer): balance = serializers.SerializerMethodField(source="get_balance") class Meta: model = Item fields = ('entered_by', 'name', 'balance') views.py from stocks.serializers import * from django.http import HttpResponse, JsonResponse def viewItem(request): if request.is_ajax and request.method == "GET": id = request.GET.get("item_id", None) item = Item.objects.get(id=id) if item: serializer = ItemSerializer() # return serializer.data return JsonResponse(serializer.data, status = 200) The output I'm seeking is a Json output like this: { name:"item name", entered_by: null, balance: 10, } Right now this is what I'm getting { entered_by: null name: "" } any thought will appreciated. -
Cloud Build Django: retry when error (collectstatic, ServiceUnavailable)
I'm building and deploying a Django app to Cloud Run with Google Cloud Build. All production migration and static file uploading are done with the same Cloud Build yaml file. However, when the step executes python manage.py collectstatic, an error occurred: google.api_core.exceptions.ServiceUnavailable: 503 DELETE [FILEPATH]: We encountered an internal error. Please try again. The official document doesn't give too much information. The storage is managed by django-storage. Is there any quick solution to retry the command if any error with cloud build? -
django how to display the todolist of the current user login
I wanna take this todoapp to the next level and display the current users todoitems aka (content). I already created a new table called todoitem with id,content,userid. The userid comes from AuthUser id. And it's showing error Cannot query "username": Must be "AuthUser" instance. here's my views.py from django.contrib.auth.decorators import login_required @login_required def todoView(request): all_todo_items = Todoitem.objects.filter(userid=request.user) return render(request, 'todoapp/home.html', {'all_items': all_todo_items}) urls.py urlpatterns = [ path('', TemplateView.as_view(template_name="todoapp/index.html")), path('home/', todoView), path('admin/', admin.site.urls), path('accounts/', include('allauth.urls')), ] index.html {% load socialaccount %} <html> <body> {% if user.is_authenticated %} <p>Welcome, {{ user.username }} !</p> {% else %} <h1>My Google Login Project</h1> <a href="{% provider_login_url 'google' %}">Login with Google</a> {% endif %} </body> <a href="/home/">Check your Todolist</a> </html> home.html {% load socialaccount %} <h1>Welcome, {{ user.username }} !</h1> <table> <tr> <th colspan="2">List of Todos</th> </tr> {% for todo_items in all_items %} <tr> <td>{{todo_items.id.content}}</td> </tr> {% endfor %} </table> -
Unable to makemigrations in Django
Problem statement: I am trying to create a new model in a new file - app1/models/model2.py I dont see any error when I try to makemigrations. But Django doesnt detect any changes. If I put the same code in my previous file app1/models/model1.py - makemigrations works. I have tried - python manage.py makemigrations app1 & python manage.py makemigrations My basic model: from django.db import models class Xyz(models.Model): name = models.CharField(max_length=100) I tried through pycharm & normal terminal. I am using UBuntu 20.04LTS. I deleted all migration files then reran makemigrations for app1 , it only picked old changes. did not pick new Xyz model. So perhaps there is something wrong in the way I am creating this new model2.py file. But I am creating it normally like model1.py. I even tried to copy paste and rename the same file. All my folder have init.py in them. -
Django: stop saving the same value in the database
my gorgeous friends on the internet. I have a problem with my Django app, implementing a function not to save the same value in the database. When I hit command + r on a Macbook Air, my app save the previous value in the form although the form was empty. If someone knows how to stop, please let me know. Here is the code below. @login_required def blog(request, pk): blog = get_object_or_404(Blog, pk=pk) comments = Comment.objects.order_by('-created').filter(blog=blog.id) number_of_comments = comments.count() if request.method == 'GET': form = CommentForm() elif request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.blog = blog comment.user = request.user comment.save() form = CommentForm() -
Assiging a css file located in static after deploying website
I have deployed a Django project using Apache2, everything is working fine except for weazyprint which creates PDF file for forms. The pdf was working fine in testing and local host. Now everytime I access the pdf it is showing this error: FileNotFoundError at /business_plan/businessplan/admin/info/2/pdf/ [Errno 2] No such file or directory: '/home/ahesham/Portfolio/static\\css\\report.css' I have tried to change the \ and adding it twice but it didn't work here is the views.py def admin_order_pdf(request, info_id): info = get_object_or_404(Info, id=info_id) html = render_to_string('businessplan/pdf.html', {'info': info}) response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'filename="order_{}.pdf"'.format( Info.id) weasyprint.HTML(string=html,base_url=request.build_absolute_uri()).write_pdf(response, stylesheets=[weasyprint.CSS(settings.STATICFILES_DIRS[0] + '\css\\report.css')], presentational_hints=True) return response The error is comming from this \css\\report.css knowing that the report.css file is in the static folder and all css and js of the deplyed site is working perfectly fine and I tried python manage.py collectstatic did not work My question: What am I doing wrong and how do I fix it? Please let me know if additional information required -
Why django migrate command don't insert to django_migrations table
There was a change in the DB and the Model was modified. After running Makemigrations, I ran migrate. The DB has been changed normally, but the history is not added to the django_migrations Table. Because of this problem, a warning to continue to migrate appears even after migrating. And when I try to migrate again, the history is not added to the django_migrations table, so I try to change the DB as before, and this is of course an error. This is migrations file. class Migration(migrations.Migration): dependencies = [ ('common_py', '0001_initial'), ] operations = [ migrations.AddField( model_name='customer_company', name='del_date', field=models.DateTimeField(default=None, null=True, verbose_name='삭제일'), ), ] Run command "python manage.py migrate" Result (venv) PS D:\Projects\AFF\AFF> python manage.py migrate Operations to perform: Apply all migrations: auth, common_py, contenttypes, sessions Running migrations: Applying common_py.0002_customer_company_del_date... OK Change Table Success But didn't add history to "django_migrations" Table Have you any idea? I Couldn't find any information about this. Thank you. -
Named url kwargs in authenticate method
I'm trying to create a custom authentication class in the Django rest framework. In the authenticate(self, request) method, at first glance, it seems that there is no way to get named kwarg from the URL. Is there a way to accomplish this? -
Non containerised Nginx not serving files from django docker container
I'm so close to solving this, it's actually painful, and so any help would be awesome. New to Django. New to Nginx. New to Docker. But love a challenge. Have a virtual server at DigitalOcean. Following a number of tutorials and reading endless documentation I've got the following, the problem is, nginx is serving the wesbite, but not the staticfiles. I'm sure it's something to do with my settings.py or nginx.conf, but can't tell what. settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "devops", "staticfiles") STATICFILES_DIRS = [ BASE_DIR / "static", ] MEDIA_URL = "/mediafiles/" MEDIA_ROOT = os.path.join(BASE_DIR, "devops", "mediafiles") docker-compose If I'm doing this correctly, I need to have my staticfiles outside of my container so that the standalone nginx can serve them. I'm doing it this way as I think I'm reading that it's easier to have LetsEncrypt and certbot set up with nginx outside of a container than inside. version: '3.7' services: web: image: <dockerimage> container_name: <name> command: gunicorn <site>.wsgi:application --bind 0.0.0.0:8000 --workers 5 volumes: - $HOME/devops/staticfiles:/home/app/web/staticfiles - $HOME/devops/mediafiles:/home/app/web/mediafiles ports: - 8000:8000 env_file: - .env.docker depends_on: - db labels: - com.centurylinklabs.watchtower.enable=true restart: "on-failure" db: image: index.docker.io/postgres:12.0-alpine container_name: db env_file: - .env.docker volumes: - postgres_data:/var/lib/postgresql/data/ restart: "on-failure" volumes: postgres_data: … -
Is there a way to use 'query' and 'forloop' together in Djang templates?
{% for game in game_query %} {% for i in game.data.participantIdentities %} {% if i.player.summonerName == summoners_result.name %} {% if i.participantId == game.participants.forloop.counter0.participantId %} {% if game.participants.forloop.counter0.stats.win == true%} win {% else %} false {% endif %} {% endif %} {% endif %} {% endfor %} {% endfor %} The game_query is json data with game data. The summoners_result.name is a user nickname. The problem is the game.participants.forloop.counter0.participantId Is there a way to use 'forloop counter' from 'for' with query? -
Django, Factory boy - can't create subfactory
I have created three factories where User and Profile are associated as onetoone field, also Label is sub factory of Profile. import factory from users.models import User, Label, Profile from .models import Release import random from django.db.models.signals import post_save @factory.django.mute_signals(post_save) class ProfileFactory(factory.django.DjangoModelFactory): class Meta: model = Profile user = factory.SubFactory("releases.factories.UserFactory", profile=None) @factory.django.mute_signals(post_save) class UserFactory(factory.django.DjangoModelFactory): class Meta: model = User email = factory.Faker("email") password = factory.Faker("password") profile = factory.RelatedFactory(ProfileFactory, factory_related_name='user') class LabelFactory(factory.django.DjangoModelFactory): profile = factory.SubFactory(ProfileFactory) name = factory.Faker("name") class Meta: model = Label but when I try to create a label (LabelFactory.create()) it throws the error RelatedObjectDoesNotExist: User has no profile. What is wrong? Please help! -
How to send data from django to Vue3 component
I am trying to send some data from django to a Vue3 component, but i can`t manage to send it to Vue. html code snippet {{object_list|json_script:"team_members"}} <script> const team_member_list = JSON.parse(document.getElementById('team_members').textContent); </script> <cardcarousel :team=team_member_list></cardcarousel> <script> console.log(team_member_list[0]['first_name'])0 </script>` My component app.component('cardcarousel', { data(){ return { } }, props:{ team:{ type: Array, required: true, } } , template:/*html*/` <div v-for="team_member in team" class="card_carousel"> <teamcard :first_name = "team_member.id"></teamcard> </div> `,})` In the console log i can see my Array, but from Vue i receive the following warning: [Vue warn]: Invalid prop: type check failed for prop "team". Expected Array, got Undefined. -
Django image not showing up in template (not URLs issue)
I've added the neccessary elements to the URLs.py. The image is NOT stored in the database. URLs.py from django.conf import settings from django.conf.urls.static import static ... ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) . I'm trying all of the following <link rel="apple-touch-icon" sizes="76x76" href="./assets/img/image.png"> <img src="static/storiesapp/img/image.png"> <img class='img-responsive' src="{{ MEDIA.URL }}{{ image.png }}" /> -
How do I change Django Index CSS?
I am working on a django web application and I am trying to change the background for my application. But the style for the whole project seems to be hardcoded in the (index) file and no matter what I do, I am unable to change it. Any idea how I would be able to change it? -
Deploying Django app to Heroku - 'ModuleNotFoundError: No module named 'storages'
I am trying to deploy a Django app to Heroku. I have deployed many times before, but now that I have added integration with S3, I am getting a collectstatic error. I am new to this and appreciate your help! The error when I do git push heroku main: remote: -----> $ python manage.py collectstatic --noinput remote: Traceback (most recent call last): remote: File "manage.py", line 22, in <module> remote: main() remote: File "manage.py", line 18, in main remote: execute_from_command_line(sys.argv) remote: File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line remote: utility.execute() remote: File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/__init__.py", line 377, in execute remote: django.setup() remote: File "/app/.heroku/python/lib/python3.8/site-packages/django/__init__.py", line 24, in setup remote: apps.populate(settings.INSTALLED_APPS) remote: File "/app/.heroku/python/lib/python3.8/site-packages/django/apps/registry.py", line 91, in populate remote: app_config = AppConfig.create(entry) remote: File "/app/.heroku/python/lib/python3.8/site-packages/django/apps/config.py", line 90, in create remote: module = import_module(entry) remote: File "/app/.heroku/python/lib/python3.8/importlib/__init__.py", line 127, in import_module remote: return _bootstrap._gcd_import(name[level:], package, level) remote: File "<frozen importlib._bootstrap>", line 1014, in _gcd_import remote: File "<frozen importlib._bootstrap>", line 991, in _find_and_load remote: File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked remote: ModuleNotFoundError: No module named 'storages' remote: remote: ! Error while running '$ python manage.py collectstatic --noinput'. My settings.py file: INSTALLED_APPS = [ ... 'django.contrib.staticfiles', 'storages', ] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' #mediaroot … -
Django Template Variable Failing as href Value
I have created a Django template which serves as an email template for my app. Upon certain actions, a celery task sends an email from this template using Sendgrid. Previously I hard-coded the URLs but now I need them to be dynamic. I am passing the url string as a variable called profile_url. I know that the URL is formatted correctly because I am printing it before calling the send_mail() function. If I use the value like so it works: <p>{{ profile_url }}</p> However, when I use it as an href value the link renders unclickable: <a href="{{ profile_url }}" target="_blank" style=" text-decoration: none; color: #ffffff; line-height: 40px; display: block; " >Go to your profile</a> If anyone can assist me or at least point me in the right direction here I'd greatly appreciate it! -
what can I do if django manage.py runserver is not working?
I am new to django and I use django 3.2. Whenever I run python manage.py with any other command. Like python manage.py runserver or python manage.py makemigrations i get this bulky error message. please what can i do.My server starts up immediately after I start the project withdjango-admin startproject dummy but a get the error message after working on my project. thank you Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.1776.0_x64__qbz5n2kfra8p0\lib\threading.py", line 973, in _bootstrap_inner self.run() File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.1776.0_x64__qbz5n2kfra8p0\lib\threading.py", line 910, in run self._target(*self._args, **self._kwargs) File "C:\Users\User\myenv\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\User\myenv\lib\site-packages\django\core\management\commands\runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "C:\Users\User\myenv\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\Users\User\myenv\lib\site-packages\django\core\management\__init__.py", line 375, in execute autoreload.check_errors(django.setup)() File "C:\Users\User\myenv\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\User\myenv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\User\myenv\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\User\myenv\lib\site-packages\django\apps\config.py", line 224, in create import_module(entry) File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.1776.0_x64__qbz5n2kfra8p0\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 972, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1030, … -
Django - How to display specific content in a template
Django newbie question - I need to display a specific entry in a template. So far I have not been able to get this to work. I have the following code: model: class BasicPage(models.Model): title = models.CharField(max_length=200) body = HTMLField() def __str__(self): return self.title view: class TermsPageView(TemplateView): model = BasicPage template_name = 'terms.html' def get_queryset(self): body = BasicPage.objects.filter(id=1) return body template: {% block content %} <h1>{{ body.title }}</h1> {% endblock content %} -
Profile Page for all Users blogs Django
everyone. I'm building a blog site and each user has a profile that should list their written blogs. But I'm finding it difficult to make a reference to individual users. My Views class ShowProfilePageView(LoginRequiredMixin, DetailView): model = UserProfile template_name= 'registration/user_profile.html' def get_context_data(self, *args, **kwargs): context = super(ShowProfilePageView, self).get_context_data(*args, **kwargs) page_user = get_object_or_404(UserProfile, id=self.kwargs['pk']) user = self.request.user user_posts = Post.objects.filter(author= user).order_by('-post_date') context['page_user'] = page_user context['user_posts'] = user_posts return context Note: The user, defined in the view above is self.request.user and this makes all the user profiles list out the blogs of the current logged in user instead of been based on particular users. Models The Post/Blog model class Post(models.Model): title = models.CharField(max_length=225) header_image = models.ImageField(blank= True, null=True, upload_to='images/header_image') author = models.ForeignKey(User, on_delete=models.CASCADE) body = RichTextField(blank=True, null=True) post_date = models.DateField(auto_now_add = True) category = models.CharField(max_length=225) snippet = models.CharField(max_length=70) UserProfile models The user profile models class UserProfile(models.Model): user = models.OneToOneField(User, null=True, on_delete = models.CASCADE) bio = models.TextField(max_length=160) profile_pic = models.ImageField(blank= True, null=True, upload_to='images/profile_pics') website_url = models.CharField(max_length=250, null = True, blank = True) twitter_url = models.CharField(max_length=250, null = True, blank = True) github_url = models.CharField(max_length=250, null = True, blank = True) linkedin_url = models.CharField(max_length=250, null = True, blank = True) dribble_url = models.CharField(max_length=250, null … -
What's the best way to return to the previous page after Post? (Not login)
After a user updates a record and hits the 'Post' button, what's the best way to redirect them to the previous page? I know there's a potential issue with using the HTTP_REFERER method however the user will be using not be using a browser with custom settings. This does not work (it only refreshes the page) def form_valid(self, form): form.instance.fk_user = self.request.user form.save() return HttpResponseRedirect(self.request.META.get('HTTP_REFERER')) def test_func(self): post = self.get_object() if self.request.user == post.fk_user: return True return False If I remove the 'self.' i recieve an error where 'name 'request' is not defined' -
What framework should I use for my project?
all the developers, I am a member of a programming team and we want to create a large scale web application that requires a lot of user interactions and databases. 3 members of our team have experience with python and C#, 2 members have with javascript(the one has python too). Which framework is better for this kind of web application? Which one will take less time to code? 1.Django 2.Flask 3.MERN stack 4.ASP.Net Thanks before :) -
Beanstalk cannot connect to rds instance
Im in a similar boat to the user on this question; Connecting the elastic beanstalk environment with existing RDS instance I have a Codestar project (Django via Beanstalk) and i cannot get the application to access any rds instances. When attempting to deploy during the testing step (python manage.py test) the following error message is thrown; django.db.utils.OperationalError: could not connect to server: Connection timed out Is the server running on host "172.31.44.126" and accepting TCP/IP connections on port 5432? Things ive already tried Running locally works fine via django and psql using ipaddress and public hostname (name.key.eu-west-2.rds.amazonaws.com) both work fine locally and provide the same error message when deploying Connecting to rds via the EC2 instance This works fine connecting via local ip and name. Queries such as \d and \l return fine indincating the instance can see the database. Changing vpc / subnets Both EC2 and rds instances are in the same vpc (only have one) and subnet (eu-west, availability group 2a) Spinning up an attached beanstalk rds instance I have tried dedicated rds instances and a connected instance using the EBS tool and the application has been unable to connect to either. Settings.py if 'RDS_DB_NAME' in os.environ: DATABASES … -
Django Nested Serializer
I am pretty new to DRF/Django and want to create an endpoint that returns nested json from multiple models in the format: { "site": { "uuid": "99cba2b8-ddb0-11eb-bd58-237a8c3c3fe6", "domain_name": "hello.org" }, "status": "live", "configuration": { "secrets": [ { "name": "SEGMENT_KEY", # Configuration.name "value": [...] # Configuration.value }, { "name": "CONFIG_KEY", "value": [...] }, "admin_settings": { 'tier'='trail', 'subscription_ends'='some date', 'features'=[] } Here are the models: class Site(models.Model): uuid = models.UUIDField( default=uuid.uuid4, editable=False, unique=True) domain_name = models.CharField(max_length=255, unique=True) created = models.DateTimeField(editable=False, auto_now_add=True) modified = models.DateTimeField(editable=False, auto_now=True) class AdminConfiguration(models.Model): TRIAL = 'trial' PRO = 'pro' TIERS = [ (TRIAL, 'Trial'), (PRO, 'Professional'), ] site = models.OneToOneField( Site, null=False, blank=False, on_delete=models.CASCADE) tier = models.CharField( max_length=255, choices=TIERS, default=TRIAL) subscription_ends = models.DateTimeField( default=set_default_expiration) features = models.JSONField(default=list) class Configuration(models.Model): CSS = 'css' SECRET = 'secret' TYPES = [ (CSS, 'css'), (SECRET, 'secret') ] LIVE = 'live' DRAFT = 'draft' STATUSES = [ (LIVE, 'Live'), (DRAFT, 'Draft'), ] site = models.ForeignKey(Site, on_delete=models.CASCADE) name = models.CharField(max_length=255, blank=False) type = models.CharField( max_length=255, choices=TYPES) value = models.JSONField( null=True) status = models.CharField( max_length=20, choices=STATUSES) Logic behind serializer/viewset to achieve mentioned json: retrieves lookup_field: uuid filters query param: Configuration.status (either live or draft filters AdminConfiguration on site id (something like AdminConfiguration.objects.get(Site.objects.get(uuid)) filters Configuration on … -
ManyToManyField does not show
Want to use REST API to populate my tables but my field does not display on the API page. Models (Series, Roster): class Series(models.Model): (...) def __str__(self): return self.title class Roster(models.Model): (...) series = models.ManyToManyField(Series) (...) def __str__(self): return self.name Serializers: class SeriesSerializer(serializers.ModelSerializer): class Meta: model = Series fields = ('id', 'title', 'icon') read_only_fields = ('slug',) class RosterSerializer(serializers.ModelSerializer): series = SeriesSerializer(many=True, read_only=True) class Meta: model = Roster fields = ('id', 'name', 'number', 'primary_color', 'secondary_color', 'image', 'series') Views: class SeriesView(viewsets.ModelViewSet): serializer_class = SeriesSerializer queryset = Series.objects.all() class RosterView(viewsets.ModelViewSet): serializer_class = RosterSerializer queryset = Roster.objects.all() Unsure where I am mistepping here.