Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can't get initial value as modelchoicefield in django form
I have a column list. I'm trying to update one row from that list. After i select a row, i am trying to update it. After i select a row, i get one of the parameters which is table_id. table_id is defined in model.py and forms.py . I show that table_id as modelchoicefield in djangoproject but i can't initiate my instance value as modelchoicefield. updateView.py from django.shortcuts import render,redirect,get_object_or_404 from django.urls import reverse from django.contrib import messages from Columns_definition.forms import ColumnsDefinitionsForms from Columns_definition.models import sysColumns def update_table(request,id): column_data = get_object_or_404(sysColumns, id = id) columns_form = ColumnsDefinitionsForms(request.POST or None, request.FILES or None, instance = column_data) print("Data KOLON") print(columns_form) if columns_form.is_valid(): aciklama = request.POST.get('tabloid') columns_form.save() messages.info(request, "\'" + column_data.name + "\'" + "{}".format((": is updated"))) return redirect("Columns_definition:columns_def") context = { "columns_form":columns_form, "id":id, } return render(request, 'columnsCreate.html', context) forms.py from django import forms from Columns_definition.models import sysColumns from Utilities.custom_enum import DataTypes from Table_definition.models import sysTables class ColumnsDefinitionsForms(forms.ModelForm): datatype = forms.ChoiceField(choices=DataTypes, required=False, label='Alan Veri Tipi' , widget=forms.Select(attrs={ 'placeholder': '','class':'form-control select-access-open select2-hidden-accessible popUp' })) def __init__(self, *args, **kwargs): super(ColumnsDefinitionsForms, self).__init__(*args, **kwargs) self.fields['datatype'].choices.insert(0, ('','---------' ) ) tableid = forms.ModelChoiceField(queryset=sysTables.objects.all(), empty_label=None, widget=forms.Select(attrs={ 'class': 'form-control select-access-open select2-hidden-accessible' })) class Meta: model = sysColumns fields = [ 'tableid', 'name', … -
how to delete and objects from the db without refreshing the page?
I have a page that shows every objects in the database, this is handled by an ajax function that gets a JSON file containing every objects in the db and renders out some html code for every object. There's also a classic Django ModelForm that allows the creations of new db's objects, the new objects is instantly loaded with the others. I want an html button for every objects that deletes it "on the fly", so without redirecting to a Detail Delete template. $('.remove').on('click', function() { $.ajax({ type:'DELETE' url: 'http://127.0.0.1:8000/MyApp/list-api/' + $(this).attr('data-id') } When the button is clicked it should send a DELETE request to the url of the detail api of the object. Nothing happens, no new request in the network tab of the browser. This is my index.html <body> <h2>coffee orders</h2> <ul id="orders"> </ul> <h4>Add coffee order</h4> <form method="POST" action="."> {% csrf_token %} {{form.as_p}} <button id="add-order" type="submit">Add!!!</button> </form> <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script> <script src="{% static 'MyApp/jquery_js.js' %}"></script> </body> This is my jquery.js, this function get the api and renders out the infos about the object and a delete button which doens't work. $(function (){ var $orders = $('#orders') $.ajax({ type: 'GET', url: 'http://127.0.0.1:8000/MyApp/list-api/?format=json', success: function(orders) { $.each(orders, function(i, order){ $orders.append('<li>name: … -
How to resolve a Django hstore error in tests
At some points in the app I'm collaborating on, a HStoreField is used (from django.contrib.postgres.fields). The app itself works normally, no build errors. But when I run tests, I get an issue: django.db.utils.ProgrammingError: type "hstore" does not exist From what I found, the issue is with Postgres, so I tried running the following command in psql: create extension hstore; on the template1 database. The extension now shows when listing extensions (\dx): hstore | 1.5 | public | data type for storing sets of (key, value) pairs Since the error is still here, this obviously wasn't the solution. What should I try? -
TypeError: produce() got an unexpected keyword argument 'linger_ms'
producer.produce('test msg'.encode(encoding='UTF-8'), partition_key=('{}'.format(count)) .encode(encoding='UTF-8'),timestamp=(datetime.datetime.now())+timedelta(seconds=120),linger_ms=120000) -
Unable to restrict access to the post edit screen with django
I am restricting access to the posted edit screen. I want to make sure that only the user who posted or the super user can edit the post. For that purpose, "UserPassesTestMixin" is used. However, there is no limit. And I think that my own "OnlyRecordEditMixin" is not responding. If you understand, thank you. #mixin class OnlyRecordEditMixin(UserPassesTestMixin): raise_exception = True def test_func(self): user = self.request.user id = self.kwargs['id'] print(id) return user.pk == URC.objects.get(id=id).user or user.is_superuser #view class RecordDetailEdit(UpdateView,OnlyRecordEditMixin): template_name = 'records/detail_edit.html' model = URC pk_url_kwarg = 'id' form_class = RecordDetailEditForm success_url = reverse_lazy('person:home') def get_object(self, queryset=None): obj = URC.objects.get(id=self.kwargs['id']) return obj #url path('<id>/edit/', views.RecordDetailEdit.as_view(), name='record_detail_edit'), #model class URC(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) -
Represent json data with PrimaryKeyRelatedField in django
I'm designing a mailbox with Django. My code is as follows: #models.py class Post(models.Model): text = models.CharField(max_length=256) sender = models.ForeignKey(User) receiver = models.ForeignKey(User) class Comment(models.Model): post = models.ForeignKey(Post) text = models.CharField(max_length=256) #serializers.py class CommentSerializer(serializers.ModelSerializer): post = serializers.PrimaryKeyRelatedField() class Meta: model = Comment fields = [ 'id', 'text', 'post' ] class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = [ 'id', 'text', 'sender', 'receiver', ] class MainUserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['username', 'email'] I tried to customize serializer and have a serializer as follows: class PostSerializer(serializers.Field): def to_representation(self, value): return PostSerializer(value, context={'request': self.context['request']}).data def to_internal_value(self, id): try: id = int(id) except ValueError: raise serializers.ValidationError("Id should be int.") try: post = Post.objects.get(pk=id) except User.DoesNotExist: raise serializers.ValidationError("Such a post does not exist") return user I want to represent comment objects like this { "post":{ "text" = "Hello" "sender" = 1 "receiver" = 2 } "text": "Greate" } My code works great but The problem is it doesn't show the Combo Box for selecting the post. I also tried to customize the PrimaryKeyRelatedField's to_represent method in this way: class PostSerializer(serializers.PrimaryKeyRelatedField): def to_representation(self, value): post_id = super(PostSerializer, self).to_representation(value) post = Post.objects.get(pk=user_id) return PostSerializer( user, {"context":self.context['request']} ).data but it says the unhashable type: … -
Generate kwargs for Django bootstrap_field
I'm trying to auto generate a list of fields for a Django form with the bootstrap4 package. I'm defining the kwargs in a dict, and want to loop through the fields and apply any kwargs to the bootstrap_field tag that comes with bootstrap4. Data data = [ { "name": "school_1", "args": { "show_label": True, }, }, { "name": "school_2", "args": { "show_label": False, }, }, ] Template: {% for field in form %} {% bootstrap_field field field|get_kwargs:data %} {% endfor %} Template filter: from django.template.defaulttags import register @register.filter def get_kwargs(formfield, data): item = next((item for item in data if item["name"] == formfield.name), None) if item: return item.get('args'): return None The issue is the bootstrap_field tag is using what the filter returns as an arg, not a kwarg. Is there anything I can do or do I need to replace bootstrap_field? Error render_field() takes 1 positional argument but 2 were given args (<django.forms.boundfield.BoundField object at 0x10f834240>, {'show_label': True}) kwargs {} -
Change Django admin forms according to the dropdown list value
When adding an item for a model in Django admin, is it possible to display different types of form accordingly based on the dropdown list value? For instance, I have a question model. Before adding question, admin will need to select the type of question he/she would like to add. Based on the type of question selected, it will display different fields/forms accordingly. -
How to do "Object of type StreamValue is not JSON serializable"
How to serialize StreamObject in wagtail. here i have StreamField object in my model and i want to make form for that model and want po list that model object in view. So how can i do that? -
How to display comments for users correctly?
I'm creating a blog app using Django and Python. I want users to be able to write and read comments under the posts. I've already created models.py, forms.py and views.py but I still have a problem with dispaying those comments. The user can write comments, but they are not dispayed under the post. However, I can see all those comments from admin page. I guess this problem is because of my templates. Could you help me please? What is wrong in my code? Thank you in advance! models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='commens') author = models.CharField(max_length=100, default='') text = models.TextField() created_date = models.DateTimeField(default=timezone.now) approved_comment = models.BooleanField(default=False) def approve(self): self.approved_comment = True self.save() def __str__(self): return self.text views.py from django.shortcuts import render, get_object_or_404, redirect from django.http import HttpResponse from .models importPos, Comment from django.contrib.auth.models import User from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from .forms import CommentForm from django.contrib.auth.decorators import login_required def add_comment_to_post(request, pk): post = get_object_or_404(Post, pk=pk) if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.save() return redirect('post-detail', pk=post.pk) else: form = CommentForm() return render(request, 'blog/add_comment_to_post.html', {'form': … -
Use data from a REST API that requires oAuth login, but that do not provide an authorization point
I'm not sure if my title makes sense, so here is the situation: I use a custom CRM (built with Django) on which I login with oAuth2 I want to extract the data from this app in order to display some statistics, or custom reports. Once I'm logged in, I can access the data with a JSON format just by adding a parameter such as http://example.com/backend/client/445/?format=json. As far as I know, there is no authorization point which could deliver a token for me to use in my app with an xhr request. Also, if I understand correctly, in any case, the CORS policy won't allow me to perform an xhr request. For the moment, I simply copy and paste the Json in my app but there is obviously a better way to do this, hence my question: As I am logged in on the CRM app in another tab, is there any way I can perform an Ajax request by leveraging the fact that I am logged in on this other tab ? I'm very new with all of this, so please let me know if I can give more informations. Thanks! -
How to add User registration data in admin after email confirmation?
Whenever someone new registers himself in my site, an email confirmation send to him. But before confirmation, his user information is adding in admin User page. I want it to add it in admin Users after confirmation not before. How to solve this problem? I didn't have models.py set because it is present {{forms}} in html page. forms.py class UserRegisterForm(UserCreationForm): email = forms.EmailField(required=True)._unique = True class Meta: model = User fields = ['username','email','password1','password2'] views.py def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False user.save() current_site = get_current_site(request) mail_subject = 'Activate your Account.' message = render_to_string('users/active_email.html', { 'user': user, 'domain': current_site.domain, 'uid':urlsafe_base64_encode(force_bytes(user.pk)), 'token':account_activation_token.make_token(user), }) to_email = form.cleaned_data.get('email') email = EmailMessage( mail_subject, message, to=[to_email] ) email.send() return render(request, 'users/confirm_email.html') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form': form}) def activate(request, uidb64, token): try: uid = force_text(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except(TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): user.is_active = False user.save() return render(request, 'users/confirmed_email.html') return HttpResponse('Activation link is invalid!') tokens.py from django.contrib.auth.tokens import PasswordResetTokenGenerator from django.utils import six class TokenGenerator(PasswordResetTokenGenerator): def _make_hash_value(self, user, timestamp): return ( six.text_type(user.pk) + six.text_type(timestamp) + six.text_type(user.is_active) ) account_activation_token = TokenGenerator() -
Can't access smtp.gmail.com in virtualbox ubuntu18.04
I'm learning linux and Django with a Django project, developing in Ubuntu 18.04 installed in Virtualbox. The host machine is Windows 10 and the VM internet is NAT, which cannot be changed due to the internet of my office. And the problem is that, sending verify email for signup failed with OSError. I used smtp.gmail.com as email server and set all needed variables like host, user, pass, .etc And I don't think that's the problem. Then I tried telnet smtp.gmail.com port with port set to 465 and 587, and after a while, telnet just reported cannot connect. It seems that the out going port is blocked or something but changing iptables didn't fix this neither. So I think that maybe the Virtualbox internet settings caused this, but have no idea what to set or change. I would like to know is there anything I can try with the Virtualbox settings? Or maybe something else caused this? I'll fill more information if needed. Please help me out!! -
How to differentiate the answers of the different forms?
There is a page on which I display multiple forms, however I haven't found a way to get the result of the different forms separated. Here's the form class I am using: class QuestionnaireForm(forms.Form): def __init__(self, *args, **kwargs): extra = kwargs.pop('extra') super(QuestionnaireForm, self).__init__(*args, **kwargs) for i in range(len(extra)): self.fields[extra[i]['output']] = forms.IntegerField(label=extra[i]['question']) Here's the view, I basically loop over every of my activities and create a custom form however I am unable to identify what answer belong to which activity. class Questionnaire(TemplateView): template_name = 'blog/questionnaire.html' context = {'title': 'Questionnaire page'} def get(self, request): def create_questionnaires(activities): questionnaires = [] for activity in activities: output_list, activity = match_activity_and_subactivities_with_outputs(activity) questionnaires.append({'activity':activity['activity'], 'questionnaire':QuestionnaireForm(None, extra=output_list)}) return questionnaires, activities self.context['form_quest'], request.session['activities'] = create_questionnaires(request.session['activities']) return render(request,self.template_name, self.context) def post(self,request): output_list = request.session['output_list'] form_quest = QuestionnaireForm(request.POST, extra = output_list) if form_quest.is_valid(): request.session['outputs_inputs'] = [] for i in range(len(output_list)): output_list[i]['input']= form_quest.cleaned_data[output_list[i]['output']] request.session['outputs_inputs'].append([output_list[i]['output'],form_quest.cleaned_data[output_list[i]['output']]]) return redirect('/report', self.context) The questionnaire page: {% extends "blog/index.html" %} {% block content %} <h1>Questionnaire page</h1> <form method="post"> {% csrf_token %} {% for object in form_quest %} {% if object.questionnaire %} <h2> {{ object.activity }} </h2> {{ object.questionnaire.as_ul}} {% endif %} {% endfor %} <button type="submit">Submit</button> </form> <p> {{ context }} </p> {% endblock content %} As of now … -
How to create the django rest auth social login?
I have been trying to create a social login in django-rest-framework using django-rest-auth, but could not able to do it properly. I am a noob in these technologies and wants to create API for social login. Need Help in this. I have tried all the tutorials that are at the top in google search but they are incomplete or hard to understand. -
Process title for WSGI in apache
I have an apache web server, which starts a django server as a vhost. I'd like to name this subprocess and I've tried the parameter "display-name" of WSGIDaemonProcess. Unfortunately, I get the following error as soon as I start apache: Invalid command 'WSGIDaemonProcess', perhaps misspelled or defined by a module not included in the server configuration Do I need to include another module than mod_wsgi and mod_alias module? Apache starts if I remove the WSGIDeamonProcess line and it works perfectly. This is my vhost.conf <VirtualHost *:80> ServerName http://localhost ServerAdmin admin@example.com RewriteEngine On RewriteCond %{HTTPS} !=on RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] </VirtualHost> <VirtualHost *:443> SSLEngine on SSLCertificateFile "${INSTALLDIR}/cert/localhost.pem" SSLCertificateKeyFile "${INSTALLDIR}/cert/localhost.key" ServerName https://localhost ServerAdmin admin@example.com DocumentRoot "${INSTALLDIR}/client" DirectoryIndex index.html index.htm index.php index.php4 index.php5 <Directory "${INSTALLDIR}/client"> Options Indexes FollowSymLinks AllowOverride None Require all granted </Directory> # wsgi python backend WSGIDaemonProcess webapp display-name=django-myapp WSGIScriptAlias /api2 "${INSTALLDIR}/webapp/api/wsgi.py" WSGIProcessGroup webapp WSGIPassAuthorization On <Directory "${INSTALLDIR}/webapp/api"> <Files wsgi.py> Require all granted </Files> </Directory> ErrorLog "${SRVROOT}/logs/error.apache.log" ErrorDocument 404 /404.html </VirtualHost> Does anybody has a solution how I can name the subprocess? -
Can't Deploy Mezzanine CMS using Apache/Ubuntu
I'm trying to become better with deploying a website from scratch so I setup a new Nanode from Linode using the latest Ubuntu (19.04 I think). I followed the instructions to install Mezzanine CMS (Django Based) and it all went fine, I was able to run the dev server to test the website fine on port 8000. I did install UFW and right now only activity on port 80 is not rejected. Also I have mysql database running with Mezzanine not Djangos default SQLlite. I installed Apache and WSGI. At first Apache would not restart due to some configuration issue which I think I've since worked out. I have a domain alexmerced which is on godaddy, but I have a DNS "a" records which is pointing to my linodes IP address "mezz.alexmerced.com" Mezzanine is still a fresh install so I haven't really changed anything outside of the WSGI and settings.py. I currently get a forbidden error when I type the URL or IP address, the permissions of the application directory is 755. below are my configuration file settings to see if I made any mistakes. django_project.conf (the only conf file enabled in the /sites-available/ directory <VirtualHost *:80> ServerName mezz.alexmerced.com ServerAdmin … -
Django union of two querysets does not work with annotated value
I'm trying to do a union of two querysets with shared fields. This works: fields = ['id', 'date_trans', 'total', 'allocated', 'balance'] qs1 = Order.objects.values_list(*fields) qs2 = OnAccount.objects.values_list(*fields) return qs1.union(qs2) The Order model has a CharField called num_invoice which I'd like to include as a field in the union. This field doesn't exist in the OnAccount model so in order to include it in the values_list() I'm using an annotation. The annotation works fine but the union causes an error: django.db.utils.ProgrammingError: UNION types character varying and date cannot be matched Here's my annotation: from django.db.models import CharField, Values as V from django.db.models.functions import Concat fields = ['id', 'num_invoice', 'date_trans', 'total', 'allocated', 'balance'] qs1 = Order.objects.values_list(*fields) qs2 = ( OnAccount.objects .annotate(num_invoice=Concat(V('OA-'), 'id', output_field=CharField())) .values_list(*fields) ) return qs1.union(qs2) -
Adding extra fields to django InlineFormSet
Suppose I have 3 models: Chess Player Tournament Participation "Participation" is a junction table of two others. I use the following InlineFormSet in admin panel in order to show some fields from Participation model. from .models import Participation class ParticipationInline(admin.TabularInline): model = Participation formset = ParticipationAdminFormset class BaseParticipationAdminFormset(BaseInlineFormSet): def clean(self): # Some code # ... def _construct_form(self, i, **kwargs): # Some code # ... ParticipationAdminFormset = inlineformset_factory( Tournament, Participation, formset=BaseParticipationAdminFormset, fields="__all__" ) The Question: How can I include any fields from "Chess_Player" model, e.g. "first_name", into the FormSet above? -
Triggering POST request from django template
I am listing transfers from json response and viewing it in template: views.py def transfers_cft(request, host_id): hostname = Host.objects.get(pk=(host_id)) abc = "List idf or idt:" leave_empty = "(leave empty to list all | use * as string filler)" if request.method == 'POST': form = TransferForm(request.POST) if form.is_valid(): response = requests.get( 'https://{}:9999/api/transfers?fields=PART%2CIDF%2CIDT%2CIDTU%2C&limit=100'.format(hostname), verify='/cert/cacerts.pem', headers={'Accept': 'application/json', 'Authorization': 'Basic xxxxxxxxxxxxxxxxxxxx'}, ).json() arr = [] for key in response['transfers']: arr.append(key) context = {'response': response, 'hostname': hostname, 'host_id': host_id, 'arr': arr} return render(request, 'app/json_nest_transfer.html', context) else: form = TransferForm() context = {'form': form, 'abc': abc, 'leave_empty': leave_empty, 'hostname': hostname,'host_id': host_id} return render(request, 'app/message.html', context) json_nest_transfer.html [...] <div class="row m-2"> <div style="width: 100px;"><b>idf:</b></div> <div style="width: 100px;"><b>idtu:</b></div> {% if response %} {% for key in arr %} <div class="border w-100"></div> <div style="width: 100px;">{{ key.idf }}</div> <div style="width: 100px;">{{ key.idtu }}</div> {% endfor %} </div> <hr> {% else %} <p>No IDs are available.</p> {% endif %} [...] now, i would like to place near every <div style="width: 100px;">{{ key.idtu }}</div> "restart" button which would take key.idtu and execute following POST request: 'https://{}:9999/api/transfers/**key.idtu**/start'.format(hostname), verify='/cert/cacerts.pem', headers={'accept': 'application/json', 'authorization': 'Basic xxxxxxxxxxxxxxxxxxxxxx'}, ) probably the best way would be to run new view somehow? but after click to end up with refreshed … -
css files are loading properly in django but no styling is visible on webpage
I have checked all the settings for django. CSS is loaded properly but no styling is visible on web page. I stopped the server and made changes and start it again, but it didn,t work.enter image description here -
'42S02', "[42S02] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Invalid object name django
I am trying to make access a table in my database but this error always occurs although a tried to access another table in the same schema and it worked PS: When I inspected the database a model of the table that I want was not created so I manually inspected it using python manage.py tableName --databse=DataAdmin > model.py it worked but the problem was not solved class Rfde2003Syd0827(models.Model): pe = models.CharField(db_column='PE', max_length=30, blank=True, null=True) # Field name made lowercase. pe_physical_interface = models.CharField(db_column='PE_PHYSICAL_INTERFACE', max_length=30, blank=True, null=True) # Field name made lowercase. pe_channel_interface = models.IntegerField(db_column='PE_CHANNEL_INTERFACE', blank=True, null=True) # Field name made lowercase. ts_usid = models.CharField(db_column='TS_USID', max_length=30, blank=True, null=True) # Field name made lowercase. ts_dna = models.IntegerField(db_column='TS_DNA', blank=True, null=True) # Field name made lowercase. new_pe = models.CharField(db_column='NEW_PE', max_length=30, blank=True, null=True) # Field name made lowercase. new_pe_physical_interface = models.CharField(db_column='NEW_PE_PHYSICAL_INTERFACE', max_length=30, blank=True, null=True) # Field name made lowercase. class Meta: managed = False db_table = 'RFDE2003SYD0827' -
Display image in dropdown list in django
I am bigenner to django ,I work on project that let user to rate countries in dropdown list, How I can display flag of each country in dropdown list of countries in django ? -
Dynamic linear interpolation between multiple HTML input field values with JavaScript
I'm trying to make a dynamically generated array of input fields where only the first and the last are editable. When either of the border fields are modified, the remaining should update their values by linearly interpolating between the two border values. Example below. I have written a (Django/Bootstrap) HTML template which generates the input fields themselves, and leaves only the border fields editable and assigns "-first" and "-last" id extensions. I have also written a basic JavaScript which takes two input values to interpolate between and output array size. This is how the input fields are instantiated. I started writing a JS function "change_values()" which would be activated on onchange event, but got nowhere. <div class="custom-control custom-linspace-field"> <div class="row" id="linspace-field"> {% for field in fields %} <div class="col p-1"> {% if forloop.first %} <input type="text" class="form-control" onchange="change_values()" id="linspace-field-first" value="{{ field | floatformat:3 }}" placeholder="min"> {% elif forloop.last %} <input type="text" class="form-control" onchange="change_values()" id="linspace-field-last" value="{{ field | floatformat:3 }}" placeholder="max"> {% else %} <input type="text" class="form-control" onchange="change_values()" id="linspace-field" value="{{ field | floatformat:3 }}" readonly> {% endif %} </div> {% endfor %} </div> </div> This is my linear interpolation JS script: function lerp(value1, value2, amount) { step = (value2 - value1) … -
DRF filter self foreign key
I have model as follows: class Category(models.Model): name = models.CharField(max_length=100) slug = models.SlugField(max_length=100, unique=True, blank=True) parent = models.ForeignKey('self', on_delete=models.SET_NULL, null=True, blank=True) and I have to filter according to parent my view looks like this class CategoryView(generics.ListCreateAPIView): queryset = Category.objects.all() serializer_class = CategorySerializer lookup_field = 'slug' name = 'category-list' filter_fields = ('name', 'parent_id') search_fields = ('^name',) ordering_fields = ('name',) as it can be seen from the view in filter_fields there is parent_id but it does not work if I select parent it returns nothing except [ ]. If I write get_queryset() def get_queryset(self): return Category.objects.filter( Q(parent_id=1) ) it returns objects whose id is 1. But I do not need to write id in numbers because in front end id can be in any number like 1, 2, 3, ... etc it should detect automatically that's why it should filter by id. Now I have no idea how to do it. Any idea please? Thanks in advance!