Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django creates migration files after each 'makemigrations' because of dictionary?
I've noticed strange things in my Django project. Each time I run python manage.py makemigrations command new migration file for my app called notifications is created. I did zero changes to the model, but the new migration file is created. I can run makemigrations command N number of times and N number of migration files will be created. The model looks as following: from django.db import models from django.db.models.fields import EmailField class EmailLog(models.Model): email = models.EmailField(max_length=70, null=False) subject = models.CharField(max_length=255, null=False) html_body = models.TextField(null=False) sent_choices = { ('OK', 'Sent'), ('KO', 'Not sent'), ('KK', 'Unexpected problems') } status = models.CharField(max_length=2, choices=sent_choices, null=False, default='KO') sent_log = models.TextField(null=True) sent_date = models.DateTimeField(auto_now_add=True, null=False) Each migration just swaps the position of sent_choices field. that's all! Is it because dictionaries in Python have random order? How do I avoid it? -
nginx unix:/webapps/myproject/run/gunicorn.sock failed (13: Permission denied) while connecting to upstream
Want to do work assembly: django, nginx, gunicorn, supervisor, centos 7. Work perfect, but I have one problem and one error in browser - "502 Bad Gateway nginx/1.10.2". nginx-error.log unix:/webapps/myproject/run/gunicorn.sock failed (13: Permission denied) while connecting to upstream, client: 192.168.4.33, server: 192.168.4.39, request: "GET / HTTP/1.1", upstream: "http://unix:/webapps/myproject/run/gunicorn.sock:/", host: "192.168.4.39" Haven`t idia how to fix it. Had tried configure selinux, give permissions, change users and some anything else, but it is did not help, I do not have enough knowledge. /etc/nginx/conf.d/myproject.conf server { listen 80; server_name 192.168.4.39; location = /favicon.ico { access_log off; log_not_found off; } client_max_body_size 2G; access_log /webapps/myproject/logs/nginx-access.log; error_log /webapps/myproject/logs/nginx-error.log; location /static/ { root /webapps/myproject/; } location /media/ { alias /webapps/myproject/media/; } location / { # include proxy_params; proxy_set_header Host $http_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_pass http://127.0.0.1:8000; proxy_pass http://unix:/webapps/myproject/run/gunicorn.sock; } } gunicorn_start.bash #!/bin/bash NAME="myproject" # Name of the application DJANGODIR=/webapps/myproject/ # Django project directory SOCKFILE=/webapps/myproject/run/gunicorn.sock # we will communicte using this unix socket USER=myproject # the user to run as GROUP=webapps # the group to run as NUM_WORKERS=3 # how many worker processes should Gunicorn spawn DJANGO_SETTINGS_MODULE=myproject.settings # which settings file should Django use DJANGO_WSGI_MODULE=myproject.wsgi # WSGI module name echo "Starting $NAME … -
Django - field of language choices
I want to let user choose from languages they speak. Is there a Django built in list of languages or should I get list of languages from other source? For now: class UserProfile(models.Model): languages = models.ManyToManyField(Language) class Language(models.Model): shortcut ... name ... The languages field should only be able to list all languages user can speak. -
django + gunicorn + nginx: Browser refreshes toggling between PRE/POST dynamic content change
Below are the nginx.conf and gunicorn.start.sh files that I use for the Django application that I'm running (which, by the way, I didn't write). When I make any one-time change to dynamic content, then repeatedly refresh the browser, the rendered content switches/flaps variously between PRE and POST changes made. But it should just update once, and never again. The only thing that momentarily fixes the issue is restarting gunicorn: myapp$ sudo supervisorctl restart gunicorn But this only works until the next change to dynamic content. No good. I've tried numerous browsers, and it happens even when I clear their caches. Makes no difference. I also temporarily tried uWSGI instead of gunicorn (just to see), and the same issue occurs. A tail -f gunicorn.access.log during browser refreshes shows HTTP statuses that vary between 200 (content was downloaded) and 304 (you already have the content; redirecting you to your local cache). But dynamic content shouldn't be cached. Note that when running the application using the development server, like this: myapp$ python manage.py runserver --settings live 0.0.0.0:8080 the issue doesn't occur; but neither does this use nginx nor gunicorn. Any ideas? I've tried everything I know, but don't know what is causing this … -
Django + mod_wsgi Fatal Python Error: Py_Initialize: No module named Encodings
I am attempting to get a website to load within a web browser using Django + mod_wsgi and apache. I have exactly the same problem as in This Question Here, but the solution found there does not work in my case. Here is my httpd-vhosts.conf setup: WSGIDaemonProcess binshellpress.com python-home=/usr/local/docs/binshellpress-production/virtpy/ python-path=/usr/local/docs/binshellpress-production/virtpy/lib/python3.6/ WSGIProcessGroup binshellpress.com WSGIApplicationGroup %{GLOBAL} <VirtualHost *:80> ServerAdmin webmaster@binshellpress.com DocumentRoot "/usr/local/docs/binshellpress-production/root" ServerName binshellpress.com ServerAlias www.binshellpress.com ErrorLog "/var/log/httpd/bsp-error_log" CustomLog "/var/log/httpd/bsp-access_log" common Alias /robots.txt /usr/local/docs/binshellpress-production/static/robots.txt Alias /favicon.ico /usr/local/docs/binshellpress-production/static/favicon.ico Alias /media/ /usr/local/docs/binshellpress-production/media Alias /static/ /usr/local/docs/binshellpress-production/static <Directory /usr/local/docs/binshellpress-production/static> Require all granted </Directory> <Directory /usr/local/docs/binshellpress-production/media> Require all granted </Directory> WSGIScriptAlias / /usr/local/docs/binshellpress-production/binshellpress/wsgi.py process-group=binshellpress.com <Directory /usr/local/docs/binshellpress-production/binshellpress> <Files wsgi.py> Require all granted </Files> </Directory> </Virtualhost> I have a virtual environment set up at /usr/local/docs/binshellpress-production/virtpy. I have rebuilt mod_wsgi to explicitly use that virtual environment. I have performed the permissions modifications as described in the answer to This Question No change. I am desperate. I have been searching up and down. I can't figure out what to do. Please, help me. I beg you. Thank you, for anything, thank, just please, help me, thank you. -
Request google app engine
I do a http request with module requests in django (python 3), import requests url = 'https://www.google.es' r = requests.get(url) str = str(r.content) and It work right in localhost, but when I deploy in Google App Engine, It return a "('Connection aborted.', error(104, 'connection reset by peer'))", I deploy in a flex enviroment. I read than it not necessary change for urlfetch module. -
Unresponsive django-bootstrap3-datetimepicker (not showing calendar)
As a beginner I often struggle with understanding the connections between Python-Django, html, javascript and css. The problem at hand is this: I'm trying to implement DateTimePicker widget from django-bootstrap3-datetimepicker-2. Since this library does not include js/css assets, I started by implementing datetimepicker without backend involvement just to see if I loaded all static files etc. correctly. Thus, I added this example to html template: <div class="container"> <div class="row"> <div class="col-sm-6"> <div class="form-group"> <div class="input-group date" id="datetimepicker1"> <input type="text" class="form-control"> <span class="input-group-addon"> <span class="glyphicon glyphicon-calendar"></span> </span> </div> </div> </div> <script type="text/javascript"> $(function () { $('#datetimepicker1').datetimepicker(); }); </script> </div> </div> Everything worked as intended, so I tried to implement datetimepicker as a widget from django forms: class FooForm(forms.Form): pick_a_date = forms.DateTimeField( widget=DateTimePicker(options={ "format": "YYYY-MM-DD", "pickTime": False} )) I also wanted to benefit from form wizard (namely SessionWizardView from formtools.wizard), so I output the above mentioned form into html like this: <form action="" method="post" role="form">{% csrf_token %} <table> {{ wizard.management_form }} {% if wizard.form.forms %} {{ wizard.form.management_form }} {% for form in wizard.form.forms %} {{ form }} {% endfor %} {% else %} {{ wizard.form }} {% endif %} </table> However, the widget is not responsive (the calendar window isn't showing, the … -
django can't find my choiceField on fields
I have my class: from django import forms from .models import Donator class DonatorForm(forms.ModelForm): BLOOD_CHOICES = ( ('A-','A-'), ('A+','A+'), ('B-','B-'), ('B+','B+'), ('AB-','AB-'), ('AB+','AB+'), ('O-','O-'), ('O+','O+'), ('TODOS','TODOS') ) SITUATION_CHOICES = ( ('Sem Problemas','Sem Problemas'), ('Problemas Momentâneos','Problemas Momentâneos'), ('Problemas Graves', 'Problemas Graves') ) class Meta: model = Donator fields = ('name', 'age', 'email','phone', forms.ChoiceField(choices = SITUATION_CHOICES, required=True, label = "Situacao do Doador"), 'bloodType', 'observation') I receive: NameError: name 'SITUATION_CHOICES' is not defined How could I correctly mention my fieldCHoices to appear a dropdown on the Form? -
How to use django login_required method
$ class HomePage(TemplateView): template_name = 'obs/homepage.html' I want to make this view accessible to only logged in users. How can i do that? i've seen django documentation but it was for functions. -
Creating / storing a form preview with Django forms and cart
I've never had to do this before and I'm wondering if I'm on the right track / this is the standard way to do something of this nature. I was going to use Django formtools FormPreview but it doesn' handle files (They can upload various images)... So, rolling my own solution or trying to. Currently I'm using a form wizard with model forms and everything validates / saves fine. I now want to add in a form preview, before purchasing the item they create with the form, and I've thought about doing the following: Save it to the database but mark it as not paid / inactive. On the form preview page grab the id (from pk in url) and display it. They have the option to go back and edit (update view) and / or pay. Using this route it's really easy to update and grab the data for viewing whether they wish to go back or forward. Similarly, if they add multiple items in their cart I can just display these items by grabbing the pk's from the DB rather than trying to handle a ton of session data. If they remove the item -> delete the row … -
Django UpdateView - get initial data from many-to-many field and add them when saving form
I'm using Django class based generic view. In my models.py I have a model called MyModel with many-to-many field called m2m. I have multiple groups of users they can edit the m2m field. Each group of users can only see and add their portion to the field - using get_form to set what they can see in the m2m field. The problem I'm having is that when one user enter his record it will delete the initial records in the m2m field. I need to somehow get the initial values from the m2m field save them and then add them to the new ones when the form is submitted. Here is my views.py: class MyModelUpdate(UpdateView): model = MyModel fields = ['m2m'] def get_initial(self): return initials def get_form(self, form_class=None): form = super(MyModelUpdate, self).get_form(form_class) form.fields["m2m"].queryset = DiffModel.objects.filter(user = self.request.user) return form def form_valid(self, form): form.instance.m2m.add( ??? add the initial values) return super(MyModelUpdate, self).form_valid(form) def get_success_url(self): ... -
django app deploy to google app engine
I am trying to deploy my django project on google app engine. When I 'gcloud app deploy' everything looks like it is going well except it takes a really long time. Then I get the message: 'ERROR: (gcloud.app.deploy) Error Response: [4] Your deployment has failed to become healthy in the allotted time and therefore was rolled back. If you believe this was an error, try adjusting the 'app_start_timeout_sec' setting in the 'readiness_check' section.' I checked my acitivity log in google cloud and i have the error: " STATIC_ADDRESSES quota limit reached " This is my first django project and first time on google app engine. How can I get this thing up? -
How to start building a django website with postgres nginx and gunicorn on separate machines?
I searched all over the internet and I guess I'm lost, Please I want a detailed answer here. I know how to make all three of these things(gunicorn, Nginx, and Postgres) work on the same machine but what if I wanna have all of them on the different/individual machine. Let's say I got 3 behemoth powerful machines capable of handling anything but the real question in my mind is where do I start. how can I connect all three of these together? what if I wanna add more storage? How do I connect multiple database machines together I'm sorry but I'm pretty new in networking and it's really crucial for me to understand this because if I don't my mind won't allow me to go ahead with the process. -
Error ! The following packages have unmet dependencies: mysql-server
I tried to install mysql on my ubuntu16.04 for a django project. The installation has some problem with some existing files, getting the error: mysql-server is already the newest version (5.7.19-0ubuntu0.16.04.1). You might want to run 'apt-get -f install' to correct these: The following packages have unmet dependencies: mysql-server : Depends: mysql-server-5.7 but it is not going to be installed E: Unmet dependencies. Try 'apt-get -f install' with no packages (or specify a solution) I tried, sudo apt-get -f install which gives error: Preparing to unpack .../mysql-server-5.7_5.7.19-0ubuntu0.16.04.1_amd64.deb ... grep: /etc/mysql/: No such file or directory Aborting downgrade from (at least) 10.2 to 5.7. If are sure you want to downgrade to 5.7, remove the file /var/lib/mysql/debian-*.flag and try installing again. dpkg: error processing archive /var/cache/apt/archives/mysql-server-5.7_5.7.19-0ubuntu0.16.04.1_amd64.deb (--unpack): subprocess new pre-installation script returned error exit status 1 Errors were encountered while processing: /var/cache/apt/archives/mysql-server-5.7_5.7.19-0ubuntu0.16.04.1_amd64.deb E: Sub-process /usr/bin/dpkg returned an error code (1) I have tried installation steps also but gets the first error. -
Django crispy forms - creating a form in home.html and getting an error
I have built a crispy form from a tutorial (https://godjango.com/29-crispy-forms/) and am getting an error that I believe means I need to define a URL in the urls.py. I also get the sense that there may be more than one issue going on - I am still trying to make this work and will continue to research it but I am quite new to Django and Python so struggling on this. Any guidance gratefully received. Here's the error: Failed lookup for key [form] in "[{'True': True, 'False': False, 'None': None}, {}, {}, {'view': <django.views.generic.base.TemplateView object at 0x10faa03c8>, 'home_url': '/'}]" For reference here are the files: forms.py from django import forms from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit, Layout, Field from crispy_forms.bootstrap import ( PrependedText, PrependedAppendedText, FormActions) class SimpleForm(forms.Form): username = forms.CharField(label="Username", required=True) password = forms.CharField( label="Password", required=True, widget=forms.PasswordInput) remember = forms.BooleanField(label="Remember Me?") helper = FormHelper() helper.form_method = 'POST' helper.add_input(Submit('login', 'login', css_class='btn-primary')) class CartForm(forms.Form): item = forms.CharField() quantity = forms.IntegerField(label="Qty") price = forms.DecimalField() helper = FormHelper() helper.form_method = 'POST' helper.layout = Layout( 'item', PrependedText('quantity', '#'), PrependedAppendedText('price', '$', '.00'), FormActions(Submit('login', 'login', css_class='btn-primary')) ) class CreditCardForm(forms.Form): fullname = forms.CharField(label="Full Name", required=True) card_number = forms.CharField(label="Card", required=True, max_length=16) expire = forms.DateField(label="Expire Date", input_formats=['%m/%y']) ccv … -
Error when running a Django server
I am using Django 1.8 and I get the following error: WARNINGS: ?: (1_7.W001) MIDDLEWARE_CLASSES is not set. HINT: Django 1.7 changed the global defaults for the MIDDLEWARE_CLASSES. django.contrib.sessions.middleware.SessionMiddleware, django.contrib.auth.middl eware.AuthenticationMiddleware, and django.contrib.messages.middleware.MessageMi ddleware were removed from the defaults. If your project needs these middleware then you should configure this setting. What do I have to do ? -
django domain setup and routing schema
Can anyone give me a short walkthrough (yes, I know that's asking a lot... I'm completely lost) of how to properly setup different domains using a single django project? Or... point me in the right direction / some insight to my questions below... I've searched around and looked at various app solutions, apache stuff, etc but still don't have a clear understanding. Specifically, each (main) app in my project is on a different domain. I have an app for news, job posts, etc and these would be on (name)news.io, (name)jobs.io, etc. In my settings.py file currently I'm using django-multiple-domains and have the MULTIURL_CONF set to point to each app based upon the domain name. As I understand it.... i can just set up the project on my domains using the same settings file since it will use this routing schema rather than the suggested route of multiple different settings file for each domain based upon the middleware that django-multiple-domains uses. Now, here's where I get confused on the URL routing.... In an app we typically include the urls inside the main urls.py file in the root app folder for our project to creating a routing schema for the entire site … -
How to create instances when there are multiple senders in django signals?
I am getting error order_id must be Order instance user must also be MyUser instance. How do i create instances? @receiver(post_save, sender=MyUser) @receiver(post_save, sender=Order) def create_order_message(sender, **kwargs): user_id = instance.id MyUser.object.filter(id=user_id) if kwargs.get('created', False): Notification.objects.create(order_id = kwargs.get('instance'), user = kwargs.get('instance'), title='Welcome to Django!', message='Thank for signing up!', ) -
Django with unique_together on foreign key and slug=slugify fails
I am building a basic CMS. I have created an organization app, that adds a project ID with foreign key to all my model objects. The form is for creating a basic website object with header and text. I was able to create and save one instance with the following code. Further tries with different titles fail with "(1062, "Duplicate entry '' for key 'cms_page_url_117a950602ffab5c_uniq'") I have now idea where I am going wrong, can somebody point me in the correct direction? I am running on mysql database. Model: class Page(models.Model): title = models.CharField(max_length=100) text = models.TextField(blank=True) slug = models.SlugField() date_created = models.DateTimeField(auto_now_add=True) last_modified = models.DateTimeField(default=timezone.now) project = models.ForeignKey(Project) def __unicode__(self): return "Page '%s' @: %s from %s" % (self.title, self.slug, self.project) def __str__(self): return unicode(self).encode('utf-8') def save(self, *args, **kwargs): self.slug = slugify(self.title) super(Page, self).save(*args, **kwargs) class Meta: unique_together = (("project", "slug"),) Form: class PageForm(ModelForm): def __init__(self, *args, **kwargs): super(PageForm, self).__init__(*args, **kwargs) for key, field in six.iteritems(self.fields): field.widget.attrs['placeholder'] = field.label class Meta: model = Page fields = ['title', 'text'] # TODO: ordering title = forms.CharField(max_length=100, label=ugettext_lazy("Add a title")) text = forms.CharField(label=ugettext_lazy("Type your text here"), widget=forms.Textarea) def save(self, project, commit=True): instance = super(PageForm, self).save(commit=False) instance.project = project if commit: instance.save() return … -
django - making .create() support writable nested fields?
So in Django, .create() does not support writable nested fields. However, I have a nested field in my project. I looked at this question, which was helpful, but I'm now getting a ValueError at /transactions/ invalid literal for int() with base 10: 'Product001'. As far as I can tell, this is caused by the line in serializer.py that reads product = Product.objects.get(pk=validated_data.pop('sku')) specifically, the 'sku' value I have in there. My question is, what value should I put in there to replace 'sku'? The answer to the question I based my code on used 'event', but that's not part of my models in my project. I've also tried using 'product', and got a TypeError that sadi "int() argument must be a string, a bytes-like object or a number, not 'collections.OrderedDict'". serializers.py from .models import Product, Family, Location, Transaction from rest_framework import serializers class LocationSerializer(serializers.ModelSerializer): class Meta: model = Location fields = ('reference', 'title', 'description') class FamilySerializer(serializers.ModelSerializer): class Meta: model = Family fields = ('reference', 'title', 'description', 'unit', 'minQuantity') class ProductSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Product fields = ('sku', 'barcode', 'title', 'description', 'location', 'family') depth = 1 class TransactionSerializer(serializers.ModelSerializer): product = ProductSerializer() class Meta: model = Transaction fields = ('sku', 'barcode', … -
how to find much matches of one objects one queryset<==(which contain one finding object) in another queryset Django?
how to find many matches with one object from the set of queryset objects (which contain one search object) in another many queryset django objects for example, how to find the most frequent product in order products and deduce its quantity I apologize for such a question, I'm still noob and my brains can not so critical think i try to do this: product = Product.objects.all() some = Order.objects.filter(products_of_order__product__in=product).count() but it's just return all product which contain in order products, how to get count each product in orders products which matches with list of products. i have one idea how to make it but i wanna make it in one line) in one queryset) some_dict = {} for i in some: for s in i.products_of_order.all(): if s.product.name_of_product in some_dict: some_dict.s.product.name_of_product += 1 else: some_dict.s.product.name_of_product = 1 -
Django: IndexError: tuple index out of range on sending a JQuery POST request
I have a use case wherein I'm sending some data using POST request to a URL, which is mapped to a view which then returns a success status. JQuery $( "#submit-id-add-update-user-button" ).click(function() { first_name = $('input[name="first_name"]').val(); last_name = $('input[name="last_name"]').val(); age = $('input[name="age"]').val(); dob = $('input[name="dob"]').val(); place = $('input[name="location"]').val(); mobile = $('input[name="mobile"]').val(); email = $('input[name="email"]').val(); user_id = $('input[name="user_id"]').val(); new_user = (user_id == '') ? ('yes') : ('no'); var url = base_url + '/add-update-user/'; var data = { 'email': email, 'first_name': first_name, 'last_name': last_name, 'age': age, 'dob': dob, 'place': place, 'mobile': mobile, 'user_id': user_id, 'new_user': new_user, 'csrfmiddlewaretoken': csrftoken, }; $.post( url, data) .done(function( data ) { console.log('this is done'); window.location.href = "/"; }); }); urls.py url(r'^add-update-user/', add_update_user, name="add_update_user") views.py def add_update_user(request): return HttpResponse({'status':200}) However, this is the error that I'm encountering: Traceback (most recent call last): File "/usr/lib/python2.7/logging/__init__.py", line 861, in emit msg = self.format(record) File "/usr/lib/python2.7/logging/__init__.py", line 734, in format return fmt.format(record) File "/home/manas/Python/Interviews/pricebaba_env/local/lib/python2.7/site-packages/django/utils/log.py", line 173, in format if args[1][0] == '2': IndexError: tuple index out of range Logged from file basehttp.py, line 85 I'm not really sure what this error means or why is it arising. Would really appreciate some help on this. -
test django app with multiple domains locally
How would I go about testing a django app which uses multiple domains locally? Each app is on a different domain (i.e. - (somename)news.io, (somename)jobs.io, ...). I'm trying to test my url routing schema as well as session data being shared across the domains. I tried setting up apache, xampp, and using virtualhosts on windows but this didn't work for me - I couldn't figure out how to set up the virtualhosts (to fake the domains) and get my app served to them. So, looking for another route for testing. -
Sorting a table by clicking the table head column in Django Web
So I have a website in django. I have a table with a few colums like ServerName,IP etc.. I would like to have the header of the columns to sort the entire column. For example when I click the ServerName column it will order all the items by ABC order of the ServerName. I have heard of django-sorting-bootstrap but the guide seem complicated. Is there any easier or good guide to do that? the idea is to click with the arrow on the head and it will sort it out (It will be like a link). index.html table- <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"> <thead> <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> </thead> <tbody> {% for server in posts %} <tr> <div class ="server"> <td>{{ server.ServerName }}</td> <td>{{ server.Owner }}</td> <td>{{ server.Project }}</td> <td>{{ server.Description }}</td> <td>{{ server.IP }}</td> <td>{{ server.ILO }}</td> <td>{{ server.Rack }}</td> <td>{{ server.Status }}</td> <td> <button type="button" class="btn btn-primary" data-toggle="modal" href="#delete-server-{{server.id}}" data-target="#Del{{server.id}}">Delete <span class="glyphicon glyphicon-trash" </span></button> … -
Why Django serialize returns string
I have problem with returning something browsable form serializers.serialize. My model: class BowlingGame(models.Model): Frame = models.PositiveSmallIntegerField() FrameRow = models.PositiveSmallIntegerField() Result = models.PositiveSmallIntegerField(blank=True, null=True) StrikeSpare = models.PositiveSmallIntegerField(blank=True, null=True) StrikeSpareInfo = models.CharField(max_length=1, blank=True, null=True) Time = models.DateTimeField(blank=True, null=True) GameId = models.PositiveIntegerField() StateOfGame = models.PositiveSmallIntegerField(default=1) class Meta: ordering = ('GameId',) def __str__(self): return str(self.GameId) And what I do next: >>> from django.core import serializers >>> from django.db.models import Max >>> from game.models import BowlingGame >>> a = BowlingGame.objects.all().aggregate(Max('GameId'))['GameId__max'] >>> game_frame = BowlingGame.objects.filter(GameId=a) >>> me = serializers.serialize('json', game_frame, fields=('Frame', 'FrameRow')) >>> me '[{"model": "game.bowlinggame", "pk": 2356, "fields": {"Frame": 1, "FrameRow": 1}}, {"model": "game.bowlinggame", "pk": 2357,......}}]' This seems to be string as >>> me[0] '[' and I'm looking for the first element of the queryset. I tried few more things: >>> me = serializers.serialize('json', [game_frame, ], fields=('Frame', 'FrameRow')) AttributeError: 'QuerySet' object has no attribute '_meta' My question: is it normal to return string? How I can browse the object. In fact I'm using it with AJAX but its the same. json.game_frame[0] returns '['. I need to be able to get the elements separately as normal dict or list. What is going on?