Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django-Registration through axios Post
I try to register an User using django-registration.one_step.views but I cannot seem to succes and I could not debug what is the missing part. I have urls in my Django side path('accounts/register/', RegistrationView.as_view( form_class=YogaUserForm, success_url="/" ), name="django_registration_register"), path('accounts/', include('django_registration.backends.one_step.urls')), path('accounts/', include('django.contrib.auth.urls')) In vuejs application I have used vuex and axios async registerUser(context, payload) { try { const response = await DjangoAPI.register(payload); return Promise.resolve(response); } catch(err) { console.log('err in store.user/registerUser', err); return Promise.reject(err); } }, async register(payload) { try { const {username, password1, password2, email} = {...payload}; const response = await apiCall .post('/accounts/register/', { email, password1, password2, username }); console.log("test"); console.log(response); return Promise.resolve(response); } catch(err) { console.log('err in DjangoService/register', err); return Promise.reject(err); } }, When I try to register, nothing happens, I get console.logs(): config: adapter: ƒ xhrAdapter(config) baseURL: "http://localhost:8000/" data: "{"email":"random@random.com","password1":"ne12veryt..","password2":"ne12veryt..","username":"random"}" headers: {Accept: "application/json, text/plain, */*", Content-Type: "application/json;charset=utf-8", Authorization: "Bearer null", X-CSRFTOKEN: "hqyVxsYXxI929ZtB5arssIDt3yq5O6acEJGdkmAdPYQhhN4RXPq2jl18Vj65Z2cm"} method: "post" url: "/accounts/register/" xsrfCookieName: "csrftoken" xsrfHeaderName: "X-CSRFTOKEN" headers: {access-control-allow-credentials: "true", access-control-allow-origin: "http://localhost:8000", content-language: "tr", content-length: "8361", content-type: "text/html; charset=utf-8", …} request: XMLHttpRequest {readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, onreadystatechange: ƒ, …} status: 200 statusText: "OK" How can I fix my registration when using django-registration? Best Regards -
Django admin. Add 'select group' to custom user model ForeignKey
Goodmorning everyone. First post so apologies if something wrong. I'm trying to add the possibility to add a custom user to a group from the django admin panel. I can do it while registering an Account user but not registering an Affiliateuser which is linked to the Accountuser by : models.ForeignKey(Account, null=True, on_delete=models.SET_NULL, limit_choices_to={'groups__name': 'Super'}) In my models.py i create an AccountManager class extending BaseUserManager. I also create the Account class (extending AbstractBaseUser and PermissionsMixindefining the USERNAME_FIELD and REQUIRED_FIELDS) and the Affiliateclass (extending models.Model and with ForeignKey stated above). Registering an Affiliate from the webpage it directly goes to the 'Affiliate' group, but when doing it from the admin I can't choose. I think I have to modify something in admin.py, but I'm not sure. Here's my admin.py from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.contrib.auth.forms import UserChangeForm, UserCreationForm from .models import * class AccountAdmin(UserAdmin): list_display = ('username', 'email', 'first_name', 'last_name', 'date_joined', 'last_login', 'is_admin', 'is_superuser') search_fields = ('email', 'username', 'ref_code') readonly_fields = ('date_joined', 'last_login') filter_horizontal = () list_filter = () fieldsets = () admin.site.register(Account, AccountAdmin) admin.site.register(Affiliate) models.py: from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin class MyAccountManager(BaseUserManager): def create_user(self, email, username, first_name, last_name, password=None): if not … -
Test the instance attribute in signal function django before to execute
I Try to put if statement in my post_save signal to check the instance attribute and execute the good instruction. I have 3 profiles User (3 table wich are link witch my costume User mode by OneToOneField. I have the flags is_student, is_teacher and is_manager (BooleanFielsd) in my User model. So I want to check the flag wich is True and execute the save. from django.db.models.signals import post_save from accounts.models import User, Student, Teacher, Manager from django.dispatch import receiver @receiver(post_save, sender=User) def sign_up_student_profile(sender, instance, created, **kwargs): if (instance.is_student ==True): Student.objects.create(user=instance) elif (instance.is_teacher ==True): Teacher.objects.create(user=instance) elif (instance.is_manager ==True): Manager.objects.create(user=instance) else: pass -
Could somebody please help me for this requirement?
This is what I want to achieve. The url needs to be called through ajax as well. The requirement is to calculate similar things in back end and from front end using ajax call. I have to pass some dictionary/json object in the url and get the result. class SomeName(View): def get(self, request, *args, **kwargs): # GET method . . # Calling nother url: '/url-to-calculate-something/' # Needs to pass dict object in the above url # Get response and use this like below context = {'value': 'calculated_value'} . . response = TemplateResponse(request, 'template_name', context) return response urlpattern = [ re_path(r'/url-to-calculate-something/', CalculationDef, name='some-calculation') ] def CalculationDef(View): # Here another call to some api # Get result return result -
how to get sessionid from Cookie in browser using jquery?
I am using js.cookie CDN to get cookie .In my browser there is a Cookie with name sessionid ,(set by django backend itself) ,having some value , but Cookie.get('sessionid') is giving undefined //CDN : <script src="https://cdn.jsdelivr.net/npm/js-cookie@rc/dist/js.cookie.min.js"></script> -
Dynamically load content in Bootstrap Modal with AJAX with Django
I am a begineer in Django framework I want to Dynamically load content in Bootstrap Modal with AJAX something like this https://makitweb.com/demo/modal_ajax/index.php I found many tutorials on internet but i want some guidance on the part where button is pressed and modal shows data related to that item. Please pardon me if it's a bad question. -
Two views with only one diffrent line of code
I have two views with only one diffrent line of code, rest is same in both views. How to prevent repetition of code? Can i delete tag_view and add optional parameter as kwarg to index and depending on it return view without specific tag or with tag? Is it how it should work? My views below. def index(request): post_form = AddPostForm(request.POST or None, instance=request.user) comment_form = AddCommentForm(request.POST or None, instance=request.user) if request.method == 'POST': # FORMULARZ DODAWANIA POSTU if post_form.is_valid(): post_form.save() create_notifications(post_form.instance) # FORMULARZ DODAWANIA KOMENTARZA if comment_form.is_valid(): comment_form.save() (posts, comments) = serve_post_and_comments_except_blocked(request) return render(request, 'mikroblog/index.html', {'posts': posts, 'comments': comments, 'post_form': post_form, 'comment_form': comment_form}) def tag_view(request, tag): post_form = AddPostForm(request.POST or None, instance=request.user) comment_form = AddCommentForm(request.POST or None, instance=request.user) if request.method == 'POST': # FORMULARZ DODAWANIA POSTU if post_form.is_valid(): post_form.save() create_notifications(post_form.instance) # FORMULARZ DODAWANIA KOMENTARZA if comment_form.is_valid(): comment_form.save() (posts, comments) = serve_post_and_comments_except_blocked(request) posts.filter(content_post__contains=tag) actual_tag = tag return render(request, 'mikroblog/tag.html', {'posts': posts, 'actual_tag': actual_tag, 'comments': comments, 'post_form': post_form, 'comment_form': comment_form}) -
Postgres raw query for foreign key in Django
I had written a SQL raw query in python for the Postgres database. However, the following query I wrote for was when my Song field in my Django model was a many-to-many field. But, due to other requirements, the same Song field in the model has been changed to the foreign key. The issue, I am facing is that the query doesn't runs successfully and returns an error. I had written two raw Postgres queries: First query:(Using left join) select songs.id, songs.name, songs.artist, songs.album, songs.albumart, songs."albumartThumbnail", cpr.votes, is_requested from ( select id, name, artist, album, albumart, "albumartThumbnail" from ( select song_id from core_plsongassociation where playlist_id in (1477) ) as sinpl left join songs on sinpl.song_id=id where explicit=False ) as songs left join ( select song_id, votes, bool_or(thirdpartyuser_id=177) as is_requested from ( select * from core_priorityrequests where client_id=2876 and is_played=False ) as clpr left join core_priorityrequests_third_party_user on clpr.id=priorityrequests_id group by priorityrequests_id, song_id, votes ) as cpr on songs.id=cpr.song_id left join ( select core_blockedsongs_song.song_id from core_blockedsongs join core_blockedsongs_song on core_blockedsongs.id=core_blockedsongs_song.blockedsongs_id where core_blockedsongs.unblock_flag = 'f' and core_blockedsongs.client_id=2870 ) as c on c.song_id = songs.id where c.song_id is null; Second Query(without using left join): select songs.id, songs.name, songs.artist, songs.album, songs.albumart, songs."albumartThumbnail", cpr.votes, is_requested from … -
Why I cannot save the new form to database?
I really don't know what's the problem of my code.I'm using django connected to my database, and try to save my new data into database, here is the models.py: class guest_room(models.Model): room_number=models.CharField(max_length=25,primary_key=True) room_type=models.CharField(max_length=25) room_status=models.CharField(max_length=25) Here is the form.py: class guest_room_form(forms.ModelForm): class Meta: model = guest_room fields = ['room_number', 'room_type', 'room_status'] widgets = { 'room_number': forms.TextInput(attrs={ 'class': 'form-control' }), 'room_type': forms.TextInput(attrs={ 'class': 'form-control' }), 'room_status': forms.TextInput(attrs={ 'class': 'form-control' }), } Here is the views.py: def addnewroom(request): if request.method=="post": form=guest_room_form(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect("guestroom") else: form=guest_room_form() return render(request,'addnewroom.html',{'form':form}) This is my html of the add new data page: <form method="POST" class="post-form" action="../addnewroom/"> {% csrf_token %} <div class="container"> <br> <div class="form-group row"> <label class="col-sm-1 col-form-label"></label> <div class="col-sm-4"> <h3>Enter Details</h3> </div> </div> <div class="form-group row"> <label class="col-sm-2 col-form-label">Room Number:</label> <div class="col-sm-4"> {{ form.room_number }} </div> </div> <div class="form-group row"> <label class="col-sm-2 col-form-label">Employee Email:</label> <div class="col-sm-4"> {{ form.room_type }} </div> </div> <div class="form-group row"> <label class="col-sm-2 col-form-label">Employee Contact:</label> <div class="col-sm-4"> {{ form.room_status }} </div> </div> <div class="form-group row"> <label class="col-sm-1 col-form-label"></label> <div class="col-sm-4"> <button type="submit" class="btn btn-primary">Submit</button> </div> </div> </div> </form> I want to go back to the 'guestroom.html' after submitting successfully, but now after I submit, it stayed at the same page. I … -
How to display all the children of parent category?
Here I want to display all the child categories of a parent category if it has child. But the below code in my templates not working properly. How to properly get all the child categories of a particular parent in the templates here ? model class Category(models.Model): parent = models.ForeignKey('self', blank=True, null=True, on_delete=models.SET_NULL) nesting_level = models.IntegerField(default=0) title = models.CharField(max_length=255, unique=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) views class ListCategoryView(generic.ListView): model = Category context_object_name = 'categories' template_name = 'list_categories.html' ordering = '-created' template <td class="text-primary"> {{category.title}} </td> <td class="text-primary toggle">{% if category.parent %}{{category.parent.title}} {{category.category_set.all.count}} # not working properly {% else %} None {% endif %} <div class="table-dialog"> {% for category in category.category_set.all %} {{category}}{% if not forloop.last %}, {% endif %} #not working properly {% endfor %} </div> </td> <td>{{category.created}}</td> -
Reduce the execution time of django view
I have a django view which returns all the products of Product model. Situation is discount is dependent on product as well as user so it has to be calculated every time at runtime. I have added only 3500 products yet and server is taking 40-50 seconds to respond. I wonder how much time will it take when i will add 100,000 products. How can i optimize this? @login_required def product_list(request): context = {} product_qs = Product.objects.all() product_list = [] for product in product_qs: discount_applied_product = apply_discount(product,request.user) product_list.append(discount_applied_product) context['products'] = product_list return render(request,"myapp/products.html",context) I have deployed website on Google App engine standard. If i increase gunicorn workers, is it going to help? -
Django ORM Prefetch and filter results
I want to filter GeneralItem by manytomany items without null (filtered by Prefetch): class GeneralItem(models.Model): title = models.CharField(max_length=250) items = models.ManyToManyField('MediaItem') qs = GeneralItem.objects.prefetch_related( Prefetch( 'items', queryset=MediaItem.objects.filter(**item_params), to_attr='custom_items' ) ).filter(custom_items__isnull=False) But I get error: Cannot resolve keyword 'custom_items' into field. Choices are: items, title Is there a way to filter this? -
Conditional unique_together in Django
I have following unique constraint in my model. class Meta: unique_together = (('crop', 'order', 'sku'),) But sku may be null in some cases and in that case this unique_together is not working as null is not equal to null.i am thinking to make a conditional unique_together like if sku is not null then (('crop', 'order', 'sku'),) else (('crop', 'order'),). -
How can I edit many to many relations in Django (admin sites)
I need to add tags to my blog posts. Each tag should be available on many posts and also posts can have multiple tags. How can I change the admin sites so that I can add multiple (existing) tags to a post? The standard view only lets me add by creating new ones. model.py # blog post tags class Tag(models.Model): name = models.CharField(max_length=20) slug = models.SlugField(max_length=40, unique=True) date_created = models.DateTimeField(default=timezone.now) class Meta: ordering = ['name'] def __str__(self): return self.name # blog posts class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) last_modified = models.DateTimeField(auto_now=True) author = models.ForeignKey(User, on_delete=models.CASCADE) # 1 author per post tags = models.ManyToManyField(Tag, related_name='tags') # n tags per m posts class Meta: ordering = ['title'] def __str__(self): return self.title Current Admin Site I know I need to edit my admin.py file in my blog application but everything i tried so far did not work. Is there a recipe for these admin views? I want to achieve something like this (1st answer - filtered view). -
Changing default "migrations" directory
What I want to do: To use a different name for the "migrations" folder. What I tried: It seems like the default approach is to set the 'MIGRATION_MODULES' in settings.py (as documented here): MIGRATIONS_MODULE = {'app_name':'app_name.migrations_folder_name'} But for some reason caused the migrations of the default apps to fail: You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, authtoken, contenttypes, sessions. How can I make sure that the default apps migrations works as intended? -
How to fix Reverse for '' not found. '' is not a valid view function or pattern name
I have a custom form created in my template with two datefields and one custom autocomplete field. My aim is to take the values of those datefields in my view and afterwards to create and call a url with ajax. After submiting the button I face with the error: Reverse for '' not found. '' is not a valid view function or pattern name. How can i fix this? template <script> $(document).ready(function() { $('#offers').DataTable( { "pagingType": "full_numbers" } ); } ); $('#offers').dataTable( { "serverSide": true, // "ajax": "https://www.example.com/api/v2/offers?dateFrom={{from_date}}T00%3A00%3A00&dateTo={{to_date}}T00%3A00%3A00&{{companyId}}" "ajax": '{{url}}' } ); </script> <form action="" method="get"> {% csrf_token %} <label for="from_date">From date</label> <input type="date" id="from_date" name="from_date"> <label for="to_date">To date</label> <input type="date" id="to_date" name="to_date"> <label for="company">Company</label> <select name="companyId" class="company" id = "company"></select> <button class="btn btn-primary" id ="submit" type="submit" > Submit </button> </form> <script> $('.company').select2({ ajax: { url: '{% url "mmkcompany-autocomplete" %}', dataType: 'json' } }); </script> view from_date = self.request.GET.get('from_date','') #string from_= "dateFrom="+from_date+"T00%3A00%3A00" to_date = self.request.GET.get('to_date','') #string to_= "dateTo="+to_date+"T00%3A00%3A00" company = self.request.GET.get('companyId','') #string companyId = "companyId="+company if self.request.method == 'GET' and from_date !="" and to_date!="": headers = { 'accept': 'application/json', 'Authorization': '', } url = 'https://www.example.com/api/v2/offers?'+from_+"&"+to_ existence = 1 try: offer_request = requests.get(url, headers=headers) existence = 2 except: print("nothing") if existence … -
Django test failing due to AssertionError:201 !=400
Got the following view class MyUserCreate(APIView): ''' Creates the user. ''' def post(self, request, format='json'): serializer = MyUserSerializer(data=request.data) if serializer.is_valid(): user = serializer.save() if user: return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) And wanted to create a test to ensure I'm not able to create a user with the same username. In serializers.py, the username in MyUserSerializer loks like this username = serializers.CharField( validators=[UniqueValidator(queryset=User.objects.all())], max_length=32 ) and in models.py, the username in MyUser username = models.CharField(db_column='username', unique=True, max_length=20) In tests.py class MyUserTest(APITestCase): ... def test_create_user_with_preexisting_username(self): data = { 'username': 'testing', 'password': 'test' } response = self.client.post(self.create_url, data, format='json') self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) self.assertEqual(MyUser.objects.count(), 1) self.assertEqual(len(response.data['username']), 1) Up to this point the tests for user creation, user without username, user with a too long username, ... all worked out fine. The problem only happens in this specific test. The user testing exists in the DB If I run python manage.py tests then FAIL: test_create_user_with_preexisting_username (codeLabsApp.tests.MyUserTest) Ensure we can't create a user with preexisting username. ---------------------------------------------------------------------- Traceback (most recent call last): ... AssertionError: 201 != 400 So I'm getting a 201 Created instead of a 400 Bad Request. -
How authenticate with username, password and token in Django?
I'm trying to authenticate users in Django with username, password and token. All of them are stored in a database. #accounts/views.py from django.shortcuts import render, redirect from django.contrib.auth import login, authenticate, logout from account.forms import RegistrationForm, AccountAuthenticationForm def login_view(request): if request.POST: form = AccountAuthenticationForm(request.POST) if form.is_valid(): username = request.POST['username'] password = request.POST['password'] token = request.POST['token'] user = authenticate(username = username, password = password, token = token) if user: login(request, user) return redirect("home") else: form = AccountAuthenticationForm() context['login_form'] = form return render(request, 'account/login.html', context) #account/models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class MyAccountManager(BaseUserManager): def create_user(self, username, token, password=None): if not username: raise ValueError('Users must have an username') if not token: raise ValueError('Users must have a token') user = self.model( username = username, token = token, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, username, token, password=None): user = self.create_user( username = username, password = password, token = token, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user Login is possible with the right username/password combination, but with the wrong token. What am I doing wrong? -
How to have list of strings in Django REST framework model using MongoDB
I am using Django version 2.2.11 with MongoDB as database I a Simple Array Field to store a list of strings in a Django REST framework Model. I want the serialized JSON output to be like this. { name : "John" roles : [ "string1", "string2" ] } I searched the internet and could only find implementation of this for PostgreSQL. I just need to store the data of roles as string/list in database and need to display in proper format in api view. -
Django Redirect to different URL base on forms choice
Hello I stack with redirect to different pages base on Form Choice in Django. I have 4 different choices to pick, but everyone has different next page. I do something like this : forms.py class DodajForm(forms.ModelForm): class Meta: model = Atrakcje exclude = ['user'] fields = ['tytul', 'opis', 'kategoriaa', 'adres', 'wojewodztwo', 'miasto', 'telefon', 'zdjecie', 'wideo', 'email', 'strona', 'facebook', 'kodpocztowy', 'zaswiadczenia', 'pakiet', 'cena', 'dla'] widgets = { 'kategoriaa': forms.Select( attrs={ 'class': 'form-control' } ), 'pakiet': forms.Select( attrs={ 'class': 'form-control' } ), 'tytul': forms.TextInput( attrs={ 'class': 'form-label' } ), 'opis': forms.Textarea( attrs={ 'class': 'form-control' } ), 'zdjecie': forms.FileInput( attrs={ 'class': 'dropzone dz-clickable', } ), 'zaswiadczenia': forms.FileInput( attrs={ 'class': 'dropzone dz-clickable', } ), } views.py def formularz(request): form = DodajForm(request.POST) if form.is_valid(): ogloszenie = form.save(commit=False) ogloszenie.user = request.user ogloszenie.save() if form.pakiet == "free": return redirect('atrakcje:after') elif form.pakiet == "pakiet1": return redirect('atrakcje:after1') elif form.pakiet == "pakiet2": return redirect('atrakcje:after2') else: return redirect('atrakcje:after3') else: ogloszenie = DodajForm() context = { 'form': form,} return render(request, 'formularz.html', context) and I have error on every choice like this : "AttributeError at /atrakcje/formularz/ 'DodajForm' object has no attribute 'pakiet' There is a error on this line : if form.pakiet == "free": Any recommendations how to resolve this please? -
django - mark_safe is not working as it is supposed to?
I don't know why but my mark_safe is not working properly,It's still loading html as a normal text. I had to use mark_safe on one of my serializer field and then get them through my api on the frontend by using jquery but I tried to use safe filter in my seriliazer,the format_html,mark_safe but it's still loading my html as a text,this field which I am trying to pass as safe is an HTMLField by tinymice! Here's my serializer class FooterSerializer(serializers.ModelSerializer): disclaimer = serializers.SerializerMethodField(read_only=True) class Meta: model = Footer fields = ["disclaimer"] def get_disclaimer(self,obj): disclaimer = mark_safe(obj.disclaimer) return disclaimer And here's my ajax call // FOOTER Disclaimer $.ajax({ url:'/api/footer/', method:"GET", headers: { 'Accept-Language':language, } , success:(data)=>{ $(".footer-disclaimer").text(data.footer.disclaimer) }, error:(data)=>{ $(".footer-disclaimer").text("Err! Disclaimer not loading....") } }) -
Problem django objects function "SUM AGGREGATE RETURN AND SAVE"
im trying to save as object by using this code, but it's give me just a "function return", and not the real value. when i did the same in admin it works fine, but i did'n save that in my db. here my code in admin: def get_total_carregado(self, obj): filt = obj.contrato tot = Carga.objects.filter(pedido__contrato=filt).values('pedido').aggregate(pesot=Sum('peso'))['pesot'] return tot get_total_carregado.short_description = "Carregado" and now in models: def get_carregado(): filt = Pedido.contrato return Carga.objects.filter(pedido__contrato=filt).values('pedido').aggregate(pesot=Sum('peso'))['pesot'] this is what i got : it's not what i want :( -
Pytest-Django on code that gets its own database connection
I have some classes that get their own database connections: from django.db import connections from psycopg2 import extensions class Foo: def __init__(self, *args, **kwargs): conn_wrapper = connections["name"] if not conn_wrapper.connection: conn_wrapper.connect() conn = conn_wrapper.connection conn.set_isolation_level(extensions.ISOLATION_LEVEL_AUTOCOMMIT) self.conn = conn The code works, but in tests, pytest-django complains that it requires the @pytest.mark.django_db decorator. The problem is that when I add this to the test class, it still complains that it requires this decorator. -
customized backend alert service for users
I was making a price comparison web app for multiple online websites. I have already made the crawler how can I make a custom alert service for multiple users so that it crawls web at regular intervals and send an alert when the price is below user specified price . how can I passively make it work even when the user in not connected ? suggesting some videos would be enough. thanks.. -
Intersection of Filter Results in Django RestFrameWork
I have created and endpoint to filter Users based on their KYC (Know Your Customer) PAN (An Identity Proof Used in India) Status. my url is as below: user-management/users/kyc/?kyc_document__document_type__verification_type=PAN&kyc_document__verification_status=VERIFIED The Models and Relations are as Below: User: The User Model Storing User Data VerificationDocuments: VERIFICATION_PENDING = "VERIFICATION_PENDING" VERIFIED = "VERIFIED" REJECTED = "REJECTED" VERIFICATION_STATUS = ( (VERIFICATION_PENDING, "Verification Pending"), (VERIFIED, "Verified"), (REJECTED, "Rejected"), ) user = models.ForeignKey( "User", related_name="kyc_document", on_delete=models.CASCADE ) document_type = models.ForeignKey( "DocumentType", related_name="document_verification", on_delete=models.CASCADE ) verification_status = models.CharField( max_length=24, choices=VERIFICATION_STATUS, default=VERIFICATION_PENDING ) DocumentType: PAN = "PAN" ADDRESS = "ADDRESS" BANK = "BANK" DEMAT = "DEMAT" VERIFICATION_TYPE = ( (PAN, "PAN Verification"), (ADDRESS, "Address Proof"), (BANK, "Bank Account Verification"), (DEMAT, "Demat Account Verification"), ) id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=64) verification_type = models.CharField(max_length=10, choices=VERIFICATION_TYPE) details = models.TextField(null=True, blank=True) def __str__(self): return self.name The View: class KYCList(generics.ListAPIView): permission_classes = () serializer_class = KYCListSerializer queryset = User.objects.all() filter_backends = [ DjangoFilterBackend, filters.SearchFilter, ] # filter_backends = (rest_framework_filters.backends.ComplexFilterBackend,) # filterset_class = UserKYCFilter filterset_fields = ( "kyc_document__document_type__verification_type", "kyc_document__document_number", "kyc_document__verification_status" ) # filter_backends = (CustomizedBackend,) search_fields = ["$first_name", "$last_name", "$mobile", "$email"] When i get the results, the output contains the details of Users , if any of the filter criteria is …