Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Docker replicas vs gunicorn workers in production
Do we need gunicorn or uwsgi workers when we have docker replicas? What is the best solution, make guincorn worker and replicate it on docker, or make multiple gunicorn workers? -
Insert large csv to MySQL, ignore lines with unknown characters
I have a large .csv that I'm trying to import into a MySQL database for a Django project. I'm using the django.db library to write raw sql statements such as: LOAD DATA LOCAL INFILE 'file.csv'... However, I keep getting the following error: django.db.utils.OperationalError: (1300, "Hey! Are you out tonight?") After grepping the .csv for the line, I realised that the error is being caused by this character: 😜; though I'm sure there will be other characters throwing that error after I fix this. Running: $ file --mime file.csv from a terminal, returns: $ file.csv: text/html; charset=us-ascii Since the rest of my db is in UTF-8, I tried writing a python script to re-encode it, using .encode('utf-8', 'ignore') hoping that the 'ignore' would remove any symbols that gave it trouble, but it threw: UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 825410: invalid continuation byte The thing is, I don't actually care about inserting 100% of the file into my db. I would rather just insert only the 'safe' lines that don't contain strange characters. So ideally, I'm looking for a way to modify my LOAD DATA LOCAL INFILE sql statement so it just skips inserting any lines that give … -
What is the best way to handle multiple user requests when lot of back end calculation is involved?
Hi I am quite new to web application development. I have been designing an application where a user uploads a file and some calculation is done and an output table will be shown. This process takes approximately 5-6 seconds. I am saving my data in sessions like this request.session ['data']=resultDATA. And loading the data whenever I need from sessions like this resultDATA = request.session['data']. I dont need DATA once the user is signed out. So is approach correct to save user data (not involving passwords) ? And my biggest problem is if n no. Of users upload their files at exact moment do the last user have to wait for n*6 seconds for his calculation to complete? If yes is there any solution for this? Right now I am using django built-in web server. Do I have to use a different server to solve this problem ? -
Does Django always work with mod_wsgi?
Installed Django 1.10, pip install Django==1.10 Question: Without installing mod_wsgi apache2 module(sudo aptitude install libapache2-mod-wsgi), To process http requests, what is the interface used by Django to work with Apache2 http server? -
Connecting django signal handlers in tests
Using django-cacheops, I want to test that my views are getting cached as I intend them to be. In my test case I'm connecting cacheops cache_read signal to a handler that should increment a value in the cache for hits or misses. However, the signal is never fired. Does anyone know the correct way to connect a django signal handler in a testcase, purely for use in that testcase? here's what I have so far from cacheops.signals import cache_read cache.set('test_cache_hits', 0) cache.set('test_cache_misses', 0) def cache_log(sender, func, hit, **kwargs): # never called if hit: cache.incr('test_cache_hits') else: cache.incr('test_cache_misses') class BootstrapTests(TestCase): @classmethod def setUpClass(cls): super(BootstrapTests, cls).setUpClass() cache_read.connect(cache_log) assert cache_read.has_listeners() def test_something_that_should_fill_and_retrieve_cache(self): .... hits = cache.get('test_cache_hits') # always 0 I've also tried connecting the signal handler at the module level, and in the regular testcase setUp method, all with the same result. -
How to get HTML filed value without using form using Django and Python
I need one help . I need to get all html field value when user will click on different button in views.py file using Django and Python. I am explaining my code below. <div class="boxwidthinnerdiv"> Nuclear Mini Plant<br /><br /> <select> <option>Reactor 1</option> <option>Reactor 2</option> <option>Reactor 3</option> </select> <br /><br /><br /><br /> <a href="{% url 'start' %}"><button class="buttondiv" type="button">Start</button></a> <a href="{% url 'shut' %}"><button class="buttondiv">Shut Down</button></a> <a href="{% url 'suspend' %}"><button class="buttondiv">Suspend</button></a> </div> Here when user will click on start button the select field value should get in views.py file which is given below. def start(request): status = 1 def shut(request): status = 0 def suspend(request): status = 2 Here inside each action I need to get the select field selected value. Please help me. -
How do I use an existing view with reverse()?
I created a view that handle POST. I'm trying to use reverse to create a view that uses this view to process multiple jobs. I get the following error message: django.core.urlresolvers.NoReverseMatch: Reverse for 'release_action' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [] View code that handles POST requests. class ReleaseActionView(APIView): authentication_classes = (SessionAuthentication,) permission_classes = (IsAuthenticated, IsAdminUser) def post(self, request, release_id, *args, **kwargs): ... return Response(...) I wrote the code in reverse () to run the above code in the for loop. I get an error message. What is the problem? Here is for-loop code class ReleaseBulkActionView(APIView): def post(self, request, *args, **kwargs): ... for release in releases: ... HttpResponseRedirect(reverse('release_action', args=(), kwargs={})) Urls.py looks like this: url(r'^releases/(?P<release_id>[0-9]+)/actions/?$', ReleaseActionView.as_view(), name="release_action") -
Django image upload issue
I'm trying to upload an image for the user's profile. But I don't know if I am on the right way or not. {{avatar}} on the template return None. My view : def view_avatar(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): avatar = form.cleaned_data['avatar'] else: form = UploadFileForm() return render(request, 'avatar.html', locals()) My form : class UploadFileForm(forms.Form): class Meta: model = Profile fields = ('avatar', ) def __init__(self, *args, **kwargs): super(UploadFileForm, self).__init__(*args, **kwargs) self.fields['avatar'].required = False avatar = forms.FileField() My model : class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) birthdate = models.DateField(null=True, blank=True) avatar = models.ImageField(upload_to='media/avatar/%y/%m/%d', blank=True, null=True) -
Django social_django query to table
It is necessary to receive a line from the table social_auth_usersocialauth which is in the database. The table was created by social_django. Tried from social_django.models import social_auth_usersocialauth but so does not find the table. How do I refer to the table social_auth_usersocialauth -
How to create a superuser in Django with Linux shell script?
Recently,I'm tring to deploy an application with docker.I get a problem about how to write a start script which will execute on Linux. An example is as fellow: Usually,we create super user like this: iMac:mysite yetongxue$ python manage.py createsuperuser Username (leave blank to use 'yetongxue'): root Email address: example@qq.com Password: Password (again): Superuser created successfully. But when deploy application with docker,I must write this command in a script which will execute after the docker container start.How can I set the username ,email and password in the script? Thanks! #!/bin/bash python manage.py createsuperuser -
Python - Error: object is not iterable
I've been struggling with this issue for 2 days now. I've also read the other questions with the same issue but those solutions didn't work for me. This is my code models.py from django.db import models from urllib.request import urlopen, Request import requests import csv from pprint import pprint url = 'LINK WITH THE CSV FILE I NEED TO GET' class Items(models.Model): name = models.CharField(max_length=250) description = models.CharField(max_length=250) image = models.CharField(max_length=250) class Item(models.Model): items = models.ForeignKey(Items, on_delete=models.CASCADE) file_type = models.CharField(max_length=10) templates/index.html <body> <h1>Item list</h1> <div class="items"> {% for items in response %} <div class="item"> {% if item.image %} <img src="{{ item.image }}"> {% else %} <p class="error">Your image url is not valid</p> {% endif %} {% if item.name %} <h3>{{ item.name }}</h3> {% else %} <h3>Untitled item</h3> {% endif %} {% if item.description %} <p>{{ item.description }}</p> {% else %} <p <p class="error">Description missing</p> {% endif %} </div> {% endfor %} </div> </body> I'm getting this error message: Error during template rendering In template /Users/z/Desktop/python3env/elements_csv_reader/csv_reader/templates/index.html, error at line 11 'Items' object is not iterable A solution for this issue would be appreciated greatly. It really would. Thanks in advance. -
Creating a Gin Index with Trigram (gin_trgm_ops) in Django model
The new TrigramSimilarity feature of the django.contrib.postgres was great for a problem i had. I use it for a search bar to find hard to spell latin names. The problem is that there are over 2 million names, and the search takes longer then i want. I like to create a index on the trigrams as descibed in the postgres documentation https://www.postgresql.org/docs/9.6/static/pgtrgm.html But i am not sure how to do this in a way that the Django API makes use of it. For the postgres text search there is a discription on how to create a index. But not for the trigram similarety. https://docs.djangoproject.com/en/1.11/ref/contrib/postgres/search/#performance This is what i have right now: class NCBI_names(models.Model): tax_id = models.ForeignKey(NCBI_nodes, on_delete=models.CASCADE, default = 0) name_txt = models.CharField(max_length=255, default = '') name_class = models.CharField(max_length=32, db_index=True, default = '') class Meta: indexes = [GinIndex(fields=['name_txt'])] and then in the vieuw's get_queryset i do: result = result.annotate(similarity=TrigramSimilarity('name_txt', query)).filter(similarity__gt=0.3).order_by('-similarity') -
How to handle token when UPDATE USERNAME_FIELD with Django REST Framework
I am developing applications using Django REST Framework and Angular 4. I do not know the treatment of token when UPDATE login user information. The user model of Django is customized as follows. Login key is changed from username to email. [models.py] class Account(AbstractBaseUser): username = models.CharField(_('username'), max_length=30, unique=True) first_name = models.CharField(_('first name'), max_length=30, blank=True) last_name = models.CharField(_('last name'), max_length=30, blank=True) email = models.EmailField(verbose_name='email address', max_length=255, unique=True) profile = models.CharField(_('profile'), max_length=255, blank=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) date_joined = models.DateTimeField(_('date joined'), default=timezone.now) objects = AccountManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] def user_has_perm(user, perm, obj): return _user_has_perm(user, perm, obj) def has_perm(self, perm, obj=None): return _user_has_perm(self, perm, obj=obj) def has_module_perms(self, app_label): return self.is_admin def get_short_name(self): return self.first_name @property def is_superuser(self): return self.is_admin class Meta: db_table = 'api_user' swappable = 'AUTH_USER_MODEL' The function to UPDATE user information from Angular 4 is implemented as follows. New user information is put in Django REST Framework with function updateUserInfo. [component.ts] updateUserInfo() { this.authService.updateUserInfo({ email: this.editUserEmail, username: this.editUserName, profile: this.edtiUserProfile }) .subscribe( data => { this.updateSuccessMessage = "success userinfo update"; this.updateErrorMessage = null; this.authService.userInfo; }, error => { this.updateErrorMessage = "failed userinfo update"; this.updateSuccessMessage = null; } ); } [service.ts] updateUserInfo(userUpdateInfo) { … -
updating unique field values django creates a new row
I have a model which has a field with unique constraint. When I try to update the unique field value, a new row is created instead of updating the old one. Did refer to few other queries but couldnt find a solution. Below is my model : class AircraftType(models.Model): aircraft_id = models.AutoField(null=False, primary_key=True) aircraft_type = models.CharField(max_length=20, null=False, blank=False, unique=True) aircraft_description = models.TextField() and my views.py : def save_aircrafts(request): print "save_aircrafts" aircraft_type = request.POST.get('aircrafttype') print str("Save aircraft_type ") + aircraft_type aircraft_instance = AircraftType.objects.filter(aircraft_type=aircraft_type) if aircraft_instance.exists(): print str("aircraft_instance.exists") + aircraft_type aircraft_instance.update(aircraft_type=aircraft_type) aircraft_instance.aircraft_type = aircraft_type aircraft_instance.save() else: print str("aircraft_instance.NOTexists") + aircraft_type AircraftType.objects.create(aircraft_type=aircraft_type) return redirect('aircraft_list') I am calling my save_aircrafts method from my html file. -
.How to upload file by help of path name using Django and Python
I need one help. I need to upload file into some folder inside the project using the path instead of browse from folder using Dajngo and Python. I am explaining the scenario below. <form method="post" action="{% url 'upload' %}"> <input name="name" type="text"> <button type="submit">Upload</button> </form> suppose here user paste one file path name e.g-/home/subrajyoti/Pictures/abc.pdf,.png etc and click on upload button in this case I need to remove the original file name with one time stamp and save this file into project folder and path into db. Please help. -
django resend request.FILES by requests failed
i have some trouble. there is a demand: first step: i get file from request.FILES like this image = request.FILES.get('image') and image's type is 'django.core.files.uploadedfile.InMemoryUploadedFile' then. i need use the image to send to third party. i try this by using requests. at the same time, i need post some other data. suppose the url:url = http://example data = {'a': b,'c': d} and i post the request use response = requests.post(url, data=data) but i don't how to post the file? i have tried this way: data = {'a': b, 'c': d, 'image'(this field name is require by third party): image} and this way: data = {'a': b, 'c': d, 'image': image.read()} or this way files = {'image': image} requests.post(url, data=data, files=files) but all failed.(response hint me no image) by the way, the third party need image's type is binary or base64 how can i solve the problem? -
NoneType object is not callable when trying to save instance of Model
I am using Django to perform a very simple function. The application will grow in size as time goes on, but for now, all I want to do is run through an html document of all my Facebook messages, and save a model for every user, and every message attached to that user. However when trying to create an instance of a model I created, FacebookUser, I get the error "NoneType" object is not callable. I read other SO articles, and browsed the internet for other issues, and found that the error usually stemmed from trying to do something with the class itself, and not an instantiation of the class. However I am creating an instance of this class, and still getting this error. models.py from django.db import models class FacebookUser(models.Model): full_name = models.CharField(max_length=255, null=True, blank=True) def __str__(self): return self.full_name class Message(models.Model): user = models.ForeignKey(FacebookUser) content = models.TextField(max_length=10000, null=True, blank=True) date_sent = models.DateTimeField(null=True, blank=True) def __str__(self): return '#{} {}'.format(self.id, self.user.full_name) views.py from django.http import HttpResponse from facebook_user.models import FacebookUser, Message from bs4 import BeautifulSoup def save_messages(request): data = open('messages.html', 'r').read() soup = BeautifulSoup(data) all_messages = soup.findAll("div", {"class": "message"}) msg_dictionaries = [{ 'user': el.findAll('span')[0], 'time': el.findAll('span')[1], 'content': el.nextSibling.nextSibling } for el … -
Delete record in Django db with ajax
I must delete record from Django db use Jquery/Ajax. Can you help me? django /views function def owner(request, identifer): x = get_object_or_404() if request.method == "DELETE": x.objects.delete() ajax code here: $(document).ready(function() { $(".delete").click(function(){ var id_number = this.id; alert(id_number); $.ajax({ type: 'DELETE', url: 'owner/{item.id}/', data: 'identifer='+id_number, success: function(){ if(data) {alert("Success!")} } }); -
setup gunicorn to run with systemd
Trying to setup gunicorn to run with systemd the control file is sudo nano /etc/systemd/system/gunicorn.service and the output for testing is root@samuel-pc:~# systemctl start gunicorn Failed to start gunicorn.service: Unit gunicorn.service is not loaded properly: Invalid argument. See system logs and 'systemctl status gunicorn.service' for details. root@samuel-pc:~# systemctl status gunicorn.service ● gunicorn.service - gunicorn daemon Loaded: error (Reason: Invalid argument) Active: inactive (dead) Jun 29 05:13:17 samuel-pc systemd[1]: [/etc/systemd/system/gunicorn.service:9] Executable path is not absolute, ignoring: gunicorn --access-logfile - --workers 3 --bind unix:/root/revamp/revamp Jun 29 05:13:17 samuel-pc systemd[1]: gunicorn.service: Service lacks both ExecStart= and ExecStop= setting. Refusing. Jun 29 05:13:29 samuel-pc systemd[1]: [/etc/systemd/system/gunicorn.service:9] Executable path is not absolute, ignoring: gunicorn --access-logfile - --workers 3 --bind unix:/root/revamp/revamp Jun 29 05:13:29 samuel-pc systemd[1]: gunicorn.service: Service lacks both ExecStart= and ExecStop= setting. Refusing. Jun 29 05:15:45 samuel-pc systemd[1]: [/etc/systemd/system/gunicorn.service:9] Executable path is not absolute, ignoring: gunicorn --access-logfile - --workers 3 --bind unix:/root/revamp/revamp Jun 29 05:15:45 samuel-pc systemd[1]: gunicorn.service: Service lacks both ExecStart= and ExecStop= setting. Refusing. Jun 29 07:01:10 samuel-pc systemd[1]: [/etc/systemd/system/gunicorn.service:9] Executable path is not absolute, ignoring: gunicorn --access-logfile - --workers 3 --bind unix:/root/revamp/revamp Jun 29 07:01:10 samuel-pc systemd[1]: gunicorn.service: Service lacks both ExecStart= and ExecStop= setting. Refusing. Jun 29 07:01:55 samuel-pc systemd[1]: … -
Schemamigration runs for existing columns in the application
Assume I am having a Django app named animals. The app has a model named "mammal" as below class Mammal(models.Model) name = models.CharField(max_length=256) is_active = models.BooleanField(default=True) date_added = models.DateTimeField(auto_now_add=True) date_modified = models.DateTimeField(auto_now=True) I run a schema migration for the above model ./manage.py schemamigration mammal --initial An initial migration file gets created and then I migrate it as follows ./manage.py migrate mammal Now I update the model and add a field mammal_type as below class Mammal(models.Model) name = models.CharField(max_length=256) mammal_type = models.CharField(max_length=63, choices=TYPE_CHOICES, default=TYPE_MAMMAL) is_active = models.BooleanField(default=True) date_added = models.DateTimeField(auto_now_add=True) date_modified = models.DateTimeField(auto_now=True) I again run a schema migration for the above model ./manage.py schemamigration mammal --auto ./manage.py migrate mammal Everything goes fine. Now comes the issue. I add another field extinct as below class Mammal(models.Model) name = models.CharField(max_length=256) mammal_type = models.CharField(max_length=63, choices=TYPE_CHOICES, default=TYPE_MAMMAL) extinct = models.BooleanField(default=False) is_active = models.BooleanField(default=True) date_added = models.DateTimeField(auto_now_add=True) date_modified = models.DateTimeField(auto_now=True) I run a schema migration ./manage.py schemamigration mammal --auto The new migration file contains schema migration for previously added mammal_type field which actually should not be present. I am not sure why this happens. I have tried running field specific schema migrations which allows me to add migrations for just that field, but when it … -
django rest auth returns AnonymousUser
I am using django, drf and django-rest-auth. I send token from frontend in request header {'Authorization': 'Token {$Token}'} But this request seems like unauthorized. I want to get users information like: def get_user_info(request): user = request.user but it returns me AnonymousUser My settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'core', 'rest_framework', 'rest_framework.authtoken', 'rest_auth', 'account', 'corsheaders' ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication' ), 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ], 'UNICODE_JSON': True, 'PAGE_SIZE': 0 } -
Permissions socket mod_wsgi in Cpanel Unable to connect
I'm trying deploy django with mod_wsgi in Cpanel but I'm receiving an error with socket permissions. [Thu Jun 29 01:17:11.166689 2017] [wsgi:error] [pid 12314] (13)Permission denied: [client 189.31.25.75:59376] mod_wsgi (pid=12314): Unable to connect to WSGI daemon process 'brunamaiahair.com.br' on '/var/run/apache2/wsgi.12082.2.1.sock' as user with uid=1013. In other question Unable connect mod_wsgi I follow somethings steps do setup mod_wsgi but not work Here is my config after changes: 1 - I created /etc/httpd/conf.d/wsgi.conf and add this lines: WSGISocketPrefix /var/run/apache2 2 - Here is my virtualhost setup (template include Cpanel) in /etc/apache2/conf.d/userdata/std/2_4/bmhair/django.conf WSGIDaemonProcess brunamaiahair.com.br user=bmhair group=bmhair socket-user=bmhair After I rebuild httpd and restart apache, but not working. So I look in /var/run/apache2 for check permissions 0 drwx------ 2 nobody nobody 40 Jun 28 22:25 htcacheclean 4 -rw-r--r-- 1 root root 6 Jun 29 01:34 httpd.pid 0 srwx------ 1 bmhair root 0 Jun 29 01:34 wsgi.12082.5.1.sock What I'm doing wrong? Here is Apache Server Info: Server version: Apache/2.4.25 (cPanel) Server built: Apr 20 2017 15:02:15 Server's Module Magic Number: 20120211:67 Server loaded: APR 1.5.2, APR-UTIL 1.5.2 Compiled using: APR 1.5.2, APR-UTIL 1.5.2 Architecture: 64-bit Server MPM: prefork threaded: no forked: yes (variable process count) Server compiled with.... -D APR_HAS_SENDFILE -D APR_HAS_MMAP -D APR_HAVE_IPV6 (IPv4-mapped … -
django 1.11 and jQuery autocomplete not working
I have a form field which has input as gene name. It searches for gene name field in my model database gene_names. I need to autocomplete when users type the name. I was suggested to use jQuery. I searched and found following links http://flaviusim.com/blog/AJAX-Autocomplete-Search-with-Django-and-jQuery/ 2.How to suggest similar words in autocomplete, and others also... based on them i have writen following code. It doesnt gives any Error but it doesnt works. models.py class GeneList(models.Model): gene_name = models.CharField(max_length=10) eg. of file uploading to database in base.html <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <link rel="stylesheet" href="http://code.jquery.com/ui/1.8.18/themes/base/jquery-ui.css" type="text/css" media="all" /> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"> </script> <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js" type="text/javascript"></script> In template file rendering form <form method="POST"> {% csrf_token %} <h4>Gene Name &nbsp {{ form.gene_p }}</h4> <button type="submit">After giving gene name Click here!</button> </form> ... ...<div class="ui-widget"> <label for="genes">Gene: </label> <input id="id_gene_p"> <!-- id_gene_p because thats what inspect element shows id for Gene name form field --> </div> <script type="text/javascript"> $(document).ready(function(){ var gene_input=$('input[id="id_gene_p"]'); gene_input.autocomplete({ source: "/filesapp/api/get_gene_names/", minLength: 2 }); } ); id_gene_p because thats what inspect element shows id for Gene name form field projects urls.py from filesapp import views urlpatterns = [ ... ... url(r'^api/get_gene_names/', views.get_gene_names, name='get_genes'), ] views.py from filesapp.forms import FileForm from filesapp.models import … -
How to calculate datetime difference using Django and python
I need some help. I need to calculate datetime difference by matching with DB date field value. Here I am getting some error. I am explaining the error below. Error: expected string or buffer Request Method: POST Request URL: http://127.0.0.1:8000/loginsave/ Django Version: 1.11.2 Exception Type: TypeError Exception Value: expected string or buffer Exception Location: /usr/local/lib/python2.7/dist-packages/django/utils/dateparse.py in parse_datetime, line 94 Python Executable: /usr/bin/python Python Version: 2.7.6 I am explaining my code below. pers = User.objects.get(pk=uid) if int(cnt) == 3: pers.status = 1; pers.date = datetime.now pers.save() else: cnt1 = int(cnt)+1 pers.count = cnt1 pers.save() Here I am getting error inside the if statement. Here I am storing the datetime inside the db. Here I need to calculate the difference with todays datetime value and the difference should be in hours(i.e-1hrs,2hrs...). Please help. -
search using django filter
I am trying to perform search on name and email field. For email field its giving an error "invalid literal for int() with base 10: 'abc@xyz.com'". but when I am using the user.id its giving correct result. For name field, its giving Cannot resolve keyword 'first_name' into field. How do i get it to work. Any help will be highly appreciated. my two models are: class publication(models.Model): title = models.CharField(max_length=500) user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1) .... class MyUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), max_length=254, unique=True) first_name = models.CharField(_('first name'), max_length=30, blank=True) last_name = models.CharField(_('last name'), max_length=30, blank=True) ..... My view: def search(request): result = publication.objects.all() query = request.GET.get("query") if query: result = result.filter( Q(title__icontains=query) | Q(user__first_name__icontains=query) | Q(user__email=query) ).distinct() user_filter = UserFilter(request.GET, queryset=result) return render(request, "search.html", {'filter': user_filter}) My filter: class UserFilter(filters.FilterSet): title = filters.CharFilter(lookup_expr='icontains') first_name = filters.CharFilter(lookup_expr='iexact') user = filters.CharFilter(lookup_expr='exact') class Meta: model = publication fields = ['title', 'first_name', 'user']