Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Make a get request with a multiple value param in django requests Module?
I have a webservice that give doc list. I call this webservice via get_doc_list. but when I pass 2 values to id__in, it return one mapping object. def get_doc_list(self, id__in): config = self.configurer.doc params = { "id__in": id__in, } response = self._make_request( token=self.access_token, method='get', proxies=self.proxies, url=config.service_url, params=params, module_name=self.module_name, finalize_response=False ) return response How can I fix it?! -
Automatic deployment of my django website after making changes
i have deployed my Django portfolio using nginx server.but now i want a feature in which i make changes to my Github repo and then it will get automatic deployed to my nginx server. how can i do this?. thankyou -
Add Serial Number on Django Form [closed]
I want to add serial no on the top of body with auto increment after submit form -
Django Return Queryset from Database table by filtering using Dictionary values
My goal is to return rows from the books table using values sent by a user through a search form. The search form contains multiple fields author, ISBN and title. NB: In the code, the author field is a char, but converted to ID based on authors name due to foreign key relation. In this code, there's a get request converted to Dictionary and transformed to allow it to query data from the books table. def search(request): form = BooksForm() if request.method == 'GET': # convert get request to dictionary book_search = dict(request.GET) print("data before cleaning", book_search) #get the name from the dictionary get request author_name =request.GET['author'] #get the author id from the author table author = Author.objects.filter(full_name__contains=author_name).values() #get author_id from author queryset author_id = author[0]['id'] #update the dict with the author id to allow search in books models (foreing key) book_search['author'] = author_id print("data after cleaning",book_search) result_set = Book.objects.filter(**book_search) print("book search queryset",result_set) Problem: When I query the books table using the dictionary it returns an empty query set and I want it to return books from in table. Does anyone have an idea of how I can make the code work? -
Build a custom authentication flow in a hosted django app for pydrive2
I am using Django as backend. I need to create a custom auth flow for pydrive2. I cannot use gauth.LocalWebserverAuth() as that is suitable only on local machines. I see this sample code at pydrive documentation for custom auth flow. from pydrive2.auth import GoogleAuth gauth = GoogleAuth() auth_url = gauth.GetAuthUrl() # Create authentication url user needs to visit code = AskUserToVisitLinkAndGiveCode(auth_url) # Your customized authentication flow gauth.Auth(code) # Authorize and build service from the code AskUserToVisitLinkAndGiveCode is the part that I am unable to understand. What should this function do? Should my backend redirect to the URI that I added as the redirect URI on google drive console? Or should I redirect the user to the auth_url link? -
Django server not reloading on file changes
I just cloned a Django project from my Github for maintenance on another machine, installed all the dependencies then ran the server. Everything seems to be working fine except the fact that the server does not reload when I make file changes (on all python files). Changes in static files are not reflected too. Things to note: Django 4.0.3 Python 3.9.0 Environment manager is Pipenv. Settings.py DEBUG = True TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, "templates")], I don't have a custom runserver command I have the suggestions on this question but they didn't work. Any help would be greatly appreciated. -
Django error when using if condition on integar
I want to write if condition on integer when write if condition on string its is working but when I want to write same condition its not working. {% if 209 in l.label %} Book Now ! {% else %} Booked! {% endif %} -
Не вызывается Modal window после нажатия кнопки
делаю свой первый сайт, использую django, python, bootstrap 5, хочу что бы после заполнения формы человек нажал кнопку "отправить" и после этого всплыло модальное окно в котором будет написано что "все ок, ваша заявка создана" <div class="row mt-5 mb-5 p-2"> <form action="{% url 'feedback_view' %}" method="POST"> {% csrf_token %} <div class="col-md-6 mb-2"> <label for="exampleInputName" class="form-label">Ваше Имя</label> <input name="name" class="form-control" id="exampleInputName" aria-describedby="NameHelp"> </div> <div class="col-md-6 mb-2"> <label for="exampleInputphone" class="form-label">Ваш Телефон</label> <input name="phone" class="form-control" id="exampleInputphone" aria-describedby="NameHelp" placeholder="+7 (918) 000-00-00"> </div> <button type="submit" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal">Отправить</button> </form> </div> <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal">Отправить_btn</button> но почему-то кнопка 'отправить' не работает, но работает кнопка 'отправить_btn' которую я сделал для теста проблемы. все что я понял на данный момент что мне мешает type="submit" тк. во второй кнопке стоит type="button". как мне решить эту проблему, учитывая что это кнопка отправки формы? это код окна: {% if messages %} {% for message in messages %} <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Modal title</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> <p class="reviews">{{ message }}</p> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button> <button type="button" class="btn btn-primary">Save changes</button> </div> </div> </div> </div> {% endfor %} {% endif … -
Static files are not loaded generating pdf from html when application run in ASGI layer
I use Weasyprint to generate pdf from HTML. When I configure ASGI static files are not loaded in pdf, if I run the application in WSGI then the static file loads correctly. How can I solve this issue? -
Django - annotate query for if queried user is followed by current user
So I have this code below that given a user_uuid I look up the info of a user. All request come with a auth token that contains the current user's uuid. If the current user queried for their own profile then the is_current_user key should be true, which is done with the item['is_current_user'] = user_uuid == request.user.uuid line and then I have another flag for if the current user is following the queried user which is item['is_following'] = FollowUser.objects.filter(follower=str(request.user.uuid), followee=user_uuid).exists(). As you can see these are very ugly hacks and I was wondering if I could add these values to the annotate function. def get_user_info(request, user_uuid): try: query_annotated = User.objects.annotate( follower_count=Count('followee_id', distinct=True), followee_count=Count('follower_id', distinct=True)).get(pk=user_uuid) except User.DoesNotExist as e: return Response(dict(error=str(e), user_message='User not found.'), status=status.HTTP_404_NOT_FOUND) serializer = FullUserSerializer(query_annotated) # TODO: This is a hack the above annotation is not working item = serializer.data item['is_following'] = FollowUser.objects.filter(follower=str(request.user.uuid), followee=user_uuid).exists() item['is_current_user'] = user_uuid == request.user.uuid return Response(item, status=status.HTTP_200_OK) -
Websocket connection using djangochannelsrestframework
Websocket connection connects and disconnects after a second and shows the following error. Tried different ports still gives the same error Error image -
Django, csrf token not set
in settings.py: #SESSION_COOKIE_SAMESITE = 'Strict' SESSION_COOKIE_HTTPONLY = True #CSRF_COOKIE_SECURE = True #SESSION_COOKIE_SECURE = True CSRF_TRUSTED_ORIGINS = [ "http://localhost:3000",'http://127.0.0.1:8000'] in views.py: @method_decorator(csrf_protect,name='dispatch') class LoginView(views.APIView): permission_classes = [AllowAny,] serializer_class = serializer.LoginSerializer def post(self,request): data = serializer.LoginSerializer(data=request.data) print(data.is_valid()) print(data.errors) if data.is_valid(): email = data.data['email'] password = data.data['password'] auth = authenticate(username=email,password=password) if auth: login(request,auth) return HttpResponse(request.session.session_key ,status=200) else: print(password == "") if email == "" and password =="": return HttpResponse('both email and password field are empty',status=400) elif email == "": return HttpResponse('email field is empty',status=400) elif password == "": print("Here") return HttpResponse('passowrd field is empty',status = 400) the problems occur in frontend, (localhost:3000) but here is part of login component: let handleSubmit = (e)=>{ e.preventDefault() axios.post('http://127.0.0.1:8000/login/',login,{withCredential:true},{headers: {'Content-Type': 'application/json','X-CSRFToken':Cookies.get('csrftoken')}}).then( (res)=>{ console.log(res.data) } } I am getting: Forbidden-Csrf token not set on the backend, but when i login from backend 127.0.0.1:8000/login it works fine, and session id is set as https only cookie, csrf is set in cookies, but when i do it from frontend, it gives an error any idea? -
Django exposes raw html on rendered website
I am learning Django with the documentation tutorial: https://docs.djangoproject.com/en/4.0/intro/tutorial03/ I have just completed the "Write views that actually do something" part, but somethings is definitely amiss. Even though I copied the code 1:1, this is the render I get: Last two bits of code I edited: index.html in polls/templates/polls directory: {% if latest_question_list %} <ul> {% for question in latest_question_list %} <li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li> {% endfor %} </ul> {% else %} <p>No polls are available.</p> {% endif %} views.py in polls directory: from django.http import HttpResponse from django.template import loader from .models import Question def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] template = loader.get_template('polls/index.html') context = { 'latest_question_list': latest_question_list, } return HttpResponse(template.render(context, request)) def detail(request, question_id): return HttpResponse("You're looking at question %s." % question_id) def results(request, question_id): response = "You're looking at the results of question %s." return HttpResponse(response % question_id) def vote(request, question_id): return HttpResponse("You're voting on question %s." % question_id) -
Getting CORS error only when running django app through docker-compose
I have a Django backend app using Django-rest-framework. Currently, I'm developing the frontend with React using Axios to make HTTP requests. Whenever I run my app using python manage.py runserver and make a request from the React client, I get the expected response. Nevertheless, if I start my app using docker-compose, I get the No 'Access-Control-Allow-Origin' header is present on the requested resource response. This is my docker-compose.yaml services: db: image: postgres volumes: - /var/lib/docker/volumes/mobilequoter/db/data:/var/lib/postgresql/data ports: - ${DB_PORT}:5432 environment: - POSTGRES_USER=${DB_USER} - POSTGRES_PASSWORD=${DB_PASSWORD} - POSTGRES_DB=${DB_NAME} web: build: . command: gunicorn mobilequoter.wsgi --bind 0.0.0.0:${PORT} env_file: .env volumes: - .:/code ports: - 8000:${PORT} environment: - DB_HOST=db - DB_PORT=5432 depends_on: - db This is is my settings.py (with the settings related to CORS: handler = EnvHandler() SECRET_KEY = handler.SECRET_KEY DEBUG = handler.DEBUG ALLOWED_HOSTS = handler.ALLOWED_HOSTS CORS_ALLOWED_ORIGINS = handler.CORS_ALLOWED_ORIGINS SHELL_PLUS = 'ipython' INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # third party 'rest_framework', 'drf_yasg', 'storages', 'django_extensions', 'corsheaders', # local 'mobilequoter.helper', 'mobilequoter.authentication', 'mobilequoter.client', 'mobilequoter.quote', 'mobilequoter.sale', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] This are my env vars related to hosts: ALLOWED_HOSTS=127.0.0.1,localhost CORS_ALLOWED_ORIGINS=http://127.0.0.1:3000,http://localhost:3000 This is my axios client: import axios from "axios"; const axiosClient = axios.create({ baseURL: process.env.REACT_APP_BACKEND_URL … -
MySQLdb._exceptions.OperationalError: (2002, "Can't connect to server on '<servername>.database.windows.net') | Django+Azure+MySql
I'm having issues connecting my Django app in my local machine to MySql Database in Azure? I added my IP in the Rules and am connecting with this: 'default': { 'ENGINE': 'django.db.backends.mysql', 'HOST': '<servername>.database.windows.net', 'PORT': '3306', 'NAME': '<database_name>', 'USER': '<admin>@<servername>', 'PASSWORD': '<cecret>', 'OPTIONS': {'ssl': {'pem': 'tls.pem'} } }, I can connect using AzureDataStudio, but not with this configuration in django. I Nmaped my host, found a bunch of open ports but 3306 and 1433 are bound to Sql servers. Django's runserver shows MySQLdb._exceptions.OperationalError: (2002, "Can't connect to server on '<servername>.database.windows.net' (115)") with this configuration even if I have that server and database within it running. One example php query string in Azure portal has: $conn = new PDO("sqlsrv:server = tcp:<server_name>.database.windows.net,1433; Database = <database_name>", "<admin>", "{your_password_here}"); So, I'm assuming I should connect to 1433 but only 3306 works from DataStudio. From python manage.py runserver it shows django.db.utils.OperationalError: (2013, "Lost connection to server at 'handshake: reading initial communication packet', system error: 104") if I try port 1433. I'm at the limit of my knowledge regarding this. -
My form is not saving for some reason... did I made a mistake on my HTML?
I wanted to modify the way my forms is displayed using html and css. Here is the <form> part of my HTML: <form action="" method="post" enctype='multipart/form-data'> {% csrf_token %} <div> <input type="text" name="post_title" placeholder="Forum title" id="id_post_title"> <textarea name="post_body" placeholder="Forum content" id="id_post_body"></textarea> <div class="authors"> <!-- This class is to call my Users model --> <select name="author" id="id_author"> <option value="">----Select Author----</option> {% for author in authors %} <option value="{{ author.first_name }} {{ author.last_name }}">{{ author.first_name }} {{ author.last_name }}</option> {% endfor %} </select> </div> <div> <label> <input type="file" accept="image/" name="forum_image" required id="id_forum_image" >Upload Image </label> </div> <input type="submit" value="Save Post" class="save_post"> </div> </form> I tried form.as_p and it all worked just fine. Did I made a mistake in my HTML? Here is my forms.py: class AddForum(forms.ModelForm): class Meta: model = Forum fields = 'all' labels = { 'post_title': 'Title of your post:', 'post_body': 'Content of your post:', 'author': 'Author:', 'forum_image': 'Attach image:', } def __init__(self, *args, **kwargs): super(AddForum, self).__init__(*args, **kwargs) self.fields['forum_image'].required = False -
QuerySet of a ManyToManyField object is returning an empty list
I wanted to have a list of foreign keys for a field, so I had used Django's ManyToManyField. I have the following models: models.py class Community(models.Model): title = models.CharField(max_length=25, unique=True) total_users = models.IntegerField(default=0) active_users = models.IntegerField(default=0) created_by = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='+' ) posts = models.ManyToManyField('Post', null=True, blank=True, symmetrical=False) created_date = models.DateTimeField() members = models.ManyToManyField( settings.AUTH_USER_MODEL, related_name='+', blank=True, null=True, symmetrical=False ) def __str__(self): return self.title class Post(models.Model): title = models.CharField(max_length=300) content = models.TextField(max_length=50000, blank=True) upvotes = models.IntegerField(default=0) downvotes = models.IntegerField(default=0) comments = models.ManyToManyField('Comment', null=True, blank=True, symmetrical=False) created_by = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) created_date = models.DateTimeField() awards = models.JSONField(default=dict) community_id = models.ForeignKey('Community', on_delete=models.CASCADE, related_name='+', null=True, blank=True) additional_fields = models.JSONField(default=dict) def __str__(self): return self.title I'm able to view the list of foreign keys from the admin panel, but when I try to get the list of posts or members from the community object using community_object.members.all() and community_object.posts.all(), I get an empty list/queryset. I'm new to Django and I don't think I understand ManyToManyFields very well. -
Parent field name in not rendering in django while adding new data
I am working on one project where i am facing issue in field value rendering. I added one product and now i want to add the record of it means for how much rupee it cost etc. But the problem now is once it click on add form the product name here it should be product1 is not rendering automatically but the category is rendering automatically i can select the item from drop down list but it should render automatically. Once i click on add product it should automatically display that product name but it's not displaying but the category is displaying. Guide me what's wrong here. class Category(models.Model): name = models.CharField(max_length=200) def __str__(self) -> str: return self.name class Storage(models.Model): product_name = models.CharField(max_length=500) quantity = models.CharField(max_length=500, default='1') MRP = models.CharField(max_length=500, default='', blank=True) selling_price = models.DecimalField(max_digits=8, decimal_places=0) class ProductRecord(models.Model): storage = models.ForeignKey(Storage, on_delete=models.CASCADE) category = models.ForeignKey(Category, on_delete=models.CASCADE) model = models.CharField(max_length=1000, null=True, blank=True, unique=True) -
Why is it that when I enter `{{ something }}`, it also gets displayed in `HTML`?
I tried entering this code in my HTML: <div> <input type="file" name="{{ form.forum_image }}" accept="image/*"> </div> And this produces a site with the usual input file but after that is the text " accept="image/*"></div> What should I do with this so that it doesn't desplay the text? I included a picture. -
Django bulk create, ignore failed foreign keys?
Is there a way to ignore foreign key errors when doing a Model.objects.bulk_create and postgres? I'm aware of the ignore_conflicts=True flag and this seems to fix some errors, but I'm specifically dealing with data where the ForeignKey is not guaranteed to exist for one reason or another (such as the data being incomplete, deleted or more). I'm aware that this can be done at the database level using FOREIGN_KEY_CHECKS but I just want this for a particular bulk_create call. What can I do here? -
Django Generate Excel and save as Object with Celery and RabbitMQ
I am using Django 2.2.5, Celery 5.2.6 and RabbitMQ and I am new to the last 2. I want to generate an Excel sheet and store it in a FileField inside a newly created object (not download it), and this is what I did: project/settings.py: CELERY_RESULT_BACKEND = "django-db" CELERY_CACHE_BACKEND = "django-cache" CELERY_BROKER_URL = "amqp://localhost" CELERY_ACCEPT_CONTENT = ["application/json"] CELERY_TASK_SERIALIZER = "json" CELERY_RESULT_SERIALIZER = "json" CELERY_TIMEZONE = "Africa/Casablanca" project/celery.py: from __future__ import absolute_import, unicode_literals import os from celery import Celery os.environ.setdefault("DJANGO_SETTINGS_MODULE", "verautonoapi.settings") app = Celery("verautonoapi") app.config_from_object("django.conf:settings", namespace="CELERY") app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print("Request: {0!r}".format(self.request)) project/init.py : from __future__ import absolute_import, unicode_literals # This will make sure the app is always imported when # Django starts so that shared_task will use this app. from .celery import app as celery_app __all__ = ("celery_app",) app/tasks.py: from __future__ import absolute_import, unicode_literals from django.http import HttpResponse, FileResponse from celery import shared_task from celery.utils.log import get_task_logger from time import sleep from openpyxl import Workbook from datetime import date from .models import Dossier, Export logger = get_task_logger(__name__) @shared_task(bind=True, track_started=True) def exp_en_cours(request): print("task activated") sleep(7) print("now starting generating the file") dossier_queryset = Dossier.objects.filter(status_admin="Validation OR Requise") today = str(date.today()) response = FileResponse( content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", ) response["Content-Disposition"] = ( "attachment; filename=" + today + … -
There is no current event loop in thread 'uWSGIWorker1Core13'
We are running into a bug with one of our API endpoints that handles fetching tiktok user info. Our app is written in Django and is using the Django rest framework. We are using uwsgi to serve our app. We are able to serve our app locally using uwsgi and our tiktok API endpoint works as intended. However, when building and deploying our docker container to our production server, we see the following error response when making a request to our tiktok API endpoint: There is no current event loop in thread 'uWSGIWorker1Core13'. It's also important to point out that we are running our app in a synchronous environment. The PyTitktokApi has some async parts. We are thinking the the bug is related to this. It should be possible to run async code in a sync environment. Here is some sample code of our API endpoint and the function responsible for fetching tiktok user info: # rest API call class TikTokConnectView(GenericAPIView): """ Connect TikTok App View """ serializer_class = TikTokConnectSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) access_token = serializer.validated_data['access_token'] open_id = serializer.validated_data['open_id'] response_status, username = tiktok_username(open_id, access_token) if not response_status: return Response({'detail': 'Error fetching username'}, status=status.HTTP_404_NOT_FOUND) # … -
How to display progress bar for multi file upload form in Django?
I'm developing an application that requires users to upload a massive directory of multiple files/file types/subfolders. It will be handling 10's possibly 100s of GB per user, so having a progress bar displayed while uploading will be very helpful in informing the user the progress of the massive files. My current setup is based on the following answer to another question: https://stackoverflow.com/a/52016594/15739035 Here is a simplified setup: models.py: class Feed(models.Model): user=models.ForeignKey(User, on_delete=models.CASCADE) text=models.TextField(blank=False, max_length=500) class FeedFile(models.Model): file = models.FileField(upload_to="files/%Y/%m/%d") feed = models.ForeignKey(Feed, on_delete=models.CASCADE) forms.py: class FeedModelForm(forms.ModelForm): class Meta: model = Feed fields = ['text'] class FileModelForm(forms.ModelForm): class Meta: model = FeedFile fields = ['file'] widgets = { 'file': ClearableFileInput(attrs={'multiple': True}), } # widget is important to upload multiple files views.py: def upload_files_view(request): user = request.user if request.method == 'POST': form = FeedModelForm(request.POST) file_form = FileModelForm(request.POST, request.FILES) files = request.FILES.getlist('file') # field name in model if form.is_valid() and file_form.is_valid(): feed_instance = form.save(commit=False) feed_instance.user = user feed_instance.save() total_files = len(files) # Get the number of files in 'files' files_count = 0 # Use to show user the progress out of 'total_files' for f in files: file_instance = FeedFile(file=f, user=use, feed=feed_instance) file_instance.save() progress = f"{total_files}/{files_count}" # render(request, 'some_folder/upload_progress.html', {'file_form': file_form, 'form': form, 'progress': … -
The field items.Item.owner was declared with a lazy reference to 'items.user', but app 'items' doesn't provide model 'user'
I have extended User Django model using AbstractUser and I have pointed AUTH_USER_MODEL = 'items.User' in my settings/base.py, then I repointed all the FK to 'items.User'( was User before the change), but I am getting this error in every class I have mentioned 'items.User' when I run python manage.py migrate Approach 1 ======items/models.py======= from django.contrib.auth.models import AbstractUser class User(AbstractUser): bio = models.TextField(max_length=500, null=True, blank=True) birth_date = models.DateField(null=True, blank=True) address = models.CharField(max_length=100,null=True, blank=True) ----------------------------------------------- ======core/settings/base.py======= .... ALLOWED_HOSTS = [] AUTH_USER_MODEL = 'items.User' .... ----------------------------------------------- =====contracts/models.py======= class Contract(models.Model): ....... owner = models.ForeignKey('items.User', on_delete=models.CASCADE) ......... Approach 2 I have imported User model from core.settings.base.py ======core/settings/base.py===== .... ALLOWED_HOSTS = [] AUTH_USER_MODEL = 'items.User' .... ----------------------------------------------- =======contracts/model.py===== from core.settings.base import AUTH_USER_MODEL User = AUTH_USER_MODEL class Contract(models.Model): ....... owner = models.ForeignKey('items.User', on_delete=models.CASCADE) ......... and still getting the same error, do I need to drop Db or something because I kind of start to think about a conflict with migrations file with the new change(kind of circulation-alike issue)!!??? -
How to send a POST to Django Rest passing only ID on relationships, instead of whole dictionary after using Serializers for related fields?
I'm doing a little tutorial on Django Rest Framework, as I never used it before even though I have some experience with Django using templates. So I'm diverging a little from the tutorial class as I think I learn better this way, so I got to a point where in a Movie Rating simple application, when you do a GET from the Ratings serializer, you get just the FK IDs and the "stars" rating I added: [ { "id": 1, "user": 1, "movie": 1, "stars": 5 }, { "id": 2, "user": 1, "movie": 4, "stars": 4 } ] As I learned in a previous lesson from the said course, I know you can specify a serializer for each field, so instead on a GET request you get the dictionary with the whole data. class RatingSerializer(serializers.ModelSerializer): movie = MovieSerializer(many=False) user = UserSerializer(many=False) class Meta: model = Rating fields = ('id', 'user', 'movie', 'stars') That way the return from the GET to the Ratings route shows relational data instead of only the IDs: [ { "id": 1, "user": { "id": 1, "username": "admin", "email": "admin@admin.com" }, "movie": { "id": 1, "title": "Matrix 2", "synopsis": "Neo is back." }, "stars": 5 }, { …