Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
OperationalError at ... no such column: funcionarios_funcionario.user_id
I am a newbie in Django and I am facing a problem. I am getting this message in the console: django.db.utils.IntegrityError: The row in table 'funcionarios_funcionario' wi th primary key '1' has an invalid foreign key: funcionarios_funcionario.empres a_id contains a value '1' that does not have a corresponding value in empresa_ empresa.id. and when I run the app, I got this message OperationalError at /admin/documentos/documento/add/ no such column: funcionarios_funcionario.user_id Request Method: GET Request URL: http://127.0.0.1:8000/admin/documentos/documento/add/ Django Version: 3.1.2 Exception Type: OperationalError Exception Value: no such column: funcionarios_funcionario.user_id the class documentos from django.db import models from apps.funcionarios.models import funcionario # Create your models here. class Documento(models.Model): descricao = models.CharField(max_length=100) pertence = models.ForeignKey(funcionario, on_delete=models.PROTECT) def __str__(self): return self.descricao the class funcionarios from django.db import models from django.contrib.auth.models import User from apps.departamentos.models import Departamento from apps.empresa.models import Empresa class funcionario(models.Model): nome = models.CharField(max_length=100) user = models.OneToOneField(User, on_delete=models.PROTECT) departamentos = models.ManyToManyField(Departamento) empresa = models.ForeignKey(Empresa, on_delete=models.PROTECT) def __str__(self): return self.nome How I can solve this? Thank you very much! -
wsgiref exception 'NoneType' object has no attribute 'split' when opening a file from media folder
When I open a file from media folder, I keep getting this exception from wsgiref 'NoneType' object has no attribute 'split' urls.py path('media/<file_id>/', views.media), views.py def media(request, file_id): file = get_object_or_404(File, id=file_id) file = file.file return FileResponse(file, as_attachment=False, filename=file.name) models.py class File(models.Model): id = models.AutoField(primary_key=True) file = models.FileField(null=False, blank=False, upload_to='media') belongs_to = models.ForeignKey('Content', null=False, blank=False, on_delete=models.CASCADE) date = models.DateTimeField(null=False, blank=False, auto_now_add=True) @property def filename(self): return os.path.basename(self.file.name) I also noticed that it only shows for mp4 and mp3 mp4 : The error keeps showing in an infinite loop mp3 : The error shows one time only Does anyone have an explanation to this ? Any help would be appreciated. -
Django get pk inside of decorator
Imagine the following pseudo code at decorators.py where you need the actual pk of the object where this decorator get placed onto: def count_view(function): def wrap(request, *args, **kwargs): pk = ('??? Missing ???') user = get_user_model().objects.get(pk=request.user.pk) hit_objects = Hit.objects.filter(viewer=user, content_object=pk) if hit_objects: return function(request, *args, **kwargs) else: new_hit = Hit.objects.create(viewer=user, content_object=pk) new_hit.save() return function(request, *args, **kwargs) wrap.__doc__ = function.__doc__ wrap.__name__ = function.__name__ return wrap How can I access the objects pk I'm placing this decorator on? e.g. @count_view def PostDetail(request, pk): post = get_object_or_404(Post, pk=pk) ... -
DoesNotExist at /profiles/user-profile/ UserProfile matching query does not exist
I am trying to add a follow toggle but In my views I am getting error in matching query set. The userprofile exist in database than still I dont why is it happening. I hope you guess can figure out my mistake and tell me how can I fix it. I am learning django if you help me than that means a lot. I shall be thankful to you. if more code required for help than let me know i will share that. class UserProfileFollowToggle(View): def post(self, request, *args, **kwargs): print(request.POST) user_to_toggle = request.POST.get('username') print(user_to_toggle) profile_ = UserProfile.objects.get(user__username__iexact=user_to_toggle) user = request.user if user in profile_.follower.all(): profile_.follower.remove(user) else: profile_.follower.add(user) return redirect("/posts/list/") trace back Environment: Request Method: POST Request URL: http://127.0.0.1:8000/profiles/user-profile/ Django Version: 3.0.3 Python Version: 3.8.3 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'bootstrap3', 'accounts', 'posts', 'profiles'] 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:\Users\AHMED\anaconda3\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\AHMED\anaconda3\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\AHMED\anaconda3\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\AHMED\anaconda3\lib\site-packages\django\views\generic\base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\AHMED\anaconda3\lib\site-packages\django\views\generic\base.py", line 97, in dispatch return handler(request, *args, … -
When I am defining the URL patterns in django version 2.1.4 , I am getting an error. please show me a path
enter code hereError on running the project from CMD: enter code herepath('about/',views.about), enter code hereAttributeError: module 'testapp.views' has no attribute 'about' enter code hereURLs.py: enter code herefrom django.contrib import admin enter code herefrom django.urls import path enter code herefrom testapp import views enter code hereurlpatterns = [ enter code herepath('about/',views.about),] enter code hereview.py enter code herefrom django.shortcuts import render enter code herefrom django.http import HttpResponse enter code heredef about(request): enter code heres=" This is an about page" enter code herereturn HttpResponse(s) -
Calling view name that belongs to a different app
I am trying to a similar task as in this thread here : calling a view when a button is clicked. However, the view name that the button is calling belongs to a different app. <button class="button table_mgt" > <a href="{% url 'table_view' %}">Table Mgt</a> </button> This button sits in a template called dashboard.html which belongs to an app called account. But the view named table_view belongs to another app called table. Both apps belong to the same root. What do I need to set up for the above code to work? -
Testing CSRF protecting views in Django Rest Framework
I was hitting a wall when it comes to testing my APIViews that require authentication. I wanted to test that both CSRF and authentications + permissions were enforced as expected. Some information of my setup: My view is a Django Rest Framework rest_framework.views.APIView which implements the post function. Default authentication classes are SessionAuthentication Default permission classes are IsAuthenticated Test cases use the APIClient to issue requests When initializing the APIClient with enforce_csrf_checks=True I still can't seem to get the response I'm expecting when it comes to views that require authentication (using the IsAuthenticated permission class). For non-authenticated views, I can test CSRF protection, no problem. The view in question: @method_decorator(csrf_protect) def post(self, request, format=None): """ Create a new user. """ serializer = UserSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) The test code: client = APIClient() response = client.post(url, data) # Success! client = APIClient(enforce_csrf_checks=True) response = client.post(url, data) # 403 FORBIDDEN For authenticated views, things get weird (this view uses the IsAuthenticated permission: def get(self, request, format=None): """ Get request user. """ user = User.objects.get(pk=request.user.id) serializer = UserSerializer(user) return Response(serializer.data, status=status.HTTP_200_OK) The test code: self.client = APIClient(enforce_csrf_checks=True) self.client.login(email='t@t.se', password='pw') self.client.get(url) # Succeeds, even though it should not. … -
Celery doesn't work with Django on Heroku. Getting `Cannot connect to amqp://guest:**@127.0.0.1:5672//: [Errno 111] Connection refused` error
I can't seem to get Celery to work with Django using Heroku. I've tried many different combinations of fixes over the past two days and can't seem to get it done. The error that I'm getting is this [2020-10-10 22:29:25,246: ERROR/MainProcess] consumer: Cannot connect to amqp://guest:**@127.0.0.1:5672//: [Errno 111] Connection refused. I use a heroku add-on called Redis Cloud for redis, (hence the celery settings using REDISCLOUD_URL as an environment variable. I'm basically at a complete loss on what to do at this point as I've looked at many tutorials, stackoverflow questions, etc. Thank you. Here is my complete set up. . ├── LICENSE ├── Pipfile ├── Pipfile.lock ├── Procfile ├── README.md ├── manage.py ├── runtime.txt ├── static │ └── README.md └── wowzers ├── __init__.py ├── celery.py ├── settings.py ├── urls.py └── wsgi.py __init__.py file in wowzers/ from __future__ import absolute_import, unicode_literals # This will make sure the app is always imported when # Django starts so that shared_task will use this app. from .celery import app as celery_app __all__ = ("celery_app",) celery.py file in wowzers/ from __future__ import absolute_import, unicode_literals import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault("DJANGO_SETTINGS_MODULE", "wowzers.settings") app … -
DJANGO ORM vs JUPYTERLAB.. can you do the same in ORM vs JupyterLab?
i want to analyse in Pandas/Numpy/MatPlotLib my sales in a project/site. can i do the same analysis in ORM vs JupyterLab? (im using SQLite3) which do you prefer? if not, how do i use the SQLITE DB from that project, in a JupyterLab project??? -
How can I program a dynamic sitemap in django, mine not working
The static part works fine but the dynamic posts of my blog app are not generated from django.contrib.sitemaps import Sitemap from django.urls import reverse from .models import Post class PostSitemap(Sitemap): changefreq = "weekly" priority = 0.9 def items(self): return Post.objects.all() I'm not able to get a dynamic sitemap with my blog and my Post class in models: class Post(models.Model): title=models.CharField(max_length=100) header_image = models.ImageField(null=True , blank=True, upload_to="images/") title_tag=models.CharField(max_length=100) author= models.ForeignKey(User, on_delete=models.CASCADE) body = RichTextUploadingField(extra_plugins= ['youtube', 'codesnippet'], external_plugin_resources= [('youtube','/static/ckeditor/youtube/','plugin.js'), ('codesnippet','/static/ckeditor/codesnippet/','plugin.js')]) #body = models.TextField() post_date = models.DateTimeField(auto_now_add=True) category = models.CharField(max_length=50, default='uncategorized') snippet = models.CharField(max_length=200) likes = models.ManyToManyField(User, blank=True, related_name='blog_posts') def total_likes(self): return self.likes.count() class Meta: verbose_name = "Entrada" verbose_name_plural = "Entradas" ordering = ['-post_date'] def __str__(self): return self.title + ' | ' + str(self.author) def get_absolute_url(self): return reverse('home') If any one can help me I would be very grateful. urls.py: from django.contrib.sitemaps.views import sitemap from theblog.sitemaps import PostSitemap, StaticSitemap sitemaps = {'static': StaticSitemap, 'blog': PostSitemap} -
Django count object views on a practically and fair base
I was searching for a solution to practically and fair track views/hit's of my post elements. Sadly all solutions I found where based on the users IP or Session-Key. In practices such a solution can be used but is somehow also very stupid I guess. All these information are coming from the client directly and can be faked either be logging-in again and get a new session key or using a proxy/VPN etc... There are several automatons to accomplish such a task at scale, see how the music industry, especially spotify gets frauded by such attacks. My Idea now is to temporary bound a view/hit to the user for at least 24 hrs. After time has went by, the table gets cleared out by celery as a periodical task. Before deleting the temporary user counted hit, celery syncs all hits to the actual post object, as this is just a IntegerField I can count-up using '+=' A model for this could look like this: class Hit(models.Model): content_type = models.ForeignKey(ContentType, limit_choices_to=hit_post_models, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') viewer = models.ForeignKey(User, on_delete=models.CASCADE) date = models.DateTimeField(auto_now=True) Now I'm at the point to get a bit confused by the actual counting implementation. … -
how to get parent object from child object in python
I have two models(classes) that one inherits from another. GRESubjectCertificate as parent class GRESubjectCertificate(LanguageCertificate): quantitative = models.PositiveSmallIntegerField() verbal = models.PositiveSmallIntegerField() analytical_writing = models.DecimalField( max_digits=2, decimal_places=1, ) total = models.PositiveSmallIntegerField() and GREBiologyCertitficate as child: class GREBiologyCertificate(GRESubjectCertificate): cellular_and_molecular = models.PositiveSmallIntegerField() organismal = models.PositiveSmallIntegerField() ecology_and_evolution = models.PositiveSmallIntegerField() I want to cast an object from GREBiologyCertificate to GRESubjectCertificate by parent class name in lower but it does not work. I have used before this solution to convert child object to parent object but now it fails. instance1 = GREBiologyCertificate() instance2 = instance1.gresubjectcertificate 'GREBiologyCertificate' object has no attribute 'gresubjectcertificate' -
Got a 500 HTTP ERROR uploading image django-CKEDITOR
Using Django 3.1 and ckeditor 6.0.0 and standard django debug server. I get 500 http error when I upload an image through RichTextUploadingField() My urls.py: from django.contrib import admin from django.urls import path, include from filebrowser.sites import site from django.conf import settings from django.views.static import serve from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('ckeditor/', include('ckeditor_uploader.urls')), path('', include('ntgiapp.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Key part of settings.py: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'ntgiapp/static') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'ntgiapp/media') CKEDITOR_UPLOAD_PATH = "" CKEDITOR_FILENAME_GENERATOR = 'utils.get_filename' CKEDITOR_IMAGE_BACKEND = 'Pillow' -
view must be a callable or a list/tuple in the case of include() | Class-based views error
I don't know why, but I got this weird error, view must be a callable or a list/tuple in the case of include(). This is my views.py: class HelloWorldView(View): def get(self, request, *args, **kwargs): context=[ ] return render(request, 'main.html', context) and my urls: urlpatterns = [ path('', HelloWorldView.as_view(), name='helloWorld'), ] -
Content of database not showing up in Django
I have some problems to get the content out of the django database. I'm a bloody beginner at django so I did some tutorials. They've worked fine. Now I want to reproduce them in my own project with own variables so I can see if I've understood all the stuff. So to come to my problem I initalized my modules in models.py from django.db import models class Aboutme(models.Model): author = models.CharField(max_length=30) ... This works because I could add content to the database. So there is no mistake. Now in the views.py from django.shortcuts import render from portfolio.models import Aboutme def portfolio_index(request): aboutme = Aboutme.objects.all() context = {'aboutme': aboutme} return render(request, 'portfolio_index.html', context) So finally in my HTML file, called portfolio_index.html, I call the content via <h1>{{ aboutme.author }}</h1> I guess it's right. But the content of author doesn't showup, so what did I miss? I can call static files via django, so couldn't be something wrong with django... Can anyone help. Thanks in advance. -
Passing model database metric to view
I am creating a Django app that displays a certain number of buttons (called tables). Below are my files: model.py class Table(models.Model): id_num = models.IntegerField(verbose_name="Table Number", db_index=True) slug = models.SlugField(max_length=200, db_index=True) max_guest_num = models.IntegerField(verbose_name="Max Number of Guests", default=0) description = models.TextField(verbose_name="Table Note", blank=True) available = models.BooleanField(verbose_name="Availability", default=True) last_checkin_time = models.DateTimeField(verbose_name="Checkin Time") last_checkout_time = models.DateTimeField(verbose_name="Checkout Time") created = models.DateTimeField(verbose_name="Date of creation", auto_now_add=True) updated = models.DateTimeField(verbose_name="Last Updated", auto_now=True) admin.py @admin.register(Table) class TableAdmin(admin.ModelAdmin): list_display = ['id_num', 'slug', 'max_guest_num', 'available', 'created', 'updated'] view.py from django.http import HttpResponse from django.shortcuts import render def table_view(request): return render(request, 'tables/table_view.html', {'table_num': '???'}) table_view.htlm (template) {% extends "base.html" %} {% block title %}Dashboard{% endblock %} {% block content %} <h1>Table View</h1> <div id="table_display"> <button class="button table1">Table 1</button> <button class="button table2">Table 2</button> <button class="button table3">Table 3</button> <button class="button table4">Table 4</button> <button class="button table5">Table 5</button> </div> {% endblock %} I have two questions: 1 - In the template, I would like create the number of buttons based on the number of table instances created in the database. How do I retrieve and pass this variable into the view.py (this is the right place to pass into, I guess?) 2 - In the template, what is the best way to create these … -
How to create file downloading link without leaking the address of file in Django
This might perhaps be a simple question, but I somehow just can not find the solution. I am trying to develop a website using Django where a user uploads an mp3 file and then requests to process their uploaded file. I perform some processes on users' uploaded mp3 file and then provide them a demo of the result (a demo.mp3 file). So, they can download the demo of their result for free. After paying, they'll be able to download the full version of the processed mp3 file (full.mp3 file). I produce and store the demo and the full version of the results at the same time (as a user submits a request). I do not want users to be able to access the full.mp3 file unless they have paid. Currently, I create two random strings of 32 characters for each user's request. I store these strings in the Django model (dir_code and demo_dir_code fields as shown below) and then create two directories on the server (within the MEDIA_ROOT directory) with the name of these strings. class Request(models.Model): dir_code = models.CharField(max_length=32, null=False, blank=False, default='') demo_dir_code = models.CharField(max_length=32, null=True, blank=True, default='') ... In one of these directories, I put the results of … -
Django Gunicorn Nginx Worker TIMEOUT Upstream TIMED OUT ERROR
I've a web application running on Django, Gunicorn and Nginx on Azure Ubuntu VM server. When running a longer requests, the request times out and goes to 504/502 timed out error. I've tried changing timeout options in both Nginx and GUnicorn config, but didn't work. Below are my config files, Nginx.conf server { listen 80; server_name 0.0.0.0; location /static { alias /home/rootadmin/WeIntelli/static; } location / { proxy_pass http://unix:/home/rootadmin/WeIntelli/WeIntelli.sock; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_connect_timeout 900; proxy_send_timeout 900; proxy_read_timeout 900; proxy_buffers 32 4k; } } Supervisor.conf [program:WeatherIntelligence] directory=/home/rootadmin/WeIntelli command=/home/rootadmin/WeIntelli/venv/bin/gunicorn --log-level=debug --workers=5 --timeout=600 --keep-alive=600 --worker-class=gthread --threads=3 --bind unix:/home/rootadmin/WeIntelli/WeIntelli.sock WeIntelli.wsgi:application user=rootadmin autostart=true autorestart=true stopasgroup=true killasgroup=true stderr_logfile=/home/rootadmin/WeIntelli/WeIntelli.err.log stdout_logfile=/home/rootadmin/WeIntelli/WeIntelli.out.log Request you to please help me resolve this, thanks in advance. -
TemplateDoesNotExist at /home/ entries/index.html, entries/entry_list.html
I need an extra pair of eyes, I just cannot see the mistake, below you can see all the necessary files, I think the error comes from there views.py from django.shortcuts import render from django.views.generic import ListView from .models import Entry class HomeView(ListView): model = Entry template_name='entries/index.html' urls.py from .views import HomeView from django.urls import path urlpatterns = [ path('home/', HomeView.as_view(), name='blog-home') ] base urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('entries.urls')) ] -
Heroku release fails on Key Error: 'user' for established Django project
After minor edits to the database (SQLite) and a revision number in settings.py I tried to push the changes to Heroku, which initially declared that their were unpulled files; this made no sense as this is my private project and a similar update worked two days before. The pull allowed a "git push heroku master". The code would run and attempt to deploy but return the following error block: ============ Operations to perform: Apply all migrations: admin, auth, brg_calcs, contenttypes, glossary, sessions, users Traceback (most recent call last): File "manage.py", line 21, in main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/init.py", line 401, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/init.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/base.py", line 85, in wrapped res = handle_func(*args, **kwargs) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/commands/migrate.py", line 201, in handle pre_migrate_state = executor._create_project_state(with_applied_migrations=True) File "/app/.heroku/python/lib/python3.7/site-packages/django/db/migrations/executor.py", line 79, in _create_project_state migration.mutate_state(state, preserve=False) File "/app/.heroku/python/lib/python3.7/site-packages/django/db/migrations/migration.py", line 87, in mutate_state operation.state_forwards(self.app_label, new_state) File "/app/.heroku/python/lib/python3.7/site-packages/django/db/migrations/operations/fields.py", line 158, in state_forwards old_field = model_state.fields.pop(self.name) KeyError: 'user' After this error, I tried re-loading the program on my laptop from GitHub. Same error. I have run "makemigrations" and "migrate", … -
Django: Store a CSS class in database
So I made an HTML button and on clicking to it, a CSS class is added to it using some Jquery/javascript logic. Is there any way I can store this animation on my database so that on page refresh the class should still stay. Or if I can do that with Javascript. A little guidance would be appreciated. Regards Fanceh -
What is an effective way to bulk create objects with related objects in django?
I have the following models: class LocationPoint(models.Model): latitude = models.DecimalField(max_digits=16, decimal_places=12) longitude = models.DecimalField(max_digits=16, decimal_places=12) class Meta: unique_together = ( ('latitude', 'longitude',), ) class GeoLogEntry(models.Model): device = models.ForeignKey(Device, on_delete=models.PROTECT) location_point = models.ForeignKey(LocationPoint, on_delete=models.PROTECT) recorded_at = models.DateTimeField(db_index=True) created_at = models.DateTimeField(auto_now_add=True, db_index=True) I have lots of incoming records to create (probably thousands at once). Currently I create them like this: # Simplified map function contents (removed mapping from dict as it's unrelated to the question topic points_models = map(lambda point: LocationPoint(latitude=latitude, longitude=longitude), points) LocationPoint.objects.bulk_create( points_models, ignore_conflicts=True ) # Simplified map function contents (removed mapping from dict as it's unrelated to the question topic geo_log_entries = map( lambda log_entry: GeoLogEntry(device=device, location_point=LocationPoint.objects.get(latitude=latitude, longitude=longitude), recorded_at=log_entry.recorded_at), log_entries ) GeoLogEntry.objects.bulk_create(geo_log_entries, ignore_conflicts=True) But I think it's not very effective because it runs N SELECT queries for N records. Is there a better way to do that? I use Python 3.9, Django 3.1.2 and PostgreSQL 12.4. -
How can i create swager document for django api?
there is FBV in Django and it log_in and when i use swagger ..it did not create input in document. """ @api_view(['POST']) def log_in(request): """ description: This API deletes/uninstalls a device. parameters: - name: username type: string required: true location: body """ payload = json.loads(request.body) phone = payload.get('username', None) user_type = payload.get('user_type', None) """ -
CSS not loading wrong MIME type on django and next.js
I am having an issue with NextJs and django. On the djnago side, when I run the server I get the mime css error. Any help? -
Getting foreign key values from Django values()
I am getting data objects from Django models using tabledata=Entity.objects.filter(quarter=1) Using this method, I am able to extract the values of the objects specified by the foreign key like so tabledata[0].creator.name However when I changed the code to tabledata=Entity.objects.filter(quarter=1).values() I can extract only foreign key values but not the values of the object data linked with the foreign key. Something like tabledata[0][creator][name] does not work Is there a way to extract the values this way?