Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using Django "rules" with CBVs doesn't seem to work
Each restaurant can have multiple managers. class Restaurant(models.Model): ... managers = models.ManyToManyField(User, related_name='restaurants_which_they_manage') Only restaurant managers can change a restaurant listing. I'm using django-rules to enforce this. I've got a predicate that creates a nice verbose "is_restaurant_manager" reference : @rules.predicate def is_restaurant_manager(user, restaurant): return user in restaurant.managers.all() And here is the permission : rules.add_perm('restaurants.change_restaurant', is_restaurant_manager) Finally, here is my view : class RestaurantChange(PermissionRequiredMixin, UpdateView): model = Restaurant permission_required = 'restaurants.change_restaurant' fields = ['name', 'description', ] I've got two tests. Test A checks that the permission works properly : self.assertEqual(rules.has_perm('restaurants.change_restaurant', self.user, self.restaurant), True) This first test passes successfully. Test B attempts to access the url with a valid user : url = reverse('restaurants__restaurant_change', kwargs={'pk': self.restaurant.key,}) response = self.client.get(url) self.assertEqual(response.status_code, 200) Test B fails, as I get a redirection. This also happens if I try to access the url via the browser. The redirection goes to the login process, as though the user didn't have permission to access the view. What's wrong with my code ? -
Cleared static and now collect static won't work
My static files wouldn't stay updated so I just ran python manage.py collectstatic --noinput --clear on my server to clear everything. Now when I run python manage.py collectstatic nothing happens. I have tried service unicorn restart and service gninx restart but still nothing changes. Here is a link to my website so you can what is happening. Obviously I would like it look styled, which it does not. http://evverest.com -
Getting name+otherinfo out of querset django
I am trying to get a dict out of a Queryset. I have a query set called showroom. When I just print showroom it gives this information. <QuerySet [<LeadFormData: Lead form: testing 2 leadform>]> When I use shoowroom.value() it shows me this. <QuerySet [{'last_updated': datetime.datetime(2017, 10, 9, 10, 5, 33, 182308), u'id': 5,'created': datetime.datetime(2017, 10, 9, 10, 5, 33, 182296)}]> I am trying to learn how filters work in a query set but I am not sure on how to get the information out of this above code and put it in a dict like this. {u'testing 2 leadform': [{'count': 5, 'ts': datetime.date(2017, 10, 9)}, {'count': 0, 'ts': datetime.date(2017, 10, 9)}]} Since I have to append to another dict which takes in the data in the above format. This is what I have currently, I am no way sure on how to take out the name from the Queryset since the error I get is Querset does not contain .name dictToStore = {} for s in showroom: dictToStore[s.name] = {'count' : s.id , 'ts':last_updated ,'ts' : last_updated} -
Unable to generate migrations in Django 1.11
On a blank MySQL database, I generated migrations for a Django 1.11 project with: python manage.py makemigrations I have several custom inter-dependent apps, but all the migrations generated without error. However, when I tried to apply these migrations with: python manage.py migrate it applies most app migrations just fine, but with some custom FeinCMS migrations with: Applying page.0001_initial...Traceback (most recent call last): File "manage.py", line 9, in <module> execute_from_command_line(sys.argv) File "/usr/local/myproject/.env/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/usr/local/myproject/.env/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/myproject/.env/local/lib/python2.7/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/myproject/.env/local/lib/python2.7/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/usr/local/myproject/.env/local/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 204, in handle fake_initial=fake_initial, File "/usr/local/myproject/.env/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 115, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/usr/local/myproject/.env/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 145, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/usr/local/myproject/.env/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 244, in apply_migration state = migration.apply(state, schema_editor) File "/usr/local/myproject/.env/local/lib/python2.7/site-packages/django/db/backends/base/schema.py", line 93, in __exit__ self.execute(sql) File "/usr/local/myproject/.env/local/lib/python2.7/site-packages/django/db/backends/base/schema.py", line 120, in execute cursor.execute(sql, params) File "/usr/local/myproject/.env/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 65, in execute return self.cursor.execute(sql, params) File "/usr/local/myproject/.env/local/lib/python2.7/site-packages/django/db/utils.py", line 94, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/usr/local/myproject/.env/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 65, in execute return self.cursor.execute(sql, params) File "/usr/local/myproject/.env/local/lib/python2.7/site-packages/django/db/backends/mysql/base.py", line 101, in execute return self.cursor.execute(query, args) File "/usr/local/myproject/.env/local/lib/python2.7/site-packages/MySQLdb/cursors.py", line 205, in execute … -
How to filter object by list of parametrs Django?
If I try to filter some object by list of parameters, it doesn't work, how do I filter it? I have some list for example: brands_list = ['Nike', 'HBO'] how to filter object by this list product = Product.objects.filter(brand__name_of_brand=brands_list) If I run this it gives me nothing empty query set, how can I filter by list parameters and output all in one variable? If i try to filter some object by list of parameters, it doesn't work, how to filter it? -
How do I compare if the value obtained from a radio button is equal to that of a column of a table in Django?
I am doing a questionnaire system in Django and would like to check if the value obtained on the radio button is equal to that of the {{gabarito.gabarito}}, which is present in the system. I would like this to be checked and the user to stay on the same page, without the option of the user replying again. index.html <form method="post"> <div> <input id="radioA" type="radio" name="radios" value="A"> <label for="radioA"><span><span></span></span>a) {{opcao.aOpcao}}</label> </div> <div> <input id="radioB" type="radio" name="radios" value="B"> <label for="radioB"><span><span></span></span>b) {{opcao.bOpcao}}</label> </div> <div> <input id="radioC" type="radio" name="radios" value="C"> <label for="radioC"><span><span></span></span>c) {{opcao.cOpcao}}</label> </div> <div> <input id="radioD" type="radio" name="radios" value="D"> <label for="radioD"><span><span></span></span>d) {{opcao.dOpcao}}</label> </div> <div> <input id="radioE" type="radio" name="radios" value="E"> <label for="radioE"><span><span></span></span>e) {{opcao.eOpcao}}</label> </div> <input type="submit" id="btnSubmit"> </form> <script type="text/javascript"> $(function(){ $('#btnSubmit').click(function(){ var radioValue = $("input[name=radios]:checked").val(); alert(radioValue); $.ajax({ url: '/submit', data: {value:radioValue}, type: 'POST', success: function(response){ console.log(response); }, error: function(error){ console.log(error); } }); }); }); -
django-import-export override not working
I am overriding the django-import-export resource's methods. But only parent methods are executed. models.py class Model(models.Model): modelField1 = models.CharField( modelField2... modelField3... admin.py class ResourceClass(resources.ModelResource): def before_import(self, dataset, using_transactions, dry_run, **kwargs): print("INside BEfore IMport") dataset.headers = ('modelField1', 'modelField2', ...) del dataset[0] def get_instance(self, instance_loader, row): print("Inside get instance") return False def get_or_init_instance(self, instance_loader, row): print("INside Get or init") instance = self.get_instance(instance_loader, row) if instance: return (instance, False) else: return (self.init_instance(row), True) @admin.register(Model) class ModelAdmin(ImportExportModelAdmin): class Meta: model = MOdel resource_class = ModelResource list_display = ('modelField1', 'modelField2', ...) search_fields = ('modelField1', 'modelField2', ...) I am not at all getting print statements in console. Error is thrown directly from the parent methods. They should not be executed at all. AM I right ? Line number: 1 - u"Column 'id' not found in dataset. Available columns are: [u'Col1', u'Col2', u'Col2', ...]" Traceback (most recent call last): File "/home/aswin/projects/mastercityenv/local/lib/python2.7/site-packages/import_export/resources.py", line 434, in import_row instance, new = self.get_or_init_instance(instance_loader, row) File "/home/aswin/projects/mastercityenv/local/lib/python2.7/site-packages/import_export/resources.py", line 258, in get_or_init_instance instance = self.get_instance(instance_loader, row) File "/home/aswin/projects/mastercityenv/local/lib/python2.7/site-packages/import_export/resources.py", line 252, in get_instance return instance_loader.get_instance(row) File "/home/aswin/projects/mastercityenv/local/lib/python2.7/site-packages/import_export/instance_loaders.py", line 32, in get_instance params[field.attribute] = field.clean(row) File "/home/aswin/projects/mastercityenv/local/lib/python2.7/site-packages/import_export/fields.py", line 63, in clean list(data.keys()))) KeyError: u"Column 'id' not found in dataset. Available columns are: [u'Col1', u'Col2', u'Col2', … -
how to get specific list with all data from a queryset django?
on server sends this data: Object { categoryes: Array[2], brands: Array[2], discount_list: "all", category_slug: "accessories", category_of_relationsheep: "m" } if i print request.POST in server side i got this: <QueryDict: {'categoryes[]': ['Accessories', 'Bands'], 'brands[]': ['Nike', 'HBO'], 'discount_list': ['all'], 'csrfmiddlewaretoken': ['S7MXVEdQLd6u0fr4FugEwlupa45oChmw3TeItB4BEUHUHSsxrmVRuAcAhFxYQfpk'], 'category_slug': ['accessories'], 'category_of_relationsheep': ['m']}> hot i can get a list for example "categoryes[]" (but why it called like this with brackets?) ok if i do like this: print(request.POST.get("categoryes[]")) it will give the only last object, how to get full list? specific like cotegoryes? if make like for keys, values in request.POST.items(): print(values) it print me all values in this dict, but i don't know from where this values? if i make this: for keys, values in request.POST.items(): if 'categoryes[]' == keys: print(values) it give the same only one object related to categoryes but in this list more than 1 object -
Django 1.10 Mezzanine Admin, Some URLs Broken
Any URLs related to changing and editing Pages, Forms, and other Mezzanine objects are broken on my Django 1.10 Mezzanine deployment. View created form: Attempt to edit form (raises custom 404): Attempt to view history: Attempt to delete My URLs: urlpatterns = [ # url(r'^static/(?P<path>.*)$', serve, {'document_root': settings.STATIC_ROOT}), url(r'^$', lambda request: redirect('tiles') if request.user and request.user.is_authenticated() else redirect('login')), # url(r'^$', login_required(lambda request: redirect('tiles'), redirect_field_name='login')), url("^$", direct_to_template, {"template": "index.html"}, name="home"), url("^/", include("mezzanine.urls")), url(r'^help/$', views.help, name='help'), url(r'^content/', include('content.urls')), url(r'^directory/', include('directory.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^login/$', auth_views.login, name='login'), url(r'^logout/$', auth_views.logout, name='logout'), url(r'^auth/', include('rest_framework_social_oauth2.urls')), url(r'^oauth/', include('social_django.urls', namespace='social')), # <-- url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')) ] -
For all but the last in Django template [duplicate]
This question already has an answer here: Django template for loop - Last iteration 2 answers Is there a way to do some logic for all runs of a for loop just not the last in a Django template? Specifically, for something like the below: {% for e in emails %} {{e.email_address}}; {% endfor %} The ';' gets included each time but ultimately I would like to ignore it on the last run. I have similar use cases for similar gramatical tasks. -
Multiple Celery Progress Bars
Question I have a Django site using Celery + RabbitMQ as a task queue for long running tasks. I'm storing the results in Redis. I've been able to show the progress of one task in a bootstrap progress bar using Celery's update_state and doing an ajax post to the Redis DB via a button to retrieve the current state. Ideally, I would like to show each task currently running or recently complete that is in Redis with it's own progress bar. Currently, I am only able to show the progress of the current task kicked off by my little Click Here button. I have tried to make multiple classes for the progress bars, but honestly I am lost as to how to do this and can't seem to find anything on how to do something like this. I've tried to upload as much of my code as possible. Any help would be greatly appreciated! Code urls.py urlpatterns = [ url(r'^poll_state$', poll_state, name="poll_state"), url(r'^do_task$', do_task, name="do_task"), ] views.py from django.shortcuts import render import json from celery.result import AsyncResult from django.shortcuts import render_to_response from django.http import HttpResponse from django.views.generic.base import View from django.views.decorators.csrf import csrf_exempt @csrf_exempt def do_task(request): data = 'Fail' if … -
Wagtail - Django Migration
So I have been set up with a wagtail project, and have gotten as far as getting the site and database setup on heroku. I am a total noob with wagtail and Django so excuse my stupidness! The issue I am experiencing is with the database. I have run python manage migrate But I just get the default wagtail site, with the one page. None of the templates or pages in the folder are shown, so I assume I need an sql export of the database? The folders do have migrations scripts which I believed would put in the relations to the database, but obviously not as I thought it would run with the migrate script? This is the folder structure so any help would be much appreciated.... | .babelrc | .bowerrc | .gitignore | .jscsrc | .jshintrc | .slugignore | bower.json | fabfile.py | gulpfile.js | gunicorn.py.ini | manage.py | package.json | Procfile | README.md | requirements.txt | runtime.txt | server.crt | server.csr | server.key | server.pass.key | tree.txt | webpack-stats.json | webpack.config.js | wsgi.py | +---project | | processors.py | | urls.py | | utils.py | | wsgi.py | | __init__.py | | | +---apps | | | … -
Equivalent between `MySQL JOIN` and Django
I'm using Django 1.11 and I would like to get the correct syntax in order to translate my MySQL Join request to Django QuerySet Syntax. I have 3 different models (1 Model in my Identity application and 2 Models in my Fiscal application) as following : #Identity.Individu class Individu(models.Model): NumeroIdentification = models.CharField(max_length=30, null=True, verbose_name='Numero Identification physique', unique=True) Civilite = models.CharField(max_length=12,choices=CHOIX_TITRE, verbose_name='Civilité') NomJeuneFille = models.CharField(max_length=30, verbose_name='Nom de jeune fille', blank=True) Nom = models.CharField(max_length=30, verbose_name='Nom de famille') Prenom = models.CharField(max_length=30, verbose_name='Prénom(s)') #Fiscal.Profession class Profession (models.Model) : Employe = models.ForeignKey(Individu, related_name='Individu', verbose_name='Individu', null=False, to_field='NumeroIdentification') Entreprise = models.ForeignKey(Societe, related_name='Société', verbose_name='Société', null=False, to_field='NumeroIdentification') NumeroImpot = models.CharField(max_length=30, null=True, verbose_name='Numéro Imposition', unique=True) Profession = models.CharField(max_length=30, verbose_name='Profession') #Fiscal.Salaire class Salaire (models.Model) : Employe = models.ForeignKey(Individu, related_name='Salaire_Individu', verbose_name='Salaire_Individu', null=False, to_field='NumeroIdentification') Salaire_B_mensuel = models.IntegerField(verbose_name='Salaire Brut Mensuel') Salaire_N_mensuel = models.IntegerField(verbose_name='Salaire Net Mensuel') With Mysql, I have this request which works fine : SELECT * FROM Identity_individu i INNER JOIN Fiscal_profession p ON i.NumeroIdentification = p.Employe_id INNER JOIN Fiscal_salaire s on i.NumeroIdentification = s.Employe_id; I thing I have to use prefetch_related and I wrote this (first step, join between two tables) : @login_required def FiscalReporting(request) : Contribuable = Individu.objects.prefetch_related("Profession").all().filter(NumeroIdentification=Profession.Employe) context = { "Contribuable" : Contribuable, } return render(request, 'Fiscal_Reporting.html', context) And in … -
permission denied while collect static django
I had project with django + guicorn + nginx (this tutorial) I delete virtualenvironment and get a new one, everything works correctly but, when I try to use command: source projectenv/bin/activate folder1/project/manage.py collectstatic I got an error: -bash: folder1/folder/manage.py: Permission denied even when I try: folder1/folder/manage.py runserver 0.0.0.0:8000 -bash: folder1/folder/manage.py: Permission denied What should I do to make this virtualenvironment work correctly? -
How Django inlineformsets works internally
I have a form with two inline formsets. At the HTML level Django use the hidden fields for the formset management, and use the prefix to know which fields are related to a formset. Also it has ids in the html id, to group like in a virtual form the fields. <input name="documents-0-document" id="id_documents-0-document" type="file"> <input name="documents-0-filename" class="vTextField" maxlength="255" id="id_documents-0-filename" type="text"> <input name="documents-0-DELETE" id="id_documents-0-DELETE" type="checkbox"> On retrieve by default I get the path to the file in a paragraph and the inputs (html elements) are empty. <p class="file-upload">Currently: <a href="/media/Test%20Insieme/documents/sdsasa7">Test Insieme/documents/sdsasa7</a><br><input name="documents-0-document" id="id_documents-0-document" type="file"> Change: </p> On Browse(upload a different file) Django knows to update the same record in the database. Similar for click on checkbox. How Django make the correlation between the paragraph that show the path, the html id of the element and what is in the database? I want to change the UI (make it dynamic with JavaScript, use button instead of checkbox) and I want to understand how the mechanism is working. -
mysqlclient 1.3.3 or newer is required; you have 0.7.11.None
I'm using python version 3.6.3 and django version 2.0.1. I got the result below when I entered py manage.py migrate in cmd. (mysqlclient 1.3.3 or newer is required; you have 0.7.11.None) I was trying to link a mysql database to my django project. init.py codes: import pymysql pymysql.install_as_MySQLdb() settings.py codes: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': os.path.join(BASE_DIR, 'mysite'), 'USER': 'root', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '8000', } } -
How to check Mail Transfer Agent availability in Python?
I'd like to check that some MTA is available on a system and change error report destination based on that from Django. Since Django uses smtplib, what's the most efficient method of checking or at least what exceptions are returned in which case on a system without MTA? -
Django how to query objects one by one
I have to query an object from a model, this object is called "exercise" and has many fields(title, body, answers, etc.) I need to get "exercise objects" one by one with all their fields, do some rendering on them and give back a pdf of the exercise as result. The problem is, if I do: exercises = ExerciseModel.objects.all() I get all of them. If I do: some_exercises = ExerciseModel.objects.filter(something=something) I get "some of them" depending on filter. And if i do: exercise = ExerciseModel.objects.get() I get error get() returned more than one exercise How can I get them one by one? I must be able to use them as input for another function. -
create a user in postgres docker container
I am trying to create a django app in docker container, but I do not know how to create a user in postgres container that django uses. I guess that is why when I start it (by docker-compose up --build --force-recreate) it tells me database_1 | FATAL: role "my_user" does not exist. What am I doing wrong? docker-compose.yaml right now looks like: version: "3.1" services: database: image: postgres:9.5 environment: POSTGRES_DB: "django_db" POSTGRES_USER: "my_user" POSTGRES_PASSWORD: "my_password" POSTGRES_DATA: /var/lib/postgresql/data/pgdata logging: options: max-size: "10m" max-file: "3" restart: always volumes: - "database:/var/lib/postgresql/data" tmpfs: - "/tmp" - "/run" networks: db-net: django: build: ./ image: django:latest environment: DATABASE_URL: "postgres://my_user:my_pass@database/django_db" ports: - 7445:80 -
Django can't find the right path for images
i just moved my project on a server and my project was working fine, no trouble loading anything when i was using localhost:port/myprojectpage/. But i had to change from localhost to an ip so anyone could reach it, and since then when i load the page it doesn't manage to load the images. i had the problem before when i was using localhost so i changed my settings.py but now with this new problem i don't know how to solve it since the path should be good. The problem doesn't come from the httpd.conf, every path is good in it. this is my settings.py : BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) FILE_DIR = os.path.dirname(os.path.abspath(__file__)) PROJECT_DIR = os.path.dirname(__file__) STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "static") STATICFILES_DIRS = ( os.path.join(PROJECT_DIR,'static'), ) My previous problem was that the path he tried to load : http://localhost:8080/gestion_mouvement//mouvementDetails/static/images/img0025.png had to be : http://localhost:8080/gestion_mouvement/static/images/img0025.png but now it's : http://localhost:8080/gestion_mouvement//mouvementDetails/static/images/img0025.png and even if i change it to this : http://localhost:8080/gestion_mouvement/static/images/img0025.png It doesn't work and get 404. Hope someone can help me on this because since my path in settings previously corrected this error i don't know what to change here to make it work. -
ajax call is not working with django
i am creating a blog just for practice and i want to mark all notifications as seen when the user view the notifications, this is working if i go to the url but when i use ajax nothing happen javascript: <script> $(document).ready(function() { $("#testb").click(function(event){ $.ajax({ type:"POST", url:"{% url 'seen' request.user.username %}", success: function(){ confirm('it worked') } }); return false; }); }); </script> url url(r'functions/user/(?P<username>\w+)/seen', views.seen, name='seen') view: def seen(request, username): nat = Nat.objects.filter(toUser=username) nat.update(show=False) return HttpResponse("test") -
Simple search engine in my Django Web is not working
I'm trying to make my search go over my query my Database in Django. The lines in form.is_valid() is other forms I added to my website of adding data and it works perfect. The only thing is that query thing.. I just don't understand why after I click search I still see the all posts and not the posts I search for.. views.py- class HomeView(TemplateView): template_name = 'serverlist.html' def get(self, request): form = HomeForm() query = request.GET.get("q") posts = serverlist.objects.all() args = {'form' : form, 'posts' : posts} return render(request, self.template_name, args) def post(self,request): form = HomeForm(request.POST) posts = serverlist.objects.all() query = request.GET.get("q") if query: posts = serverlist.filter(Project__icontains=query) if form.is_valid(): # Checks if validation passed post = form.save(commit=False) post.save() text = form.cleaned_data['ServerName'] form = HomeForm() return redirect('serverlist') args = {'form': form, 'text': text} return render(request, self.template_name,args) index.html - <div class="container"> <br> <center><h1>DevOps Server List</h1></center> <br> <form method='GET' action=''> <input type='text' name='q' placeholder='Search Item'/> <input type='submit' value='Search' /> </form> <table class="table table-hover"> <thread> <tr> <th> Server Name </th> <th> Owner </th> <th> Project </th> <th> Description </th> <th> IP Address </th> <th> ILO </th> <th> Rack </th> <th> Status </th> <th> </th> </tr> </thread> <tbody> {% for server in posts %} … -
Django Raw Query with params on Table Column (SQL Injection)
I have a kinda unusual scenario but in addition to my sql parameters, I need to let the user / API define the table column too. My problem with the params here is that the query results in: SELECT device_id, time, 's0' ... instead of SELECT device_id, time, s0 ... Is there another way to do that through raw or would I need to escape the column by myself? queryset = Measurement.objects.raw("\ SELECT device_id, time, %(sensor)s FROM measurements \ WHERE device_id=%(device_id)s AND time >= to_timestamp(%(start)s) AND time <= to_timestamp(%(end)s) \ ORDER BY time ASC;", {'device_id': device_id, 'sensor': sensor, 'start': start, 'end': end}) -
How to link two tables in django?
I use build in User model in django, but i want use some custom fields, i was create new model class Profile(models.Model): user = models.OneToOneField(User) profile_img = models.ImageField(null=True) def __str__(self): return self.user.username this is my custom model. But when i create new user it doesn't display in admin(in profile table), i need to add user from admin panel, after adding it works fine. what i should to do to display Profile info of all users? p.s. When i was create table profile and was try to select info from joined tabels, sql query wasn't return anything, but after adding existed user to Profile table sql query return all what i want -
Django accessing a JSONResponse from another views file
I have two files within views directory, /views/api.py and /views/pages.py /views/api.py has methods which return JSONResponses objects Example: @api_view(['GET']) def foos(request): foos = get_list_or_404(Foo) data = [{'id': foo.id, 'name': foo.name, 'description': foo.description, 'tag': foo.tag} for foo in foos] return JsonResponse({'foos': data}) /views/pages.py will have methods that will access some of the methods from /views/api.py and add them to context and render a page. Example: def home(request): foos = api.foos(request) print foos return HttpResponse(status=200) On the line print stacks, I can see the JSONResponse object with the correct data. How do I access individual values within foos so I can create a list or a dictionary or something that is custom for each view?