Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cannot archive a user account then got "Invalid password." error (Django GraphQL Auth)
With Django GraphQL Auth, I'm trying to archive a user account with the GraphQL below: mutation { archiveAccount( password: "test1test1", ) { success, errors } } And REQUEST HEADERS below: { "Authorization": "JWT my_jwt_access_token" } But, I got the error "Invalid password." as shown below: { "data": { "archiveAccount": { "success": false, "errors": { "password": [ { "message": "Invalid password.", "code": "invalid_password" } ] } } } } Actually, my password is correct and the account is verified and I properly set the JWT Access Token to "Authorization" in REQUEST HEADERS. Are there any ways to solve the error to archive a user account? -
Save Parent and Child in One hit to database
I have Three tables. class Parent(): pass class Child(): parent = models.ForiegnKey(Parent) class GrandChild(): child = models.ForiegnKey(Child) Now Parent can have many Childs and child have many GrandChilds, i mean 100's. Is there any way to save the Parent/Child/Grandchild at the same time ? So we get only 1 database hit and Parent/Child/Grandchild are all saved. I know there is transaction available in Django, but as per my understanding (I may be wrong) transactions are not the solution to this problem. -
Django and React: csrf cookie is not being set in request header
To explain my situation, if I logged in from backend, csrf cookie is set in cookie tab, the problem occur in frontend, if i try to login from there, csrf cookie is not in request header (being undefined), some code provided: settings.py: ALLOWED_HOSTS = ['*'] ACCESS_CONTROL_ALLOW_ORIGIN = '*' CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True ACCESS_CONTROL_ALLOW_CREDENTIALS = True ACCESS_CONTROL_ALLOW_METHODS = '*' ACCESS_CONTROL_ALLOW_HEADERS = '*' ''' SESSION_COOKIE_SECURE = True ''' CSRF_COOKIE_SAMESITE = 'None' SESSION_COOKIE_SAMESITE = 'None' CSRF_TRUSTED_ORIGINS = [ "http://127.0.0.1:3000",'http://127.0.0.1:8000','http://localhost:3000'] setting SAMESITE protocol to anything else haven't made any change in views.py, we have login view (class based): 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()) 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("Success",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 == "": return HttpResponse('Passowrd field is empty',status = 400) else: return HttpResponse("Both email and password fields are empty",status=400) in serializer.py, we got the login serializer: class LoginSerializer(serializers.Serializer): email = serializers.CharField(required=False) password = serializers.CharField(required=False,allow_null=True,allow_blank=True) in react (frontend side), here is how i am making a … -
Django instance return none from ImageField
How could I solve this problem? I want to create a model with an image and upload it to create a folder with the id of that object. When I try to upload an image in the same class I can't reference the id to add in the url. The path looks like: http://127.0.0.1:8000/media/foto_pacientes/None/image.png pacientes.models.py class Pacientes(models.Model): id = models.AutoField(primary_key=True) foto = models.ImageField(blank=True, null=True, upload_to=foto_paciente) def foto_paciente(instance,filename): print(instance) return '/'.join(['foto_pacientes', str(instance.id.id), filename]) However, when I try to upload an image using a ForeginKey I can get the desired id. As: http://127.0.0.1:8000/media/foto_pacientes/1/image.png imagens.model.py def imagens_historico(instance, filename): print(instance) return '/'.join(['historico', str(instance.id_historico.id_historico), filename]) class ImagensHistorico(models.Model): id_imagem_historico = models.AutoField(primary_key=True) imagem = models.ImageField(blank=True, null=True, upload_to=imagens_historico) id_historico = models.ForeignKey(Historicos, related_name='imagens', on_delete=models.CASCADE, blank=False, null=False) -
Getting rest_framework.exceptions.ParseError: JSON parse error - 'utf-8' codec can't decode byte 0xff in position 260: invalid start byte
I am building a rest api using django rest framework.I am making a post request through postman and passing the body as a form data as given in the below image: The code in views.py file is: def addItem(request): if request.method == "POST": items = request.body itemStream = io.BytesIO(items) dataItems = JSONParser().parse(itemStream) serializedData = MenuSerializer(data=dataItems) if serializedData.is_valid(): serializedData.save() responseMessage={'message':"Items added successfully"} return JsonResponse(responseMessage) json_data=JSONRenderer().render(serializedData.error) return HttpResponse(json_data,content_type='application/json') Code of serializer.py is: from dataclasses import fields from .models import Menu from rest_framework import serializers class MenuSerializer(serializers.ModelSerializer): class Meta: model = Menu fields = '__all__' def create(self,validated_data): return Menu.objects.create(**validated_data) Code of models.py file is: class Menu(models.Model): item_name = models.CharField(max_length=20) image = models.ImageField(upload_to="media") category = models.CharField(max_length=20) price = models.IntegerField() discount = models.IntegerField() plate_size = models.IntegerField() -
ManyToMany field returns None instead of giving me the data
I am developing a restaurant management application in django. When I am trying to print the ordered items of a customer I am getting testapp.Menu.None testapp.Menu.None Only that many to many fiedls is showing none. Other are working fine. These are my models: categories=( ('Starters','Starters'), ('Maincourse','Maincourse'), ('Breakfast','Breakfast'), ('Desserts','Desserts'), ('Beverages','Beverages') ) class Menu(models.Model): name=models.CharField(max_length=200,null=True) category=models.CharField(max_length=200,null=True,choices=categories) price=models.IntegerField(null=True) date_created=models.DateTimeField(auto_now_add=True,null=True) def __str__(self): return self.name class Customer(models.Model): name=models.CharField(max_length=200) email=models.CharField(max_length=200) phone=models.IntegerField() address=models.TextField(max_length=200) date_created=models.DateTimeField(auto_now_add=True,null=True) def __str__(self): return self.name class Orders(models.Model): status=( ('Out of delivery','Out of delivery'), ('Pending','Pending'), ('Order recieved','Order recieved'), ) customer=models.ForeignKey(Customer,null=True,on_delete=models.SET_NULL) items=models.ManyToManyField(Menu) status=models.CharField(max_length=200,choices=status) date_created=models.DateTimeField(auto_now_add=True,null=True) This is my view.py file def customer_info(request,pk): customer=Customer.objects.get(id=pk) order=customer.orders_set.all() context={ 'customer':customer, 'order':order } return render(request,'customer_info.html',context) My html file <table> <tr> {{customer.name}} <br> {% for order in order %} {{ order.items }} {% endfor %} </tr> </table> Please help me to fix this. -
how to filter a time field in a list between two times
I have created an app where an interviewer can fill out forms and schedule multiple interviews. this is the model for the schedule: class ScientificSchedule(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) start_time = models.TimeField(blank=True, null=True) end_time = models.TimeField(blank=True, null=True) date = models.DateField(blank=True, null=True) province = models.CharField(max_length=100, blank=True) and I wrote this view for it: class ScientificScheduleView(FormView): template_name = 'reg/scientific-schedule.html' form_class = ScientificScheduleForm def post(self, request): form = ScientificScheduleForm(request.POST) if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) def form_valid(self, form): form.save() return super(ScientificScheduleView, self).form_valid(form) it works fine. I want to add a statement to the form_valid function that checks if another schedule in that timespan already exists. for example imagine that this particular user has an interview from 8 a.m. to 10 a.m. He is not allowed to schedule another interview between 8 and 10. How do I make it check the user's previous interviews objects and see he is allowed to submit this form or not? I want something like this: def form_valid(self, form): if ScientificSchedule.objects.filter(user=self.request.user, province=form.instance.province, date=form.instance.date, start_time__in=[a list between two times from other interviews on that specific date]).exists(): return self.form_invalid(form) else: form.save() return super(ScientificScheduleView, self).form_valid(form) how can I filter it like this? -
Create a auto generated password field in a django model
I have a model named Customers. I want the admin to be able to add the details of each customer through admin panel. The details include username, password, company, email, etc. For password, I want to generate an auto randomly generated password field(not to be typed in admin forms), which can't be seen by admin and will be sent to the customer. I am new to Django and I can't figure out a way to do that. -
Updating chart.js with ajax
i'm trying to auto-update my chart js graph trough ajax , but my if statement always return the wrong awnser on the first iter , any idea why ? thank again. , tell me if you need anything more. setInterval(addData, 10000); //setting the loop with time interval function addData() { $.ajax({ url:'get', url: "/hello-world/", success: function(response){ let labels=String(response.labels); let datas=response.datas; console.log('check',String(label.slice(-1))); console.log('in',labels); ',myChart.data.labels.slice(-2)[1]); if (labels == String(label.slice(-1))){ console.log('same content'); }else{ console.log('updating content',labels,'to',String(label.slice(-1))); myChart.data.datasets[0].data.push(datas); myChart.data.labels.push(labels); myChart.update(); console.log('revisu',myChart.data.labels.slice(-2)[0],' : ',myChart.data.labels.slice(-2)[1]); if(myChart.data.labels.slice(-2)[0] == myChart.data.labels.slice(-2)[1]){ console.log("something's wrong"); myChart.data.labels.pop(); myChart.data.datasets[0].data.pop(); myChart.update(); }else{ }; myChart.update(); } } }); } -
How do I set up django on heroku for direct to s3 file uploads
There doesn’t seem to be any tutorials online about django direct to s3 on heroku. All tutorials are either flask or rails. I would like to know is there a tutorial or simple method for django? -
getting error {"error": "invalid_client"} when creating access token in django
I have created Application in my project and its successfully created. and I received Client ID and Client secret from this. but when I am entering command to get access token this gives me an error message {"error": "invalid_client"} I entered this command curl -X POST -d "grant_type=password&username=<user_name>&password=<password>" -u"<client_id>:<client_secret>" http://<ip_address>:<port>/o/token/ In Windows CMD using my username password. I have added this in settings.py 'oauth2_provider' in INSTALLED_APPS OAUTH2_PROVIDER = { # this is the list of available scopes 'SCOPES': {'read': 'Read scope', 'write': 'Write scope', 'groups': 'Access to your groups'} } REST_FRAMEWORK = { 'DEFAULT_FILTER_BACKENDS' : [ 'django_filters.rest_framework.DjangoFilterBackend' ], 'DEFAULT_AUTHENTICATION_CLASSES' : ('oauth2_provider.contrib.rest_framework.OAuth2Authentication',), } But still getting {"error": "invalid_client"} In CMD. Unauthorized: /o/token/ [31/May/2022 18:08:17] "POST /o/token/ HTTP/1.1" 401 27 and above error in VS code's Terminal. How I get solution of it. -
How to count products in category django
i need to show how many items in each category,like i have 3 items in category Phones and i want to do this Phones(3). I tried to to some methods in models,but it doenst work def count_products(self): return Category.objects.all().count() also tried in views.py context = super().get_context_data(**kwargs) context['grade_info'] = self.get_ordered_grade_info() context['category'] = Category.objects.count() return context -
API for admin section django rest framework
I am new to DRF hence I wish to know that: http://x.x.x.x:8000/Admin => admin interface for Django Rest Framework. can this be accessed by using API for authenticated users? -
Django-Docker-PostgreSQL multiple db
I am currently trying to figure how can I setup multiple databases by means of the docker-compose.yml. With only one db everything works well, the docker-compose.yml with one db is: version: "3.7" x-service-volumes: &service-volumes - ./:/app/:rw,cached x-database-variables: &database-variables POSTGRES_DB: postgres POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres x-app-variables: &app-variables <<: *database-variables POSTGRES_HOST: postgres services: website: image: "django_image:latest" command: python manage.py runserver 0.0.0.0:8000 volumes: *service-volumes environment: *app-variables depends_on: - postgres ports: - "8000:8000" db_migrate: image: "django_image:latest" command: python manage.py migrate volumes: *service-volumes environment: *app-variables depends_on: - postgres postgres: image: postgres:latest ports: - "5432:5432" environment: *database-variables volumes: - db-data:/var/lib/postgresql/data restart: unless-stopped pgadmin: container_name: pgadmin_container image: dpage/pgadmin4 environment: PGADMIN_DEFAULT_EMAIL: ${PGADMIN_DEFAULT_EMAIL:-admin@admin.com} PGADMIN_DEFAULT_PASSWORD: ${PGADMIN_DEFAULT_PASSWORD:-admin} PGADMIN_CONFIG_SERVER_MODE: "False" volumes: - pgadmin:/var/lib/pgadmin ports: - "${PGADMIN_PORT:-5050}:80" restart: unless-stopped volumes: db-data: pgadmin: But, when I change the docker-compose.yml with the below config and add to root dir the create-multiple-db.sh, the postgres db_migrate raises: Could not translate host name “postgres” to address: Temporary failure in name resolution The docker-compose.yml: version: "3.7" x-service-volumes: &service-volumes - ./:/app/:rw,cached x-database-variables: &database-variables POSTGRES_DB: postgres POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres x-app-variables: &app-variables <<: *database-variables POSTGRES_HOST: postgres services: website: image: "django_image:latest" container_name: django_container volumes: *service-volumes command: python manage.py runserver 0.0.0.0:8000 ports: - "8000:8000" db_migrate: image: "django_image:latest" container_name: db_migrate_container command: python manage.py migrate … -
Python Can not found - Django, runserver err
I can't run my Django project, can you help? While py can run any py file in the terminal as py_any_project_name.py, when I type py manage.py runserver or python manage.py runserver, I get python not found error. Any ideas on the cause and solution? I'm using Python 3.10 and it's attached to the environment variables as the path.. For example i create an example.py file that includes print("Example"). py example.py Example py manage.py runserver Python can not found. -
"uid":"Invalid user id or user doesn't exist."
I am sending user registration credentials via postman in my Django project as below, and this returns me 201 response code. After that I am getting this link for activation as below Now I am getting uid and token from the URL as { "uid":"NjI5NWZmYmJkZTYzNTg1MDBjM2ZjYTIy", "token":"618-673ef2e1058d5f98fe41" } You can see my POST request to activate my account as below, as you can see in above image, after sending a post request with uid and token, it says { "uid": [ "Invalid user id or user doesn't exist." ] } And also I saw many uids on google, they are only of max length of 3 letters and my uid is greater than 10 letters. Is my uid is correct ? Thanks for your time! -
Django: Seed user to database with hash of password
Is there a nice way to use django-seed to seed a database with users which have their passwords hashed. I mean following. If I run this code in Django u = User(email="fero@example.com", username="fero") u.set_password('pass') u.save() it actually adds user fero to my database with his password in hashed form, i.e., in the database I see pbkdf2_sha256$320000$3rH6NIPNFDJX928EvkV9ni$ko5dwp7d4L8qg92FwnUc3DXu61AVmBYrzy0SlQDPojY= However, if I try to populate my database using django-seed using this code from django_seed import Seed seeder = Seed.seeder() seeder.add_entity(User, 15, { 'password': 'pass' }) inserted_pks = seeder.execute() then I put to the database 15 rows, each having a value of column password equal to pass, thus, the password is not hashed. Is there any nice way to tell django-seed to hash the password before putting it to the database? Many thanks for your help! -
No module named 'account'
ModuleNotFoundError at /admin/login/ No module named 'account' I have an app called users not account. The error is only when I submit login form or go to http://localhost:8000/admin/login/ You can also view full project on https://github.com/cell20/twitter Full Traceback: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/admin/login/?next=/admin/ Django Version: 4.0.4 Python Version: 3.9.7 Installed Applications: ['users.apps.UsersConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_extensions', 'faker'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "E:\Dev\realpython\django\projects\django-social\venv\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "E:\Dev\realpython\django\projects\django-social\venv\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "E:\Dev\realpython\django\projects\django-social\venv\lib\site-packages\django\utils\decorators.py", line 46, in _wrapper return bound_method(*args, **kwargs) File "E:\Dev\realpython\django\projects\django-social\venv\lib\site-packages\django\views\decorators\cache.py", line 62, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "E:\Dev\realpython\django\projects\django-social\venv\lib\site-packages\django\contrib\admin\sites.py", line 422, in login **self.each_context(request), File "E:\Dev\realpython\django\projects\django-social\venv\lib\site-packages\django\contrib\admin\sites.py", line 337, in each_context "available_apps": self.get_app_list(request), File "E:\Dev\realpython\django\projects\django-social\venv\lib\site-packages\django\contrib\admin\sites.py", line 537, in get_app_list app_dict = self._build_app_dict(request) File "E:\Dev\realpython\django\projects\django-social\venv\lib\site-packages\django\contrib\admin\sites.py", line 477, in _build_app_dict has_module_perms = model_admin.has_module_permission(request) File "E:\Dev\realpython\django\projects\django-social\venv\lib\site-packages\django\contrib\admin\options.py", line 606, in has_module_permission return request.user.has_module_perms(self.opts.app_label) File "E:\Dev\realpython\django\projects\django-social\venv\lib\site-packages\django\contrib\auth\models.py", line 483, in has_module_perms return _user_has_module_perms(self, module) File "E:\Dev\realpython\django\projects\django-social\venv\lib\site-packages\django\contrib\auth\models.py", line 230, in _user_has_module_perms for backend in auth.get_backends(): File "E:\Dev\realpython\django\projects\django-social\venv\lib\site-packages\django\contrib\auth\__init__.py", line 38, in get_backends return _get_backends(return_tuples=False) File "E:\Dev\realpython\django\projects\django-social\venv\lib\site-packages\django\contrib\auth\__init__.py", line 27, in _get_backends backend = load_backend(backend_path) File "E:\Dev\realpython\django\projects\django-social\venv\lib\site-packages\django\contrib\auth\__init__.py", line 21, in load_backend return … -
Django email sending limit with GMAIL
I have successfully automated sending emails when a user registers my website and orders from my website. The problem is Gmail can only send 500 emails per 24 hours. That is so little when its a marketplace website. Is there a way to include two email accounts in settings.py file, so that when one email account finishes sending 500 emails the second one can start sending those emails? OR If there are other ways around this, I am thankful to all suggestions. -
How to map API using raw function in django
I want to create a search field in my Django project, but in Django document given for the database, but I want to use this for API/without using the database field Person.objects.raw('SELECT id, first_name, last_name, birth_date FROM myapp_person') Anybody could help me? How could this be for API? -
How to group by json field data in django-mongodb
Hi, Thanks in advance... I am using Django 3.0.5, Python 3.8.0, and MongoDB 5.0 My requirement: Group the data by matching the value of Width, Height, Thickness, and Type fields. While grouping the data, do the summation of Length. I tried this way list(UploadCableTrayData.objects.filter(creator_id__in=selected_users).filter(date_added__range=(selected_start_date, selected_end_date)).values( 'Thickness__value', 'Width__value', 'Height__value', 'Selection').annotate(dcount=Count(['Thickness', 'Width', 'Height']), Length=Sum('Length__value')).order_by("date_updated")) But I am getting errors like this NameError: name 'Thickness__value' is not defined Here is my model class UploadCableTrayData(BaseModel, models.Model): """ Model to store Cable Tray data """ order_upload_id = models.AutoField(primary_key=True) Order_number = jsonfield.JSONField(null=True, blank=True) Type = jsonfield.JSONField(null=True, blank=True) Selection = jsonfield.JSONField(null=True, blank=True) Height = jsonfield.JSONField(null=True, blank=True) Width = jsonfield.JSONField(null=True) Box_width = jsonfield.JSONField(null=True) Box_height = jsonfield.JSONField(null=True) Length = jsonfield.JSONField(null=True) Inner_bend1 = jsonfield.JSONField(null=True, blank=True) Inner_bend2 = jsonfield.JSONField(null=True, blank=True) Thickness = jsonfield.JSONField(null=True, blank=True) Rung_width = jsonfield.JSONField(null=True, blank=True) Rung_height = jsonfield.JSONField(null=True, blank=True) Distance_between_rungs = jsonfield.JSONField(null=True, blank=True) project = models.ForeignKey('project.Project', on_delete=models.DO_NOTHING) def __str__(self): return str(self.order_upload_id) class Meta: db_table = 'UploadCableTrayData' Data stored in the model is like this { "_id": { "$oid": "62384f772d6545101709083b" }, "order_upload_id": 4, "creator_id": 3, "updater_id": 3, "date_added": { "$date": { "$numberLong": "1647857527370" } }, "date_updated": { "$date": { "$numberLong": "1647857527370" } }, "is_deleted": false, "Order_number": { "key": "order", "value": "o1" }, "Type": { "key": "type", "value": "pct" }, … -
Reverse for 'category_list' not found. 'category_list' is not a valid view function or pattern name
i want to do pages for my categories,but when i added get_absolute_url,i got issue that url pattern is doesnt exist.I have done it with functions,and previously didnt work with classes,like ListView.And this is a little bit problem for me views.py model = Category active_tab = 'category_list' template_name = 'products/category_list.html' def get_ordered_grade_info(self): return [] def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['grade_info'] = self.get_ordered_grade_info() return context models.py name = models.CharField(_('Name'), max_length=200) slug = models.SlugField(_('Slug'), unique=True) PARAMS = Choices( ('following', 'following'), ('price_to', 'price_to'), ('price_from', 'price_from'), ) def __str__(self): return self.slug def get_absolute_url(self): return reverse('category_list', kwargs={'category_slug': self.pk}) urls.py url(r'^$', views.CategoryListView.as_view(), name='category_list') html {% block content %} <h2>Categories</h2> <div class="list-group"> {% for category in category_list %} <a href="{{ category.get_absolute_url }}" class="list-group-item"> <h4 class="list-group-item-heading">{{ category.name }}</h4> </a> {% endfor %} </div> -
External URL into a iframe to embed an external url within Django
I would like to embed a pptx that is uploaded into a folder in OneDrive within a iframe tag in a Django template. I have the urls stored in a model and saved into the SQLite database. In this sense, in the views.py file, I have the following code: context = { 'selectedunit': selectedunit, 'url_to_be_inserted': MyModel.objects.filter(unit=selectedunit) } return render(request, 'web.html', context) The code for web.html is very easy: {% extends 'base.html' %} {% load static %} {% block content %} <div class="container col-lg-8"> <div class="center"> <iframe class="center" src={{ url_to_be_inserted.url }} width="100%" height="300%" frameborder="0"/> </div> </div> {% endblock %} The result is the snapshot below: While, I would like to embed the ppt into the web site. If I directly insert the URL, instead of using the context variable, it works. That is to say: <iframe class="center" src="https://..." width="100%" height="300%" frameborder="0"/> In this case, the result is as follows (ppt embedded into the Web site): The reason why doing in this sense is because, depending on the selectedunit variable, I would like to address a different pptx with a different URL and I would like to dynamically change the pointer (as you see above by filtering the model). How could I … -
Is there a better way to dynamically change the content of a div in django othen than AJAX?
I have an HTML page with a select in a form, when I select a value and hit submit I want to load dynamically something different in the div following the select. I read that AJAX gives you this opportunity. But is there another way? Maybe something more native? -
Django-filters query params conflict
I am trying to work with filtering db by query params from the link that looks like this: {{url}}/api/books?author="XXX"&from=2003&to=2051&acquired=true I already handled author and acquired params but am stuck with from and to. My filter.py looks like this: class BookFilter(django_filters.FilterSet): author = django_filters.CharFilter(field_name="authors__fullname", lookup_expr="icontains") from = django_filters.NumberFilter(field_name="published_year", lookup_expr="gte") to = django_filters.NumberFilter(field_name="published_year", lookup_expr="lte") acquired = django_filters.BooleanFilter(field_name="acquired") class Meta: model = Book fields = [ "author", "from", "to", "acquired" ] I am looking for a way to assign these query params without overwriting key words (from and to) which is obviously a terrible idea.