Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Replace views functions for view class in Django
I would like to replace my views functions for a class. I'm new in Django and I try to send service object from user function to metrics function but I can´t do that with < a href="{% url 'metrics' %}">Metrics</a> in home.html. I don't know how to call a class instead a function too my code: def user(request): username = request.POST.get('username') password = request.POST.get('password') service = Service() service.start(username=username, password=password) return render( request, 'home.html', { 'service': service, } ) def metrics(request, service): metrics = service.get_metrics() return render(request, 'metrics.html', { 'metrics', metrics } the code I would like or something like it: class User(object): def __init__( self ): super(User, self).__init__() self.usernme = '' self.password = '' self.service = '' def get_service(self, request): self.username = request.POST.get('username') self.password = request.POST.get('password') self.service = Service() self.service.start(username=self.username, password=self.password) return render( request, 'home.html', {} ) def metrics(self, request): metrics = self.service.get_metrics() return render( request, 'metrics.html', { 'metrics': metrics, } ) -
CK - Editor in django is not working in production
I used ckeditor in my django project.It is working fine in local machine.But after deploying to web server it is not working. I can see the textarea without ckeditor tools. -
i got error " tshop.models.Tshirt.DoesNotExist: Tshirt matching query does not exist."
my views.py file cart=request.session.get('cart') if cart is None: cart=[] for c in cart: tshirt_id=c.get('tshirt') tshirt=Tshirt.objects.get(id=tshirt_id) c['size']=Sizevariant.objects.get(tshirt=tshirt_id, size=c['size']) c['tshirt']=tshirt print(cart) return render(request,"cart.html",{"cart":cart}) -
use existing odoo database with django or zend framework
I would like to use an existing odoo database (generated) with a framework in order to retreive and display some data (lms project) my question is which framework can be helpful in my case , django or zend framework -
Django Rest framework as Single Sign On
I have created DRF application with Django OAuth Toolkit (DOT) Rest Application with oAuth2 flow. I was planning to use these api's as Single Sign On (SSO). For javascript client it is working fine with "authorization_code" grant type which is returning me access token and refresh token and with those I can authorize and authenticate my javascript application. But for another Django application I am stuck to do the same. It has its own user database and default authentication backend. I want to authenticate users with SSO user database and create a session on successful login into SSO application (DRF application in my case). I want to achieve following: In Django Application I click on login link. It redirect me to SSO login page and ask me to provide user credentials. On successful login I redirect back to Django application and land on dashboard page after auto login. If anybody can spare some time and let me know if I am getting wrong anywhere it will be helpful. Thank you in advance. -
How can you display only one product in the products page? Django
I'm trying to build a products page, but when I add two products for example, both of the products get displayed instead of just one. How can you fix that? I've been trying some solutions but without much luck and it is driving me crazy already. views.py: def productpage(request, slug): context = {'items': Item.objects.all()} return render(request, 'ecommerceapp/product-single.html', context) HTML code: <section class="ftco-section"> <div class="container"> <div class="row"> {% for item in items %} <div class="col-lg-6 mb-5 ftco-animate"> <a href="images/product-1.png" class="image-popup prod-img-bg"><img src='{% static "images/product-1.png" %}' class="img-fluid" alt="Colorlib Template"></a> </div> <div class="col-lg-6 product-details pl-md-5 ftco-animate"> <h3>{{ item.title }}</h3> <div class="rating d-flex"> <p class="text-left mr-4"> <a href="#" class="mr-2">5.0</a> <a href="#"><span class="ion-ios-star-outline"></span></a> <a href="#"><span class="ion-ios-star-outline"></span></a> <a href="#"><span class="ion-ios-star-outline"></span></a> <a href="#"><span class="ion-ios-star-outline"></span></a> <a href="#"><span class="ion-ios-star-outline"></span></a> </p> <p class="text-left mr-4"> <a href="#" class="mr-2" style="color: #000;">100 <span style="color: #bbb;">Rating</span></a> </p> <p class="text-left"> <a href="#" class="mr-2" style="color: #000;">500 <span style="color: #bbb;">Sold</span></a> </p> </div> {% if messages %} <ul class="messages"> {% for message in messages %} <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li> {% endfor %} </ul> {% endif %} {% if item.discount_price %} <p class="price"><span>${{ item.discount_price }}</span></p> {% else %} <p class="price"><span>${{ item.price }}</span></p> {% endif %} <p>{{ item.description }} </p> <div class="row mt-4"> … -
Reverse for 'UserProfile' with arguments '('',)' not found. 1 pattern(s) tried: ['user/profile/(?P<pk>[0-9]+)/$']
Could someone please help with the template for the particular URL. Thanks in advance. Views.py class UserProfileView(DetailView): model = UserEntry template_name = 'userprofile_app/userprofile.html' def get_context_data(self, *args, **kwargs): users = UserEntry.objects.all() context = super(UserProfileView, self).get_context_data(*args, **kwargs) page_user = get_object_or_404(UserEntry, id=self.kwargs['pk']) context['page_user'] = page_user return context urls.py urlpatterns = [ path('entry/', UserRegistrationView.as_view(), name='UserEntry'), path('profile/<int:pk>/', UserProfileView.as_view(), name='UserProfile'), ] Templates <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <a class="navbar-brand" href="{% url 'UserProfile' UserEntry.id %}">EDIT PROFILE</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> -
Django: create new user with field which has ManyToMany relationship
Hi as I’m quite newby I’m trying to create a new user with ManyToMany relationship on account field: models.py class User(AbstractBaseUser, PermissionMixin): id = models.UUIDField(primary_key=True) name = models.CharField(max_length=250), account = models.ManyToManyField( 'accounts.Account', 'through=’Membership' ) class Account(models.Model): id = models.UUIDField(primary_key=True) name = models.CharField(max_length=250), class Membership(models.Model): id = models.UUIDField(primary_key=True) account = models.ForeignKey(‘accounts.Account’) permissions = models.ManyToManyField(‘accounts.Role’) What I need to achieve is after creating a new user the data from the api, I need to get this JSON: { id: 1, name: 'User 1', accounts: [ { id: 1, name: 'account1', permissions: [ { id: 1, name: 'permission1' } ] }, { id: 2, name: 'account2', permissions: [ { id: 1, name: 'permission' }, { id: 2, name: 'permission2' } ] } ] } So far I have only this and Im wondering how to deal with account with MAnyToMany relationship... user = models.User.objects.create_user( name='user 2', accounts= ???? ) ```’ Do I need to pass an array with accounts ids? but then how I can set the permission ? … Thanks in advanced!! -
How to get Sphinx doctest to reset the Django database after each test?
[TL;DR] When using Sphinx's make doctest, Django models created in tests are committed to the database; how do we prevent them auto-committing or to reset the database between each test (using a similar method to pytest)? Setup I created a basic Django application using the script: python -m pip install django sphinx pytest pytest-django pytest-sphinx django-admin startproject project_name cd project_name mkdir project_name/app python manage.py startapp app project_name/app touch pytest.ini touch conftest.py mkdir docs cd docs ; sphinx-quickstart ; cd .. (Creating separate source and build directories in sphinx-quickstart.) Then: Changed project_name/app/models.py to: """Models for the test application.""" from django.db import models class Animal(models.Model): """A django model for an animal. .. rubric: Example .. testsetup:: animal from project_name.app.models import Animal .. testcode:: animal frog = Animal.objects.create(name="frog") print( frog ) .. testoutput:: animal Animal object (1) """ name = models.CharField(max_length=200) Edited project_name/settings.py to add 'project_name.app' to the INSTALLED_APPS. Edited docs/source/conf.py to add the lines under "Path Setup": import os import sys import django sys.path.insert(0, os.path.abspath('../..')) os.environ['DJANGO_SETTINGS_MODULE'] = 'project_name.settings' django.setup() and, under "General Configuration", to set: extensions = [ "sphinx.ext.autodoc", "sphinx.ext.doctest", ] Replaced docs/source/index.rst with: .. toctree:: :maxdepth: 2 :caption: Contents: Project Name Documentation ========================== .. currentmodule:: project_name.app.models .. autoclass:: Animal Replace pytest.ini … -
Why isn't Admin detecting these models?
I'm making a kanban app to learn Django, and I've run into this problem: Admin doesn't pick up the models I've created. I had an existing Postgresql database with the necessary tables created, and autogenerated the models with python manage.py inspectdb. These are the relevant models: class Boards(models.Model): name = models.CharField(max_length=50) description = models.CharField(max_length=255) class Meta: managed = False db_table = "boards" class Columns(models.Model): name = models.CharField(max_length=25) board = models.ForeignKey(Boards, models.CASCADE, db_column="board") class Meta: managed = False db_table = "columns" class Cards(models.Model): name = models.CharField(max_length=140) description = models.TextField() deadline = models.DateTimeField() column = models.ForeignKey("Columns", models.CASCADE, db_column="column") class Meta: managed = False db_table = "cards" And this is the content of admin.py: from django.contrib import admin from .models import Boards, Columns, Cards admin.site.register(Boards) admin.site.register(Columns) admin.site.register(Cards) Just in case, these are the INSTALLED_APPS in settings.py: INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "rest_framework", ] Thanks in advance for the help! -
Django forms - how to select which model to create in the form
I have some loosely similar models that are separate but share a parent through concrete inheritance. Two of the models have the same form, so I want to be able to select which model to create within the form. To clarify, I want one of the fields to be a select field and the value of that field should tell the form which model class it is going to be creating. I have been trying to research this but I cannot find any related questions and all of my google searches are littered with "model form" and "model choice field" results. -
Deployment of Django project with Apache on windows AWS instance environment
I am trying to deploy a developed django project in AWS ec2 instance ( Windows instance server) with https. I have installed apache and configured the httpd.conf file. After configuration of public ip of ec2 instance in both django settings.py file and httpd.conf file , I tried to run the browser with public IP address of ec2 instance , it shows Internal server error. Kindly find the code of httpd.conf file: LoadFile "c:/users/sanmugapriyab/appdata/local/programs/python/python37/python37.dll" LoadModule wsgi_module "c:/users/sanmugapriyab/appdata/local/programs/python/python37/lib/site-packages/mod_wsgi/server/mod_wsgi.cp37-win_amd64.pyd" WSGIPythonHome "c:/users/sanmugapriyab/appdata/local/programs/python/python37";" <VirtualHost *:80> ServerName localhost WSGIPassAuthorization On ErrorLog "C:/users/sanmugapriyab/Desktop/hawk_web_version1/hawkproj/logs/hawkproj.error.log" CustomLog "C:/users/sanmugapriyab/Desktop/hawk_web_version1/hawkproj/logs/hawkproj.access.log" combined WSGIScriptAlias / "C:/users/sanmugapriyab/Desktop/hawk_web_version1/hawkproj/hawkproj/wsgi.py" <Directory "C:/users/sanmugapriyab/Desktop/hawk_web_version1/hawkproj/hawkproj/"> <Files wsgi.py> Require all granted </Files> </Directory> Alias /static "C:/users/sanmugapriyab/Desktop/hawk_web_version1/hawkproj/static" <Directory "C:/users/sanmugapriyab/Desktop/hawk_web_version1/hawkproj/static"> Require all granted </Directory> Alias /media "C:/users/sanmugapriyab/Desktop/hawk_web_version1/hawkproj/media" <Directory "C:/users/sanmugapriyab/Desktop/hawk_web_version1/hawkproj/media"> Require all granted </Directory> </VirtualHost> Kindly do the needful and help me on resolve of this issue. -
which database should i use for large scale web apps?
which database should i use for large scale web apps? i am planning to build a large scale website which include several features q/a , messaging , image posting etc... on fiction if i am predicting almost 5 million users that consistently use all of the features. on large scale which database should i use in django for this application DATA BASE SHOULD HANDLE LARGE NUMBER OF USERS AND REQUEST I KNOW 5 MILLION IS VERY HUGE BUT STILL WHICH DB YOU GUYS PREFER -
How to put each loop value into separate divs in django
Here's my html page. I want each 'question' to be placed in separate div to make them look nice. So I put in the following code: {% for post in object_list %} <div class="myDiv"> <a href="{% url 'article' post.pk %}">{{ post.title }}</a> <br>- {{ post.author }} , {{ post.date.date }}<br> </div> {% endfor %} But here's what it did: It makes one big div and placing all the posts/questions in them. How do I separate them? Here's my css: .myDiv { background-color: #012B39; text-align: left; margin: left; width: 25%; } Little help will be appreciated! THANKS P.S I will change the font colors to make them visible with the div. -
Video Streaming with Node.js not working on iOS
i have built a little website in django with a video player that gets partial video content from a node.js server. When I try to play a video from an ios device, no video is being played though. Is this an iOS problem or am i doing something wrong? Everything works on my windows machine My html code for the video: <video id="player" playsinline controls data-poster="{% get_media_prefix %}{{ thumbnail_path }}"> <source src="http://localhost:8001/video/{{ video_id }}" type="video/mp4" size="1080"/> </video> I use the Plyr video player with it My Node.js server: const express = require("express"); const app = express(); const fs = require("fs"); const sqlite3 = require("sqlite3").verbose(); const db = new sqlite3.Database('../db.sqlite3', sqlite3.OPEN_READONLY); //path for videos app.get("/video/:video_id", function (req, res) { let video_id = req.params.video_id; // get the requested video id //check if the video id is indeed a number, then convert it to an int if (!/^\d+$/.test(video_id)) return; video_id = parseInt(video_id); console.log('Serving video with id ' + video_id); db.get("SELECT file_path FROM streaming WHERE id=?", video_id, (error, row) => { //get the file path from the db let file_path = ""; if(row == null) return; file_path = row["file_path"]; const range = req.headers.range; // Ensure there is a range given for the video if … -
GeoDjango: Route creation inside polygon
I'm currently trying to create a LineString route like snake inside created by user polygon. Also, the user selects the width between the lines inside the route. Example of user selection polygon Base up on polygon, I want to create a route inside it like this Actually, everything I could think of is create a circle on the first point of polygon, find the point of circle inside the polygon and start LineString (my route) from the first point of polygon to the founded point, what is wrong and not what I want. if request.method == 'POST': form = AreaForm(request.POST) if form.is_valid(): form.save(commit=False) first_point = geos.Point(form.instance.field_location[0][0], srid=4326) first_point.transform(6347) circle = first_point.buffer(10) #10 - distance between lines, selected by user first_point.transform(4326) circle.transform(4326) point_inside_polygon = False while point_inside_polygon == False: point = random.choices([geos.Point(i, srid=4326) for i in circle[0]])[0] point_inside_polygon = form.instance.field_location.contains(point) form.instance.collecting_route = geos.LineString([first_point, point], srid=4326) form.save() I have no idea how to implement route creation like I want, any ideas? Is it possible? -
Validation inactive user Django
I looking for a resolving of my issue. I have custom User model: class User(AbstractUser): username = models.CharField(max_length=150, unique=True, blank=False, null=False) first_name = models.CharField(max_length=150, blank=True) last_name = models.CharField(max_length=150, blank=True) password = models.CharField(max_length=150, blank=False) email = models.EmailField(unique=True, blank=False) date_create = models.DateTimeField(auto_now_add=True) address = models.CharField(blank=True, max_length=128) phone = PhoneNumberField(unique=True) photo = models.ImageField(upload_to='images/', blank=True) is_active = models.BooleanField(default=True) In my app I have e-mail-confirmation. When I create user I hit the "is_active=False". When user activate account then flag "is_active=True". Everything works good. But when INactive user tries to log in I wanna get message from Django in Login form. Django has it(source code): def confirm_login_allowed(self, user): if not user.is_active: raise ValidationError( self.error_messages['inactive'], code='inactive', ) But doesn't work for me. I tried to override AuthenticationForm: User = get_user_model() class CustomAuthenticationForm(AuthenticationForm): class Meta: # tried with Meta and without model = User def confirm_login_allowed(self, user): if not user.is_active: raise forms.ValidationError('There was a problem with your login.') View: class CustomLoginView(SuccessMessageMixin, LoginView): form_class = CustomAuthenticationForm success_url = reverse_lazy('home') success_message = "You was logged in successfully" url: path('login/', CustomLoginView.as_view(), name='login'), Could someone help me? Thanks. -
How to send scraped data to a page but without waiting for the page to load?
I am showing some scraped data on my Django website.. The data is changing a couple times every hour so it needs to be updated. I am using Beautiful Soup to scrape the data, then im sending it to the view and passing it in a context dictionary to present it on a website. The problem is that scraping function takes some time to work and because of it the website is not loading until the function does its work. How can I make it load faster? There is no API on the data webstie. -
How do I get my API with django-cors-headers working without 405 error
I can't find my answer in other posts about CORS and django. So I am asking my question here after a full day figuring out what I am doing wrong. my frontend is VUE.js and this app is making this API call to my backend on a DigitalOcean.com app server with Django and djangoRestFramework. fetch( 'https://someurl.ondigitalocean.app/api/user/token', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ email: 'emai@email.com', password: 'password' }), }, ).then(function(response){ if (response.ok){ return response.json() } }).then(function(data) { console.log(data) } ) This does a post to receive a token. This call is just for testing purpose. The API is working, for testing I use the default django browser interface and also all my units tests are OK. I am using django-cors-headers as Middleware and added corsheaders to my 'APP' and 'MIDDLEWARE'' in my settings file. these are my settings: CORS_ALLOWED_ORIGINS = [ "http://maf-internet.nl", "http://localhost:8080", "http://127.0.0.1:8000" ] CSRF_TRUSTED_ORIGINS = [ "http://maf-internet.nl", ] CORS_ALLOW_ALL_ORIGINS = True CORS_ALLOW_METHODS = [ 'DELETE', 'GET', 'OPTIONS', 'PATCH', 'POST', 'PUT', ] CORS_ALLOW_HEADERS = [ 'accept', 'accept-encoding', 'authorization', 'content-type', 'dnt', 'origin', 'user-agent', 'x-csrftoken', 'x-requested-with', ] These are my packages: Django>= 2.2, <2.2.2 djangorestframework>=3.9.0,<3.10.0 psycopg2-binary dj-database-url gunicorn django-cors-headers>=3.7.0 flake8>=3.6.0,<3.7.0 Digital Ocean also has an entry for CORS … -
How can i solve this error ("Application error")
this is the error message these are the logs of mysite I want to deploy my site on heroku and it gives me "Application error how can i solve this" My procfile is look like this web: gunicorn theweatherforecast.wsgi --log-file - clock: python 'weather/cronjob.py' -
error in forms.py wile runserver or migrate
I am trying to add one more field of profile picture in my registration form but after saving the code and while trying to run locally it shows error inconsistent use of tabs and spaces in indentation . please help if you can see error my forms.py file error while runserver -
How to write a FormView that can handle multiple forms
I'm trying to find a way on how to write one FormView that can handle different ModelForms. My situation: I have 6 models that have a common AbstractBaseClass with a custom ModelManager. I want to display them as ModelForms in a FormView that displays the form(s) and handles the POST data. They have the same methods. My approach: Abstract Base Class with a custom ModelManager that all models inherit from. **models.py** class AbstractBaseClass(): slug = models.CharField(max_length=20) name = models.CharField(max_length=40) objects = MyModelManager() def __str__(self): return self.name def get_absolute_url(self): return reverse('some-name', kwargs=[str(self.name)]) class Meta: abstract = True class ChildClassOne(AbstractBaseClass): city = models.CharField(...) class ChildClassTwo(AbstractBaseClass): city = models.CharField(...) In forms.py I created the corresponding ModelForms ChildClassOneForm and ChildClassTwoForm with validation-methods. My views.py is something like this: **views.py** class ChildClassOneView(FormView): template_name = 'formulare/formular_detail.html' form_class = ChildClassOneForm #here's the problem - it should work for other ModelForms, too def post(self, request, *args, **kwargs) form = self.form_class(request.POST) if form.is_valid(): # do lots of different stuff with the data, send email, etc. **I want to avoid:** class ChildClassTwoView(FormView): form_class = ChildClassTwoForm # the rest is identical with ChildClassOneView **urls.py** path('forms/<str:slug>', ChildClassOneView.as_view(), name='some-name') And here's my question: How can I write a FormView that can be used … -
Error while running the collectstatic on django FileNotFoundError:
So I am running the command python manage.py collectstatic and I am getting an error, I am pretty sure it is because I have some setting off inside my settings.py. First I will attach a picture, so everyone can see the tree of my documents and then the error itself. Any idea of what I did wrong? Thank you. Picture: Image with the tree of files and settings My settings.py # on the top import os # on the bottom BASE_DIR = os.path.dirname(os.path.abspath(__file__)) STATIC_ROOT = os.path.normpath(os.path.join(BASE_DIR, 'staticfiles')) STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) The error is the following: (env) PS C:\Users\lenil\Documents\Development\Personal Projects\the-journey\thejourney_project> python manage.py collectstatic Traceback (most recent call last): File "C:\Users\lenil\Documents\Development\Personal Projects\the-journey\thejourney_project\manage.py", line 22, in <module> main() File "C:\Users\lenil\Documents\Development\Personal Projects\the-journey\thejourney_project\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\lenil\Documents\Development\Personal Projects\the-journey\thejourney_project\env\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\lenil\Documents\Development\Personal Projects\the-journey\thejourney_project\env\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\lenil\Documents\Development\Personal Projects\the-journey\thejourney_project\env\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\lenil\Documents\Development\Personal Projects\the-journey\thejourney_project\env\lib\site-packages\django\core\management\base.py", line 371, in execute output = self.handle(*args, **options) File "C:\Users\lenil\Documents\Development\Personal Projects\the-journey\thejourney_project\env\lib\site-packages\django\contrib\staticfiles\management\commands\collectstatic.py", line 194, in handle collected = self.collect() File "C:\Users\lenil\Documents\Development\Personal Projects\the-journey\thejourney_project\env\lib\site-packages\django\contrib\staticfiles\management\commands\collectstatic.py", line 109, in collect for path, storage in finder.list(self.ignore_patterns): File "C:\Users\lenil\Documents\Development\Personal Projects\the-journey\thejourney_project\env\lib\site-packages\django\contrib\staticfiles\finders.py", line 130, in … -
DRF Uploading to aws s3 multiple files(more than 1)
I have endpoint which successfully upload to AWS s3 bucket image but when I try to upload more than 1 file, It upload last one. My view: class MediaViewSet(mixins.CreateModelMixin, viewsets.GenericViewSet): queryset = Media.objects.all() serializer_class = MediaSerializer permission_classes = (IsAuthenticated,) My serializers: class MediaSerializer(serializers.ModelSerializer): class Meta: model = models.Media fields = ('uploaded_at', 'upload') My Model: class Media(models.Model): uploaded_at = models.DateTimeField(auto_now_add=True) upload = models.FileField(storage=MediaStorage()) -
While deleting : ValueError: "<User: Test USER (testuser)>" needs to have a value for field "id" before this many-to-many relationship can be used
I'm pretty sure people will say this question already has answers but I couldn't find any. In other questions, the problem appears when creating objects with many-to-many relations. In my case, it happens when I try to delete a record.... Eh ?! I have the User model and the Group (from django.contrib.auth.models import Group) with a standard many-to-many relation between them (django standard). Everything was working fine until I use the depth Meta attribute in the serializers (which is very convenient by the way !). My User serializer : from rest_framework import serializers from ..models.base_user import User class BaseUserSerializer(serializers.ModelSerializer): class Meta: model = User depth = 1 fields = ( 'id', 'username', 'email', 'first_name', 'last_name', 'is_active', 'groups', ) My Group serializer : from django.contrib.auth.models import Group from rest_framework import serializers class BaseGroupSerializer(serializers.ModelSerializer): class Meta: model = Group depth = 1 fields = ( 'id', 'name', 'user_set', ) def to_representation(self, instance): response = super().to_representation(instance) # By using the 'depth' Meta attribute, the nested User records were serialized # with their password. By doing this, we remove the 'password' field from the # representation of the Groups and their nested Users. for user in response.get("user_set"): user.pop("password", None) return response My API function …