Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Local Django server is incredibly slow
I am trying to connect with a Django dev server running locally. HTTP requests take a minute or more! Looking for a way to speed it up. According to Chrome network monitor, Waiting (TTFB) on one of the URLs is 5.5 minutes. Similarly bad performance occurs using Firefox screenshot of chrome network monitor Server side error/logs: HTTP GET /sources/ 200 [151.03, 127.0.0.1:49420] <generator object source_list.<locals>.<genexpr> at 0x7fccf6a90350> Application instance <Task pending coro=<AsgiHandler.__call__() running at .../djangoenv377/lib/python3.7/site-packages/channels/http.py:192> wait_for=<Future pending cb=[_chain_future.<locals>._call_check_cancel() at .../.pyenv/versions/3.7.7/lib/python3.7/asyncio/futures.py:351, <TaskWakeupMethWrapper object at 0x7fccf5c4bf50>()]>> for connection <WebRequest at 0x7fccf5f41690 method=GET uri=/sources/ clientproto=HTTP/1.1> took too long to shut down and was killed. <generator object source_list.<locals>.<genexpr> at 0x7fccf6a90250> HTTP GET /sources/ 200 [332.32, 127.0.0.1:49846] When refreshing, these two lines happen pretty instantaneously: HTTP GET /sources/ 200 [332.32, 127.0.0.1:49846] <generator object source_list.<locals>.<genexpr> at 0x7fccf695e350> And it takes a while for the Application instance <Task pending coro=<AsgiHandler.__call__()... error to occur. Environment info: OS: Ubuntu 20.04.2 LTS Python: 3.7.7 channels==2.4.0 channels-redis==2.4.2 celery==4.4.7 redis==3.5.3 Twisted==20.3.0 websocket-client==0.57.0 uWSGI==2.0.18 daphne==2.4.1 defusedxml==0.6.0 Django==2.2.7 django-celery==3.3.1 django-celery-results==1.2.1 django-channels-panel==0.0.5 djangorestframework==3.11.0 asgi-redis==1.4.3 asgiref==3.3.1 async-timeout==3.0.1 I've tried mixing and matching different pip package versions with no success. I've tried using debug=False with no success. The annoying thing is that this application works as expected … -
Nginx wont update static files for Django
I haveNginx + Gunicorn + Django server deployed on Ubuntu. It running with Debug=False settings and everything works fine. CSS is loaded fine, JS works as well. But when I try to update the css file or js file, the changes I made are not reflected when I run the server. I tried to update an old static files, also static file created after collectstatic command, I also tried clean collectstatic as well as systemctl restart nginx (and gunicorn). I also cleaned my cache in browser. But when I look a page source code, this changes are not there. this is how my nginx config looks like server { listen 80; server_name mediadbin.n-media.co.jp; client_max_body_size 500M; access_log /home/mediaroot/mediadbin/logs/nginx-access.log; error_log /home/mediaroot/mediadbin/logs/nginx-error.log; server_tokens off; location / { proxy_pass http://127.0.0.1:8000; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $host; proxy_set_header X-Forwarded-Server $host; proxy_set_header X-Real-IP $remote_addr; } location /static { $ I TRIED APPLY CHANGES HERE <- NOTHING happens alias /home/mediaroot/mediadbin/mediadbin/static; } location /media { alias /home/mediaroot/mediadbin/mediadbin/media; } include global404; } HERE is my gunicorn config #!/bin/bash # Name of the application NAME="mediadbin" # Django project directory DJANGODIR=/home/mediaroot/mediadbin/mediadbin # how many worker processes should Gunicorn spawn NUM_WORKERS= $(( $(nproc) * 2 + 1 )) # … -
Keycloak Integration with Python
Does anybody know a solid tutorial of how to connect Keycloak to a Django backend? I tried to use this one: https://blog.jonharrington.org/static/integrate-django-with-keycloak But apart from the Keycloak part, the Django setup is not as easy as it made it seem. Then, I moved to this one: https://sairamkrish.medium.com/keycloak-integration-part-3-integration-with-python-django-backend-5dac3b4a8e4e And again, I got stuck in the technicality with python. Both descriptions seem so vague to me. Did anybody manage to it with the tutorials out there? -
How can I use Django signals outside the Django application?
I have a gRPC server running that responds to external requests. I also have a Django app that takes care of all other web related events. I want to send a signal to the Django app when the gRPC server receives requests. (The gRPC system was already in place. The Django app is an extension) Since using Django signals outside the app doesn't work (no context), I want another way to send some kind of notification to the app. I am aware that this is a very unlikely scenario. -
Celery Picking alternative task
While learning and implementing CELERY I noticed celery is picking my task alternatively, which means if I do the same event multiple times, for 1st-time celery doesn't pick the task, and for the second time it picks and completes the task, this goes for 3rd and 4th time and so on... Here is my output - here is my celery app - I am calling my task defined in my tasks.py (sending email for now) from my views.py, for checking, I am calling task in my list function of viewset. so when I go to URL for 1st time nothing happens and on the second visit, the mail is sent. Using rabbitmq as a broker. also have Daemonized celery. The first image is by using a manual command. WHAT AM I MISSING OR WHAT WRONG HAVE I DONE ?? -
Can't use CROS in django on production
I use nginx, gunicorn and systemd to deploy my Dajngo application on a virtual private server. and I have set all settings for CROS but it doesn't work. this is my dajngo setting CROS related parts: ALLOWED_HOSTS = ['*'] CORS_ORIGIN_ALLOW_ALL = True INSTALLED_APPS = [ 'corsheaders', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'shop', 'user', 'mag', ] 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', 'corsheaders.middleware.CorsMiddleware', ] and this is my Nginx server configuration: server { listen 80; server_name 116.203.231.211 127.0.0.1 localhost; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /www/public_html/stage/; } location / { proxy_pass http://127.0.0.1:8000; # address of the Node.js instance } location /media/ { autoindex on; alias /webapps/stage/media/; } location /api/ { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } I have also tried adding the headers like below to the nginx server but it didn't worked if ($request_method = 'GET') { # 1. Allow any origin add_header 'Access-Control-Allow-Origin' '*' always; # 2. Credentials can be cookies, authorization headers or TLS client certificates add_header 'Access-Control-Allow-Credentials' 'true'; # 3. What methods should be allowed when accessing the resource in response to a preflight request add_header 'Access-Control-Allow-Methods' 'GET, POST, PATCH, PUT, DELETE, OPTIONS'; … -
Can't add an anchor tag using a url path to another Django template
I am trying to add an anchor tag using a url in Django like below: layout.html {% extends "tasks/layout.html" %} {% block body %} <h1>Tasks</h1> <ul> {% for task in tasks %} <li>{{ task }}</li> {% endfor %} </ul> <a href="{% url 'add' %}">Add Tasks</a> {% endblock %} Views.py from django.shortcuts import render tasks = ["foo", "bar", "baz"] # Create your views here. def index(request): return render(request, "tasks/index.html", { "tasks": tasks }) def add(request): return render(request, "tasks/add.html") urls.py from django.urls import path from . import views app_name = "tasks" urlpatterns = [ path("", views.index, name="index"), path("add", views.add, name="add") ] However, I keep getting the following error when setting the href using the url method, but not when I hardcode the path: Error during template rendering In template C:\Users\User\Desktop\Coding\CS50W\Week3-Django\lecture3\tasks\templates\tasks\layout.html, error at line 0 'set' object is not reversible 1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <title>Tasks</title> 5 </head> 6 <body> 7 {% block body %} 8 {% endblock %} 9 </body> 10 </html> Traceback Switch to copy-and-paste view C:\Users\User\Desktop\Coding\CS50W\Week3-Django\venv\lib\site-packages\django\core\handlers\exception.py, line 47, in inner response = get_response(request) … ▶ Local vars C:\Users\User\Desktop\Coding\CS50W\Week3-Django\venv\lib\site-packages\django\core\handlers\base.py, line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) … ▶ Local vars C:\Users\User\Desktop\Coding\CS50W\Week3-Django\lecture3\tasks\views.py, line 6, in index … -
Django local and production database
Some days ago I deployed my first django project on heroku, now every time I want to change something and do some test, I'm switching between them commenting one and uncommenting the other ## Heroku DB #DATABASES = { # 'default': { # 'ENGINE': 'django.db.backends.postgresql', # 'NAME': 'FOO', # 'HOST': 'FOO', # 'POST': 5432, # 'USER': 'FOO', # 'PASSWORD': 'FOO', # } #} # LOCAL DATABASE DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'FOO', 'USER': 'FOO', 'PASSWORD': 'FOO', 'HOST': 'localhost', 'PORT': '5432' } } How to work with different databases without doing this, just putting all inside the dictionary. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'FOO', 'USER': 'FOO', 'PASSWORD': 'FOO', 'HOST': 'localhost', 'PORT': '5432' }, 'LOCAL': { FOOOOOO } } -
Django download a BinaryField as a CSV file
I am working with a legacy project and we need to implement a Django Admin that helps download a csv report that was stored as a BinaryField. The model is something like this: class MyModel(models.Model): csv_report = models.BinaryField(blank=True,null=True) Everything seems to being stored as expected but I have no clue how to decode the field back to a csv file for later use. I am using something like these (as an admin action on MyModelAdmin class) class MyModelAdmin(admin.ModelAdmin): ... ... actions = ["download_file",] def download_file(self, request,queryset): # just getting one for testing contents = queryset[0].csv_report encoded_data = base64.b64encode(contents).decode() with open("report.csv", "wb") as binary_file: # Write bytes to file decoded_image_data = base64.decodebytes(encoded_data) binary_file.write(decoded_image_data) response = HttpResponse(encoded_data) response['Content-Disposition'] = 'attachment; filename=report.csv' return response download_file.short_description = "file" But all I download is a scrambled csv file. I don't seem to understand if it is a problem of the format I am using to decode (.decode('utf-8') does nothing either ) PD: I know it is a bad practice to use BinaryField for this. But requirements are requirements. Nothing to do about it. -
Django view function for navbar
I have my page only for navigation bar and I include it in base page. Now I have drop down menu in that navigation bar and links I get from database(that links are my categories). But how can I call my function in views without path, because I don't need to have path for navigation bar? And I need that view function to get data from database. -
The 'imagem_post' attribute has no file associated with it
Estou tentando fazer com que as imagens estejam na tela.Estou tentando resolver isso parece que meu código não está reconhecendo as informações do meu model.py, tudo isso acontece quando tento chamar as informações na tag do html. model.py import django from django.db import models from categorias.models import Categoria from django.contrib.auth.models import User from django.utils import timezone class Post(models.Model): titulo_post = models.CharField(max_length=255, verbose_name='Titulo') autor_post = models.ForeignKey(User, on_delete=models.DO_NOTHING, verbose_name='Autor') data_post = models.DateTimeField(default=django.utils.timezone.now, verbose_name='Data') conteudo_post = models.TextField(verbose_name='Conteúdo') excerto_post = models.TextField(verbose_name='Excerto') categoria_post = models.ForeignKey(Categoria, on_delete=models.DO_NOTHING, blank=True, null=True, verbose_name='Categoria') imagem_post = models.ImageField(upload_to='post_img/%Y/%m/%d', blank=True, null=True, verbose_name='Imagem') publicado_post = models.BooleanField(default=False, verbose_name='Publicado') def __str__(self): return self.titulo_post Na tag de img é onde estou tentando referenciar minhas imagens quando coloco: imagem_post.url aí começa a dar erro se eu não colocar .url o erro some mais eu fico sem imagens na tela index.html {% extends 'base.html' %} {% load static %} {% block conteudo %} <!-- CONTENT --> <div class="card-columns mt-4"> <!-- FOR LOOP --> {% for post in posts %} <div class="card"> <a href="post.html"> <img class="card-img-top" src="{{ post.imagem_post.url }}" alt="{{ post.titulo_post.url }}"> </a> <div class="card-body"> <h5 class="card-title"> <a href="post.html">A wonderful </a> </h5> <p class="card-text">When, while the lovgleams steal ...</p> <p class="card-text"> <small class="text-muted">hoje | 1 comentário | Tecnologia</small> </p> … -
python selenium - how can i find out exactly when an alert happens?
I want to find out when an alert happens so I can automatically accept. I've placed self.driver.switch_to.alert.accept() in various places in the code but I always get a selenium.common.exceptions.NoAlertPresentException. When I don't place it anywhere I get an selenium.common.exceptions.UnexpectedAlertPresentException. When I use expected_conditions I get a selenium.common.exceptions.TimeoutException. I don't know what to do at this point. Can anyone help? Python/Django Backend. Using Selenium (Firefox) -
why models.BooleanField returning bytes instead of Boolean value?
I am trying to assigning a boolean value to model.BooleanField otp_object = models.Otp( blocked=(user_agent is None and route == 'exposed') ) Here is where I am checking if the bool is true but it's returning b'\x00' if otp_object.blocked: I am unable to understand where I am going wrong? -
Django HTML User authentication
I have a condition like this: {% if object.author == user or object.res_person_1_username == user %} If I view variables with, for example: <p class="article-content mb-1"><strong>object.res_person_1_username: </strong>{{ object.res_person_1_username }}</p> They are the same, all three, but condition object.res_person_1_username == user is always False. Why is that? What I'm missing? Do I need to change data type or something? models.py res_person_1_username = models.TextField(blank=True, max_length=40) -
How to seperate import and export fields in Django-Import-Export
I am using Django-Import-Export and have a model-fields like below id, date, val1, val2, val3 what i want is to import by only 2 fields (date and val1) and i want to export 4 fields (date val1 val2 val3) if i do like below i can see import fields changing but in export only 2 fields are coming class MyResource(ExportImportObjectHere): class Meta: model = ModelName skip_unchanged = True fields = ('date', 'val1') -
Django 1.11's signed_cookie session backend sets a new sessionid for every request
This makes the vary_on_cookie decorator useless because the coookie is different at every request, and also it makes the sessions never expire regardless of SESSION_COOKIE_AGE because every request pushes the expiration forward. I did some digging, and process_response in sessions/backends/middleware.py does request.session.save(), which causes the signed_cookie backend to create a new session key with this code: return signing.dumps( self._session, compress=True, salt='django.contrib.sessions.backends.signed_cookies', serializer=self.serializer, ) This code returns a different value even if called with the same argument (I guess it's built into the encryption). Am I missing something? This doesn't sound right... any ideas? Thanks! -
How do I make Django Website public on my local network?
I am building a website for myself and family in Django and React. Every time I ask them to check my process and get their opinions they get a webpage not found error or this site can't be reached. How do I make is so that anyone on my local network can check my page when its running. This is the default in flask, I don't understand why django runs like this? (safety maybe?) I can't find any good information on how to add an allow all to the ALLOWED_HOSTS section in the settings of the main app. I also know that you can add IP address, But I'm a noob and I don't follow how to get the ip address of all my families devices without alot of work?? Does anyone have a good solution for this?? -
Django zappa error: InconsistentMigrationHistory: Migration admin.0001_initial is applied before its dependency accounts.0001_initial on
So, I'm using Zappa on AWS Lambda. I just added a custom user model to my project and tried to migrate to the RDS on AWS and Zappa gives me the following error: InconsistentMigrationHistory: Migration admin.0001_initial is applied before its dependency accounts.0001_initial on database 'default'. Now, I know that if I got this error on my local server, I would do this: python manage.py migrate admin zero python manage.py migrate auth zero python manage.py migrate contenttypes zero python manage.py migrate sessions zero I would then run the migrations to destroy their tables and recreate them again (see this helpful SO post) However, if I ran zappa manage dev migrate after that, I get InconsistentMigrationHistory: Migration admin.0001_initial is applied before its dependency accounts.0001_initial on database How should I do the same thing on the AWS RDS using Zappa or should I do something else? -
How to get the Refresh Token with the django-graphql-social-auth library
Hi I am using the django-graphql-social-auth library and whenever I create a social user using this mutation: import graphene import graphql_social_auth class Mutations(graphene.ObjectType): social_auth = graphql_social_auth.SocialAuthJWT.Field() and this Graphql mutation: mutation SocialAuth($provider: String!, $accessToken: String!) { socialAuth(provider: $provider, accessToken: $accessToken) { social { uid } token } } I am just able as you see to get the token. Because if add the refreshToken to be also returned from the mutation (just as I did with the token above) it says it refreshToken is not defined. So I am not actually sure about how to get the refreshToken using this library. -
django: View to delete html table row not taking effects in Database
I have a page that displays rows from a db table. I added a button to each row that is designed to delete the row upon its click as well as redirect toward a deleted confirmation page. Everything seems to work, unless that nothing gets deleted in the database table. Here is what my views.py look like: def ProductsView(request): queryset = Products.objects.all() products_list = list(queryset) request.session['context'] = products_list #table = ProductsTable(queryset) #context = {'table':table} return render(request, 'inventory.html', {'products_list':products_list}) def DeleteProduct(request, Id): Products.objects.filter(ProductId=Id).delete() return render(request,'delete_confirmation.html') and here is what the html page look like, including the code for the delete button <table class="table text-center table-bordered table-hover"> <thead class="thead-dark"> <tr> <th scope="col">ID</th> <th scope="col">NAME</th> <th scope="col">CATEGORY</th> <th scope="col">TAG NUMBER</th> <th scope="col">STOCK ON HAND</th> <th scope="col">DELETE</th> </tr> </thead> <tbody style="background-color: white"> {% for Products in products_list %} <tr> <td>{{ Products.ProductId }}</td> <td>{{ Products.ProductName }}</td> <td>{{ Products.ProductCategory }}</td> <td>{{ Products.ProductTagNumber }}</td> <td>{{ Products.StockOnHand }}</td> <td> <a class="btn btn-primary" href="{% url 'delete_confirmation' Id=Products.ProductId %}" style="color: white">Delete</a> </td> </tr> {% endfor %} </tbody> </table> I can't find out what I am doing wrong, I have been at it all day and need a pair of fresh eyes to look at it! Does anyone has a clue … -
How to optimize Django API Query
How can I optimize my api View or Serializer ? It takes more than 3 minutes to perform the task. I think it due to foreign key fields but even I retrieve them on the serializer fields, it still run slowly. api/View.py @api_view(['GET', 'POST']) def edge_list(request): """ List all edges of all networks, or create a new edge. """ if request.method == 'GET': edges = Edge.objects.all() context = {'request': request} # for filtering by field in url serializer = EdgeSerializer(edges, many=True, context=context) return Response(serializer.data) elif request.method == 'POST': serializer = EdgeSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.error, status=status.HTTP_400_BAD_REQUEST) api/serializers.py class EdgeSerializer(DynamicFieldsMixin, serializers.ModelSerializer): class Meta: model = Edge fields = ( 'id', 'edge_id', 'name', 'length', 'speed', 'lanes', 'param1', 'param2', 'param3', 'network', 'road_type', 'source', 'target' ) api/models.py class Edge(models.Model): network = models.ForeignKey(RoadNetwork, on_delete=models.CASCADE) source = models.ForeignKey(Node, related_name='source', on_delete=models.CASCADE, help_text='Source node of the edge', ) target = models.ForeignKey(Node, related_name='target', on_delete=models.CASCADE, help_text='Target node of the edge', ) road_type = models.ForeignKey(RoadType, on_delete=models.CASCADE, help_text='Roadtype of the edge' ) edge_id = models.PositiveBigIntegerField(db_index=True) name = models.CharField(max_length=80, blank=True, help_text='Name of the edge') geometry = models.LineStringField() length = models.FloatField() speed = models.FloatField(null=True, blank=True) lanes = models.SmallIntegerField(null=True, blank=True) param1 = models.FloatField(null=True, blank=True) param2 = models.FloatField(null=True, blank=True) param3 = models.FloatField(null=True, … -
how to make full html page as pfd in django
i have a html page in my django templates, its a pdf type, the for loop should make a transactions based on the number of which the object model returns, however i want every transaction to be in a full html page, and the other transaction come net page, i have tried to do it but seems a bit hard since im new to django html. {% extends "base.html" %} {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> {% block title %} Report {% endblock title %} <div id="container"> {% block content %} {% for transaction in transactions %} {% if transaction.complete %} <table class="tg"> <thead> <tr> <th class="tg-fv77" colspan="12" rowspan="2"><span style="color:#3531FF">Report For Tenant ( {{ transaction.chp_reference }} )</span></th> </tr> <tr> </tr> </thead> <tbody> <tr> <td class="tg-0pky" colspan="9">CHP Reference</td> <td class="tg-0pky" colspan="3">{{transaction.chp_reference}}</td> </tr> <tr> <td class="tg-0pky" colspan="9">Rent Effective From (dd/mm/yyyy)</td> <td class="tg-0pky" colspan="3">{{transaction.rent_effective_date}}</td> </tr> <tr> <td class="tg-0lax" colspan="9">CRA Fortnightly Rates valid for 6 months from</td> <td class="tg-0lax" colspan="3">{{transaction.cra_rate_from}}</td><hr> </tr> <tr> <td class="tg-0lax" colspan="9">Market Rent of the Property</td> <td class="tg-0lax" colspan="3">{{transaction.property_market_rent}}</td> </tr> <tr> <td class="tg-0lax" colspan="9">Number of Family Group(s)</td> <td class="tg-0lax" colspan="3">{{transaction.number_of_family_group}}</td> </tr> </tbody> </table> {% if transaction.complete %} <table class="tg" style="undefined;table-layout: fixed; width: 714px"> <colgroup> <col style="width: … -
Reference an unsaved field on a Django model when saving
I am uploading my media to an S3 bucket and would like to reference the name field before uploading to S3. class Customer(models.Model): name = CharField() img = ImageField(upload_to='<name>/avatars/') How do I use the name field dynamically in upload_to? -
Django: combining a DetailView and a form on the same view
Is there a way I can combine a detailview and a form into the same view? I'm making a rental system where when a user clicks on a particular house, he will be directed to a detailview page of that house. And after viewing the details of the house he intends to rent, he will fill a form while still on the detailview page then the form will be saved in the database. Here's what I have so far views.py class HouseDetailView(DetailView): model = House template_name = 'Home/detail.html' def get_context_data(self, **kwargs): context = super(HouseDetailView, self).get_context_data(**kwargs) context['house_list'] = House.objects.all() return context def Callback (request): form = CallbackForm() if request.method == 'POST': form = CallbackForm(request.POST) if form.is_valid(): form.save() messages.success(request, 'Callback Submission Successful.') return redirect('Home') context = {'form':form} return render(request, 'Home/callback.html', context) urls.py from django.urls import path from .views import ( HouseView, HouseDetailView, ) from . import views urlpatterns = [ path('Home/', views.Home, name='Home'), path('SignUp/', views.SignUp, name='SignUp'), path('Login/', views.Login, name='Login'), path('house/', HouseView.as_view(), name='house'), path('callback/', views.Callback, name='callback'), path('Logout/', views.Login, name='Logout'), path('<slug:slug>/', HouseDetailView.as_view(), name='detail'), ] forms.py from django.forms import ModelForm from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django import forms from .models import House, Lease, Agent, Customer, Callback class CreateUserForm(UserCreationForm): class Meta: model … -
I can't get a value from a field in a one-to-one relationship, tabularinline
How do I get the value from the field in a one-to-one relationship. The tables Tables and Table are linked using TabularInline. And I want to get a value from a field by OneToOneField relationship. I do it with signals. In this case I'm using post_save. I get an error "Tables has no data" class Tables(models.Model): title = models.CharField(max_length=10) class Table(models.Model): count = models.IntegerField() obj = models.OneToOneField(Tables, on_delete=models.CASCADE, related_name="data") @receiver(post_save, sender = Tables) def create(instance, sender, **kwargs): print(instance.data) If I write it like this, it returns the old queryset @receiver(post_save, sender = Tables) def create(instance, sender, **kwargs): print(Table.objects.filter(table__id=instance.id))