Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
M1 Mac - GDAL Wrong Architecture Error [Django]
I'm trying to get a django project up and running, which depends on GDAL library. I'm working on a M1 based mac. Following the instructions on official Django docs, I've installed the necessary packages via brew $ brew install postgresql $ brew install postgis $ brew install gdal $ brew install libgeoip gdalinfo --version runs fine and shows the version as 3.3.1 gdal-config --libs returns this path: -L/opt/homebrew/Cellar/gdal/3.3.1_2/lib -lgdal a symlink is also placed on the homebrew's lib directory, which is in my path. When I try to run django, it complains that it cannot find the GDAL package. When I try to specify the path to the GDAL library using GDAL_LIBRARY_PATH, I get this error: OSError: dlopen(/opt/homebrew/Cellar/gdal/3.3.1_2/lib/libgdal.dylib, 6): no suitable image found. Did find: /opt/homebrew/Cellar/gdal/3.3.1_2/lib/libgdal.dylib: mach-o, but wrong architecture /opt/homebrew/Cellar/gdal/3.3.1_2/lib/libgdal.29.dylib: mach-o, but wrong architecture P.s. I've already seen this answer, but it didn't help. Isn't that strange when I try to run gdalinfo it runs fine but when django tries to run it throws me this error? What am I doing wrong? -
how to show facebook data in django website
I am building a website where user can login and see his Facebook data, and other social networking sites at one place(likes, shares, posts, comments etc) I need to pull data from the Facebook. Is there a way that he can just enter email and password and we can pull that, I know about creating an graph API app in Facebook developer. 2 Website is based in Django, what approach will be the best and roadmap to achieve the goal. -
Django: TypeError at /login/ __init__() takes 1 positional argument but 2 were given
I'm trying to update Django version to 3.2.5 from 1.9 in my simple project, and all looks good. But when I try to access the Login page, I get the following error in the browser: Request Method: GET Request URL: http://localhost:49801/login/ Django Version: 3.2.5 Exception Type: TypeError Exception Value: __init__() takes 1 positional argument but 2 were given Exception Location: C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\site-packages\django\core\handlers\base.py, line 181, in _get_response Python Executable: C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\python.exe Python Version: 3.7.8 Python Path: ['C:\\source\\repos\\aud', 'C:\\Program Files (x86)\\Microsoft Visual Studio\\Shared\\Python37_64\\python37.zip', 'C:\\Program Files (x86)\\Microsoft Visual Studio\\Shared\\Python37_64\\DLLs', 'C:\\Program Files (x86)\\Microsoft Visual Studio\\Shared\\Python37_64\\lib', 'C:\\Program Files (x86)\\Microsoft Visual Studio\\Shared\\Python37_64', 'C:\\Program Files (x86)\\Microsoft Visual Studio\\Shared\\Python37_64\\lib\\site-packages'] Traceback: Environment: Request Method: GET Request URL: http://localhost:49801/login/ Django Version: 3.2.5 Python Version: 3.7.8 Installed Applications: ['app', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] 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 "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) Exception Type: TypeError at /login/ Exception Value: __init__() takes 1 positional argument but 2 were given Additional info from settings.py: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], … -
How to determine in javascript when a dict of images created in django has loaded
I am using django and javascript. When a page is first loaded I load a dict of images (around 85 in all) and I don't want the javascript to attempt to display the images until I am sure that all of the images are loaded js $(document).ready(function () { $.ajax( { type: "GET", url: "/common/load-common-data/", cache: false, success: function (context) { images = context.images; setTimeout(() => { displayImages(images) }, 750); } } ); } This is unsatisfactory because the 750 ms delay is arbitrary and might not be sufficient in specific cases I have seen attempts to solve this, but they rely on loading the images individually whereas for various reasons I need to select the images in my view and upload them as a dict. -
TypeError: create_user() missing 1 required positional argument: 'password'
from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager # User Related Models class cUserManager(BaseUserManager): def create_user(self, email, username, password, **other): if not email or username or password: raise ValueError('All fields must not be blank') email = self.normalize_email(email) user = self.model(email=email, password=password, **other) user.set_password(password) user.save() return user def create_superuser(self, email, password, **other): other.setdefault('is_staff', True) other.setdefault('is_superuser', True) other.setdefault('is_active', True) return self.create_user(email, password, **other) class cUser(AbstractBaseUser): username = models.CharField(max_length=64, unique=True) email = models.EmailField(max_length=64, unique=True) password = models.CharField(max_length=128) # superuser fields is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = cUserManager() No idea what I'm doing wrong, I am clearly setting the password.. or am I? When I was searching for solutions it seems to that people don't make a password field in the user model, so maybe I'm overriding it and that's the reason for the error? -
I cannot add products into my cart View template
I am trying to add a product into my cart , but the product is not being able to add . AffProduct Model is the model where all the details of the product is being stored. Whenever I click on the 'Add To Cart' button the pages are being rendered and all the css and html elements being also renderd , but the product is not being added. Models.py class AffProduct(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='foo') product_title = models.CharField(max_length=255) uid = models.IntegerField(primary_key=True) specification = models.CharField(max_length=255) sale_price = models.IntegerField() discount = models.IntegerField() img1 = models.ImageField(max_length=255, null=True, blank=True, upload_to="images/") img2 = models.ImageField(max_length=255, null=True, blank=True, upload_to="images/") promote_method = models.TextChoices terms_conditions = models.CharField(max_length=255, null=True) promote_method = models.CharField( max_length=20, choices=promote_choices, default='PPC' ) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) This is my CartAdd View: @login_required @require_POST def CartAdd(request, uid): cart = Cart(request) product = get_object_or_404(AffProduct, uid=uid) form = CartAddProductForm(request.POST) if form.is_valid(): cd = form.cleaned_data cart.add(product=product, quantity=cd['quantity'], update_quantity=cd['update']) return redirect('CartDetail') This is my CartAddProductForm from django import forms from .models import Order PRODUCT_QUANTITY_CHOICES = [(i, str(i)) for i in range(1, 21)] class CartAddProductForm(forms.Form): quantity = forms.TypedChoiceField(choices=PRODUCT_QUANTITY_CHOICES, coerce=int, label="quantity") update = forms.BooleanField(required=False, initial=False, widget=forms.HiddenInput) The template where i have been trying to render {% block content %} <h1>Your … -
RECEIVING DATA FROM X3 CONCOX GPS DEVICE USING PYTHON
I have a project where I'm trying to receive data from X3 GPS device using python socket. And so far i have managed to create listening script with both port number and IP address configured. s= socket.socket(socket.AF_INET,socket.SOCK_STREAM) host = '192.XX.XX.XX' port = 1234 s.bind((host,port)) s.listen() print(f'listening ...') while True: conn, address = s.accept() print(f'connection from {address} has been establish') And i also configured the IP and the port number to the device via SMS. BUT I can't get it to connect. I need a help to connect the device first before starting receiving login packets or if there are better solutions for the same issue using python. Thank you in advance -
Document Complaint not getting aved after editing in django
I have two pages that help my users view and edit the complaints that they register. There are two types of complaints they can register. One is a written and the other is through a document. When the user tries to edit a written complaint, the edits get saved in the model but when i followed the same logic to edit my document complaints, the users can view them but on editing and saving, the edits are not getting saved, what's wrong? models.py: class Complaint(models.Model): user = models.ForeignKey(User, on_delete= models.CASCADE, null = True, blank=True) id = models.AutoField(blank=False, primary_key=True) reportnumber = models.CharField(max_length=500 ,null = True, blank= False) eventdate = models.DateField(null=True, blank=False) event_type = models.CharField(max_length=300, null=True, blank=True) device_problem = models.CharField(max_length=300, null=True, blank=True) manufacturer = models.CharField(max_length=300, null=True, blank=True) product_code = models.CharField(max_length=300, null=True, blank=True) brand_name = models.CharField(max_length = 300, null=True, blank=True) exemption = models.CharField(max_length=300, null=True, blank=True) patient_problem = models.CharField(max_length=500, null=True, blank=True) event_text = models.TextField(null=True, blank= True) document = models.FileField(upload_to='static/documents', blank=True, null=True) def __str__(self): return self.reportnumber @property def totalcomplaints(self): return Complaint.objects.count() class DocComplaint(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) event_date = models.DateField(null=True, blank=False) document = models.FileField(upload_to='static/documents', blank=False, null=True) def __str__(self): return str(self.event_date) forms.py: class EditComplaintForm(ModelForm): class Meta: model = Complaint fields = ['reportnumber', 'event_type', 'eventdate', … -
How can I copy data of field in other field which is located in other app with different name django
I have two models and In first app there is field name current_bill and in Second app there is field name is previous_bill I want to copy data of current_bill in previous_bill How can I copy it ? meter_detail/models.py Meter(models.Model): current_bill=MoneyField(max_digits=10, decimal_places=2, null=False, blank=True, default_currency='INR') bill_detail/models.py Bill(models.Model): previous_bill=MoneyField(max_digits=10, decimal_places=2,default_currency='INR') I want copy of value which I enter in current_bill and save in Model Bill I tried this def save(self, *args, **kwargs): self.previous_outstanding = self.current_outstanding.previous_outstanding super(BillDetailModel, self).save(*args, **kwargs) But Its not working please give me solution for copy field -
How to get all parent nodes but filter child node in python django
I am trying to fetch all parent's records with child models with filtration in Django(3.2). class Parent(models.Modal): name = models.CharField(max_length=20) class Child(models.Modal): parent = models.ForeignKey(Parent, related_name="children", on_delete=models.CASCADE) name = models.CharField(max_length=20) is_working = models.BooleanField(default=True) just like these models I want to get all parents with not working children's. i am trying like this Parent.objects.filter(children__is_working=False). but get those parent who has is_working False value. if one parent has multiple children who have both kinds of records so parent queryset returns those parents also. my requirement is to get all parents with those children whose is_working value is False. -
i have set up an django server and i need to communicate with my iot device. how can it be done?
I have set a Django app in the AWS ubuntu in nginx.i am running my Django app using uwsgi and my apis are working well, but I need to communicate with the iot device that I got. so , how can I set up the connection between hub and server using emqx mqtt over tls/ssl mqtt protocol. -
nautobot_easy_onboard is not a registered namespace
I did not create a separate app while making my django project. I have my urls.py, views.py and other files in the parent folder itself.I have tried many ways to register a namespace none of them worked out. This is the image of my urls.py file. Sometimes the website works fine but sometimes it shows the above mentioned error. So can someone please tell how to register namespace properly in this case. -
Django testing model instance setup
Why when creating instance as a class attribute: class ModelTestsProducts(TestCase): # Create example objects in the database product_category = models.Product_category.objects.create( name='Spring' ) product_segment = models.Product_segment.objects.create( name='PS1', product_category=self.product_category ) product_group = models.Product_group.objects.create( name='PG1', product_segment=self.product_segment ) def test_product_category(self): self.assertEqual(str(self.product_category), self.product_category.name) def test_product_segment(self): self.assertEqual(str(self.product_segment), self.product_segment.name) def test_product_group(self): self.assertEqual(str(self.product_group), self.product_group.name) I am getting following error when running test for the 2nd time? django.db.utils.IntegrityError: duplicate key value violates unique constraint "products_product_category_name_key" DETAIL: Key (name)=(dadsad) already exists. When I use setUp method and then create objects insite this setUp method it works fine, but I cant understand why the above method somehow creates every object multiple times and thus fails the unique constraint set in the model. Is it because django test suite somehow calls this class everytime every test function is run, thus every attribute is assigned multiple times? But then if I move the object assignment outside the class (in the test file) then I also get this duplicate error, so that would mean whole test file is being called multiple times every time test is being run. One more thing I use docker to run this Django app and and run django test from docker-compose command. -
Is there any attribute or something like placeholder in django, where I can write the permanent text
I am making a simple form. i am searching any term in django like placeholder, but 'placeholder text' vanishes as user type something in text box. I want something like 'permanent text' in django-text-field, where as user opens the form, they have to start writing something after 'permanent text' which i have entered while coding. The permanent text should remain there user input and not fade-away like placeholder text does. -
not able to start the start the server djano
I am getting this error for no reason, not knowing where the problem lies, it's not allowing me to run migrations as well, I am posted by trace below, need help with this Traceback (most recent call last): File "C:\Users\atif\AppData\Local\Programs\Python\Python37\lib\threading.py", line 926, in _bootstrap_inner self.run() File "C:\Users\atif\AppData\Local\Programs\Python\Python37\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\atif\PycharmProjects\my_proj_basic\virtual-env\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\atif\PycharmProjects\my_proj_basic\virtual-env\lib\site-packages\django\core\management\commands\runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "C:\Users\atif\PycharmProjects\my_proj_basic\virtual-env\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\Users\atif\PycharmProjects\my_proj_basic\virtual-env\lib\site-packages\django\core\management\__init__.py", line 375, in execute autoreload.check_errors(django.setup)() File "C:\Users\atif\PycharmProjects\my_proj_basic\virtual-env\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\atif\PycharmProjects\my_proj_basic\virtual-env\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\atif\PycharmProjects\my_proj_basic\virtual-env\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\Users\atif\PycharmProjects\my_proj_basic\virtual-env\lib\site-packages\django\apps\config.py", line 301, in import_models self.models_module = import_module(models_module_name) File "C:\Users\atif\AppData\Local\Programs\Python\Python37\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\atif\PycharmProjects\my_proj_basic\food_deliveryapp\orders\models.py", line 9, in <module> class PlacedOrder(models.Model): File "C:\Users\atif\PycharmProjects\my_proj_basic\virtual-env\lib\site-packages\django\db\models\base.py", line 161, in __new__ new_class.add_to_class(obj_name, obj) File "C:\Users\atif\PycharmProjects\my_proj_basic\virtual-env\lib\site-packages\django\db\models\base.py", line 326, in add_to_class value.contribute_to_class(cls, name) File "C:\Users\atif\PycharmProjects\my_proj_basic\virtual-env\lib\site-packages\django\db\models\fields\__init__.py", line 788, in contribute_to_class if not getattr(cls, self.attname, … -
Pass and receive object pk to fix foreign key field in CreateView in Django
I'm trying to build a django app to mantain a class called "Actuacion". Depending on the values of the field "tipo" additional info is required, so I have created a main class "Actuacion" with the common fields, and a different class for each "tipo" with specific fields for each type linked with the main class "Actuacion" through a foreign key. The model is something like this: models.py class TipoActuacion(models.Model): # Values for "tipo" by the moment are "DEPURACION", "CONSERVACION", "PLANEAMIENTO" tipo = models.CharField(max_length=50) def __str__(self): return self.tipo class Actuacion(models.Model): titulo = models.CharField(max_length=200) tipo = models.ForeignKey('TipoActuacion', on_delete=models.SET_NULL, null=True) # Other common fields class ActuacionPlaneamiento(models.Model): actuacion = models.ForeignKey('Actuacion', on_delete=models.SET_NULL, null=True) info = models.CharField(max_length=100) # Other fields class ActuacionDepuracion(models.Model): actuacion = models.ForeignKey('Actuacion', on_delete=models.SET_NULL, null=True) habitantes = models.IntegerField(null=True, blank=True) # Other fields class ActuacionConservacion(models.Model): actuacion = models.ForeignKey('Actuacion', on_delete=models.SET_NULL, null=True) fecha = models.DateField(null=True, blank=True) # Other fields So, I pretend to create "Actuacion" objects through django class-based views and after creating the main object, depending on the value registered on "tipo" field redirect to the corresponding create view to complete the info. The main class "Actuacion" is created but I haven't found the way to link it with the child entity (based on field "tipo", … -
How to get count in Django for a model two foreign keys away
I have three modles in my Django app as follows: class City(models.Model): city_name = models.CharField(length=50) class Area(models.Model): city = models.ForeignKey(City) area_name = models.CharField(length=50) class Person(models.Model): area = models.ForeignKey(Area) person_name = models.CharField(length=50) I require cities in order of their population (i.e. Person basis). How is it possible with Django? -
django form.errors showing "This field is required!" after running modelform validation with form.isvalid
So I'm trying to get a django model form to only accept alphanumeric input via REGEX, as shown here: class AddDeadCoin(forms.ModelForm): class Meta: model = DeadCoin fields = ( 'category', 'is_coin', 'name', 'ticker', 'founder', 'total_coins_or_tokens', 'no_exchanges', 'project_start_date', 'project_end_date', 'social_end_date', 'logo', 'screenshot', 'notes', 'links', ) def clean_name(self): name = self.cleaned_data.get('name') if bool(re.match(r'^[A-Za-z0-9_-]+$', str(name))): return name else: raise forms.ValidationError("Sorry , you can only have alphanumeric, _ or - in username") def save(self): instance = super(AddDeadCoin, self).save(commit=False) instance.slug = orig = slugify(instance.name) for x in itertools.count(1): if not DeadCoin.objects.filter(slug=instance.slug).exists(): break instance.slug = '%s-%d' % (orig, x) instance.save() return instance However, on trying to submit any input(both valid and invalid) I get a "This field is required!" forms.error message. I get the message twice to be precise. It should be noted that 'name' and 'ticker' fields are required. This is what my models look like: class DeadCoin(models.Model): name = models.CharField(max_length=70, default=None) summary = models.TextField(blank=True, null=True, default="Dead Coin Summary") ticker = models.CharField(max_length=20, default=None) founder = models.CharField(blank=True, null=True, max_length=50) is_coin = models.BooleanField(blank=True, null=True, default=True) notes = models.TextField(blank=True, null=True, default='') links = models.TextField(blank=True, null=True, default='') total_coins_or_tokens = models.CharField(blank=True, null=True, max_length=50, default='Unknown') no_exchanges = models.BooleanField(blank=True, null=True, default=True) project_start_date = models.CharField(blank=True, null=True, max_length=10, default='2018') project_end_date = models.CharField(blank=True, null=True, max_length=10, … -
Django - inline formset save multiple rows
I'm following this tutorial to create an inline formset where you can add & remove rows. The visual aspect is working fine, adding & removing rows works fine but when I click the create button to save it only one row is saved despite me adding multiple rows. Why does the inline formset only save one row & not all of them? CreateView (Views.py) def get_context_data(self, **kwargs): SubprogramBudgetFormSet = inlineformset_factory( Subprogram, SubBudget, fields=('subprogram', 'budgetYear', 'budgetCost'), can_delete=False, extra=1, ) data = super().get_context_data(**kwargs) if self.request.POST: data['subbudget'] = SubprogramBudgetFormSet(self.request.POST) else: data['subbudget'] = SubprogramBudgetFormSet() return data def form_valid(self, form): context = self.get_context_data() budget = context["subbudget"] if budget.is_valid(): self.object = form.save() budget.instance = self.object budget.save() return super().form_valid(form) Template.html <table class="table table-light"> {{ subbudget.management_form }} {% for form in subbudget.forms %} {% if forloop.first %} <thead> <tr> {% for field in form.visible_fields %} <th scope="col">{{ field.label|capfirst }}</th> {% endfor %} </tr> </thead> {% endif %} <tbody> <tr class="{% cycle row1 row2 %} budget_formset_row"> {% for field in form.visible_fields %} <td> {# Include the hidden fields in the form #} {% if forloop.first %} {% for hidden in form.hidden_fields %} {{ hidden }} {% endfor %} {% endif %} {{ field.errors.as_ul }} {{ field }} </td> {% … -
gunicorn + django + telegram + mqtt client
We use gunicorn with django and django-telegrambot. We also have a MQTT client in an own app. When some MQTT messages arrive we send Telegram messages and the other way around. The Problem is now that when we use gunicorn with multiple workers, we have multiple MQTT Clients, so that when a MQTT message arrives we will send multiple times the same Telegram message. When we use gunicorns preload with workers, we only have one MQTT client, but then all processes share the same Telegram TCP connection and we get wired SSL errors. As an alternative we could use only use on process and multiple threads, but then sometimes MQTT and Telegram messages gets not processed (idk why). Is there a way to get this running? Instead of using webhooks one could use botpolling, but django-telegrambot says: Polling mode by management command (an easy to way to run bot in local machine, not recommended in production!) -
How do I group a list of repeating elements?
I have a list from many-to-many relationship: INPUT: channels_list = [channelscategory_1: channel_1; channelscategory_1: channel_2; channelscategory_1: channel_3; channelscategory_2: channel_4; channelscategory_2: channel_5] How can you do it to get it? OUTPUT: channels_list = [channelscategory_1: channel_1, channel_2, channel_3; channelscategory_2: channel_4, channel_5] -
Django Factory Boy and Faker always return same value
I'm trying to generate dummy data and I have a selectable field among several options but the same sector is always generated models.py: SECTOR = (("1", _("Administración y gestión")), ("2", _("Agricultura y ganadería")), ("3", _("Industria alimentaria")), ("4", _("Grandes almacenes")), ("5", _("Comercio")), ("6", _("Construcción e industrias extractivas")), ("7", _("Actividades físico-deportivas"))) class Company(TimeEntity): ... sector = models.CharField(verbose_name=_("Sector"), max_length=20, choices=SECTOR, default=1) factories.py: SECTOR_FACTORY = list(map(lambda x: x[0], app_models.SECTOR)) class CompanyFactory(DjangoModelFactory): class Meta: model = app_models.Company sector = fake.random_choices(elements=SECTOR_FACTORY, length=1) -
I want to input multiple quantity as per my order item
admin panelstrong text if i select multiple item order quantity also increases according to my selected item -
Import csv encoding error in admin Django
admin.py @admin.register(Country) class CountryAdmin(ImportExportModelAdmin): pass It shows the following error: Imported file has a wrong encoding: 'charmap' codec can't decode byte 0x81 in position 1233: character maps to The csv file contains arabic characters also. How to resolve it? -
Inner Join relationship filter in Django REST framework
I have models like these relationship I access these models via Django REST framework api class User(models.Model): name = models.CharField(max_length=128,unique=True) class Mix(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE,null=True,blank=True) pub_date = models.DateTimeField('date published',default=timezone.now) class AccessToken(models.Model): id = models.BigAutoField(primary_key=True) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True, related_name="%(app_label)s_%(class)s", ) token = models.CharField(max_length=128,unique=True) and here is the viewset class MixViewSet(viewsets.ModelViewSet): queryset = Mix.objects.all() serializer_class = MixSerializer filter_backends = [django_filters.rest_framework.DjangoFilterBackend] filter_fields = ["id","user"] // how can I Set?? token class MixSerializer(serializers.ModelSerializer): class Meta: model = Mix fields = ('id','pub_date','user') then I want to get the mixes by token with this procedure Select from AccessToken table and find one user select * from Mix where user = user(selected at 1) I guess it is something like inner join??? How can I make it in django filter???