Django community: Django Q&A RSS

This page, updated regularly, aggregates Django Q&A from the Django community.

Killed loaddata

Posted on April 19, 2014 at 4:13 PM by Stack Overflow RSS

I use PostgreSQL 9.1 and Django 1.6.2. CREATE DATABASE db WITH ENCODING = 'UTF8' TEMPLATE template0; CREATE USER db_user WITH password 'password'; GRANT ALL privileges ON DATABASE db TO db_user; Then I want to load fixture: python loaddata cars Killed What does it mean? Killed? All works perfect with mysql. Cars.yaml - its a very big file (it has russian words, do I need to create db with LC_COLLATE = 'ru_RU.UTF-8'?). In mysql I use: CREATE DATABASE `db` CHARACTER SET utf8 COLLATE utf8_general_ci; And everything works fine. Please, help, I am newbie in PostgreSQL. How to fix that problem with killed?

Read this post in context »

Django "Installed Apps" sync issue

Posted on April 19, 2014 at 3:50 PM by Stack Overflow RSS

I have the following Django directory structure: PROJECT_FOLDER \__ \__ MY_PROJECT \__ \__ \__ \__ \__ APPS \__ MY_APP \__ \__ \__ \__ \__ In I included my app in the follwing line: INSTALLED_APPS = ( ... # Applications 'MY_PROJECT.APPS.MY_APP' ) But when I do syncdb (python syncdb), it gives me an error: ImportError: No module named APPS.MY_APP In the INSTALLED_APPS, I tried different lines like: 'PROJECT_FOLDER.MY_PROJECT.APPS.MY_APP', 'APPS.MY_APP' but all of these give me errors... Is there anything wrong with my or directory structure??? tHanks

Read this post in context »

Fetching nested objects with Django REST framework

Posted on April 19, 2014 at 3:40 PM by Stack Overflow RSS

I am attempting to fetch nested objects but not quite sure how to achieve this. My model is as shown: class Brand(models.Model) name = models.CharField(max_length=128) class Size(models.Model) name = models.CharField(max_length=128) class Brand_Size(models.Model) brand = models.ForeignKey(Brand) size = models.ForeignKey(Size) class Brand_Size_Location(models.Model) location = models.ForeignKey(Location) brand_size = models.ForeignKey(Brand_Size) I filter objects in Brand_Size_Location by location which can occur 1..x. I want my serializer to output the results in terms of the model Brand (BrandSerializer). Since my resultset can be 1..x and furthermore the occurrence of Brand can be duplicates i would like to eliminate these aswell at the same time.

Read this post in context »

python social app (django) - properly save/retrieve user

Posted on April 19, 2014 at 3:28 PM by Stack Overflow RSS

I'm experimenting with python social app for my django project and I'm having some trouble understanding the easiest - most straightforward way of creating/saving/retrieving users once logged (eg. via google). I notice that when logging in through, lets say, gmail - an entry is created in the social auth/Users table. However; the Auth/Users table only has one entry at a time(the person who is logged in). Now my social auth pipeline goes something like this SOCIAL_AUTH_PIPELINE = ( 'social.pipeline.social_auth.social_details', 'social.pipeline.social_auth.social_uid', 'social.pipeline.social_auth.auth_allowed', 'social.pipeline.social_auth.social_user', 'social.pipeline.user.get_username', 'social.pipeline.mail.mail_validation', 'social.pipeline.user.create_user', 'social.pipeline.social_auth.associate_user', 'social.pipeline.social_auth.load_extra_data', 'social.pipeline.user.user_details', '', ) So as you can see I have my own pipeline handler at the very end which I can use to extract more information. I guess i'm just confused as I do not see many examples online on what is the best way/best practice of storing and retrieving social logged in users from the DB? Should I just extract the social auth user's name,email, etc from the pipeline and create my own model or is this already provided somehow?

Read this post in context »

django + Ajax POST request - can't figure out why the view isn't being called at all

Posted on April 19, 2014 at 3:12 PM by Stack Overflow RSS

This is my first time using Ajax(to create a 'favorite' button) and I'm just trying to send one piece of data to a view, which I will then use to create an object to save to the database. My problem is that I have all 200s and no errors anywhere - the success function is activated and all of the jquery stuff works, it just isn't sending anything to my django view and I'm getting no response. In the console I also only see a POST request to /favorites/ (200) but nothing after that. Not sure if that is important. I have all of the AjaxSetup/csrf stuff, and then here is my ajax call: $('.favorite').submit(function(e){ e.preventDefault(); var kitchenID = $(this).attr('name'); $.ajax({ type: "POST", url: "/soupkitchens/favorites/", contentType: "application/x-www-form-urlencoded", data: {"id":kitchenID, 'csrfmiddlewaretoken':$( "#csrfmiddlewaretoken" ).val()}, dataType: "text", success: function(data, response) { alert(kitchenID); $('.favorite').html("Faved!"); $("#results").html(response); }, error: function(rs, e) { alert(e); } }); return false; }) }); Django view - I've been trying to debug which is why I just have the print statement, but I get no response and nothing in the console. I can add in my code where I retrieve the data and create the 'favorite' object but even when I ...

Read this post in context »

Openshift Django static files

Posted on April 19, 2014 at 2:53 PM by Stack Overflow RSS

I've started a new Django project for Openshift following the github example. According to this openshift post the project folder structure can be simplified. I tried this so now, I only have openshift files in my repo root. Having this, I tried to serve static files with apache with the following .htaccess: RewriteEngine On RewriteRule ^application/static/(.+)$ /static/$1 [L] But it does not work. It only works if I recreate the wsgi directory and place static folder under it (modifying settings and config files to find them there ofc.). I guess it is something related with the .htaccess but don't know how to modify it in order to find static files in the repo root folder. Any guesses?

Read this post in context »

Complex queryset across different models

Posted on April 19, 2014 at 2:45 PM by Stack Overflow RSS

I'm using Django 1.6 and have following models (a bit simplified for readability): class Person(models.Model): name = models.CharField(max_length=128) class Room(models.Model): max_persons = models.SmallIntegerField() name = models.CharField(max_length=30, unique=True) class Stay(models.Model): person = models.ForeignKey(Person) STAY_TYPE = ( (1, 'Type 1'), (2, 'Type 2'), (3, 'Type 3'), ) stay_type = models.CharField(max_length=1, choices=STAY_TYPE) class Hospitalization(models.Model): stay = models.ForeignKey(Stay) date_in = models.DateField() date_out = models.DateField(blank=True, null=True) room = models.ForeignKey(Room) With a queryset, I'd like to obtain all the available rooms for a given date, i.e. where max_persons isn't met. So far, I've tried to play around with Q and things like Room.objects.filter(hospitalization__date_out__lt="2014-04-25") but I'm not able to figure out the max_persons comparison. Would you have any idea?

Read this post in context »

How to get 'real-time' data from db PyQt4

Posted on April 19, 2014 at 12:54 PM by Stack Overflow RSS

Before I start, I must submit that I am just an intermediate Python developer and so I hope I will not receive any backlash for my question. I'm building a hospital system using Python and PyQt4 for the client side, which communicates with a Django based server through an API. Multiple clients will be communicating with the server. The system is role based and thus the client displays a different interface for each of the roles e.g patient_registration, triage, doctors_desk etc. The problem i'm struggling with is how to handle the queuing of patients. Each doctor should be able to view the queued patients from his/her desk. In the db, I have a table patient_queue which handles those records. Displaying the info currently in the table is quite straightforward, however, how I'm I supposed to make any new record that is added to the patient_queue table to appear in the doctors' queue automatically? How can I ensure the doctors have the latest data from the db without having to do something hacky like making the query periodically?? Thank you.

Read this post in context »

How to JSON serialize __dict__ of a Django model?

Posted on April 19, 2014 at 12:09 PM by Stack Overflow RSS

I want to serialize the values of a single model in Django. Because I want to use get(), values() is not available. However, I read on Google Groups that you can access the values with __dict__. from django.http import HttpResponse, Http404 import json from customer.models import Customer def single(request, id): try: model = Customer.objects.get(id=id, user=1) except Customer.DoesNotExist: raise Http404 values = model.__dict__ print(values) string = json.dumps(values) return HttpResponse(string, content_type='application/json') The print statement outputs this. {'_state': <django.db.models.base.ModelState object at 0x0000000005556EF0>, 'web site': '', 'name': 'Quiteworks', 'id': 1, 'logo': '', 'use r_id': 1, 'address3': '10557 Berlin', 'notes': '', 'address2': 'Lehrter Stra├če 6 9a', 'address1': 'Danijar Hafner', 'ustid': 'DE291439717', 'fullname': 'Quitewor ks', 'mail': ''} Because of the _state key that holds an unserializable value the next line fails with this error. <django.db.models.base.ModelState object at 0x0000000005556EF0> is not JSON serializable How can I serialize the dictionary returned from __dict__ without _state being included?

Read this post in context »

Django redirect with custom kwargs

Posted on April 19, 2014 at 11:29 AM by Stack Overflow RSS

I use my django as proxy to some server with POST api. import requests import xmltodict from django.conf import settings from django.views.generic import FormView, TemplateView class GetServerResultView(FormView): template_name = "myTemplate.html" form_class = MyForm success_url = 'result/' def form_valid(self, form): data = form.cleaned_data server_url = settings.SERVER_API_ADDR resp =, data) if resp.status_code == 200: return redirect(self.get_success_url(), kwargs={'data': self.parse_xml(resp.content)}) return super(GetServerResultView, self).form_valid(form) def parse_xml(self, content): data_dict = xmltodict.parse(content) return data_dict['results']['data'] class ListResultView(TemplateView): template_name = 'list.html' data = None def get_context_data(self, **kwargs): print kwargs context = super(ListResultView, self).get_context_data(**kwargs) return context def dispatch(self, request, *args, **kwargs): print args print kwargs print return super(ListResultView, self).dispatch(request, *args, **kwargs) So, in my ListResultView (after redirect on it) i want to get this result. I do not want to save the result to database and pass to the url schema id of database record. I do not want to save result to the session (because of my session backend is database). How can i show in other view the result? in ListResultView i prints args, kwargs and They are all empty.

Read this post in context »

Django app in heroku and local deployment

Posted on April 19, 2014 at 11:27 AM by Stack Overflow RSS

I have a django app with the following if else block in my file if block is getting executed when app runs in heroku , else is getting executed when app is in local system, please explain what is this os.getenviron.get? and what MBAIR,False is used for? import os if not bool(os.environ.get('MBAIR', False)): DEBUG = True import dj_database_url DATABASES = {'default': dj_database_url.config(default='postgres://localhost')} else: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'rsdfmsfgjsdk_sdfhsdfh' 'USER': 'sdfhsdfhsdf', 'PASSWORD': 'sdhsdfhsdhgfsdf', 'HOST': 'localhost', 'PORT': '', } }

Read this post in context »

unbound method must be called with instance as first argument

Posted on April 19, 2014 at 11:09 AM by Stack Overflow RSS

I'm working with django and i'm getting this error: "unbound method create() must be called with SocialUrl instance as first argument (got nothing instead)". I've read several answers to the same problem here but i'm not sure they are doing the same thing wrong as i am. Here is the stacktrace: Environment: Request Method: GET Request URL: Django Version: 1.6.2 Python Version: 2.7.6 Installed Applications: ('django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'SocialUrl') Installed Middleware: ('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: File "C:\Users\Sverker\.virtualenvs\coomba\lib\site- packages\django\core\handlers\" in get_response 114. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Sverker\Dropbox\Coomba\SbrgCoomba\SocialUrl\" in test 8. socialUrl = SocialUrl.create() Exception Type: TypeError at /su/asdadsf Exception Value: unbound method create() must be called with SocialUrl instance as first argument (got nothing instead) Here is the Model containing the method i'm trying to call: from django.db import models class SocialUrl(models.Model): code = models.CharField(max_length=30) def create(): socialUrl = SocialUrl(code = generateCode()) return socialUrl def __unicode__(self): return self.code and here is the method trying to call SocialUrl.create(): from django.shortcuts import render from django.template import RequestContext from .general import generateCode from .models import SocialUrl def test(request): socialUrl = SocialUrl.create() #print(SocialUrl.objects.all()) return render(request, 'test.html', RequestContext(request, {"title": socialUrl.code})) Help would be appreciated :)

Read this post in context »

Django and Rails with one common DB

Posted on April 19, 2014 at 11:03 AM by Stack Overflow RSS

I have earlier worked on Java+Spring to create a web-app. I have to build a new web-app now. It will have one centralized db. There will be two different type of instance of web-app. Web-App 1: a) It would have nothing to UI render, no html,js etc. b) All it need to give is some set of rest API which will b.1) create some new entries in DB b.2) modify some entries in DB b.3) retrieve some of DB records in JSON format. some frontend code ( doesn't belong to this app) will periodically fetch this details. c) it will be used by max by 100,000 people but at a given point of time, we can expect about 1000 users logged in and doing whats being said in b) Web-App2 : a) It will have some dashboards b) 90% of DB operations would be read operations c) 10% of DB operations would be write/modify d) There will be about 1000s of user of this system and at any given point of time hardly 50-1000 people will be accessing it. I am thinking of following. Have Web-App 1 created in python+Django and Web-App 2 created in RoR. I am planning to ...

Read this post in context »

javascript/jquery notification after successful form submission in django

Posted on April 19, 2014 at 10:32 AM by Stack Overflow RSS

i am new in javascript and its relative libraries and framework,i am just struggling to give notification when i have successfully complete any form submission.I have a project which is developed by Django and in this project i have an image upload form.Here is the of the image upload form... from django.shortcuts import render_to_response,RequestContext from photo.models import Photo from django.contrib.auth.decorators import login_required from myprofile.forms import DocumentForm from django.contrib.auth import authenticate, login, logout, REDIRECT_FIELD_NAME def UserImageUpload(request): if request.method == 'POST': form = DocumentForm(request.POST,request.FILES) if form.is_valid(): newdoc = Photo(photo = request.FILES['photo'],user = request.user) else: form = DocumentForm() uploaded_image = Photo.objects.all() return render_to_response('myprofile/user_image_upload.html',{'uploaded_image':uploaded_image,'form':form},context_instance = RequestContext(request)) and this is the from django import forms class DocumentForm(forms.Form): photo = forms.ImageField( label='Select a file' ) and this the template.. (upload_image.html) {% extends 'base.html'%} {% block title%}User Image Upload {% endblock %} {%block content%} <div class="container" style="margin-top:5%"> <div class="col-md-4 col-md-offset-4"> <div class="well"> <form action="" method="post" enctype="multipart/form-data"> {% csrf_token %} <p>{{ form.non_field_errors }}</p> <p>{{ }} {{ }}</p> <p> {{ }} {{ }} </p> <p><input type="submit" value="Upload" class="btn btn-success" /></p> </form> </div> </div> </div> {%endblock%} now i want to give notification to user after he succesfully upload an image, or you can ...

Read this post in context »

How to resize uploaded file with PIL before saving it?

Posted on April 19, 2014 at 10:08 AM by Stack Overflow RSS

I realize that this is a trivial task and this question was answered multiple times, but I just can't get it. Is there a way to resize and crop image before saving it to disk? All the solutions I found tend to store image, resize it, and then store it again. Can I do this? # extending form's save() method def save(self): import Image as pil # if avatar is uploaded, we need to scale it if self.files['avatar']: img =['avatar']) img.thumbnail((150, 150), pil.ANTIALIAS) # ??? # self.files['avatar'] is InMemoryUpladedFile # how do I replace self.files['avatar'] with my new scaled image here? # ??? super(UserForm, self).save()

Read this post in context »

Would you have an english tutor online?

Posted on April 19, 2014 at 10:08 AM by Django Forum RSS

Would you have an english tutor online?

Read this post in context »

Django-cas - 403 error after successfull logging in

Posted on April 19, 2014 at 9:58 AM by Stack Overflow RSS

I'm trying to include CAS authentication in my website. I installed and configured MIDDLEWARE_CLASSES, AUTHENTICATION_BACKENDS and CAS_SERVER_URL (as in I also setup own CAS server on localhost. In my I have: ... url(r'^accounts/login/$', 'django_cas.views.login'), url(r'^accounts/logout/$', 'django_cas.views.logout'), ... When I'm visiting accounts/login/ it redirects me to CAS server site. But after successfull log in, CAS server site redirects me back to accounts/login/?next=%2F&ticket=ticket_here and this URL gives me 403 error, none cookies are setted. What I should do to get it working?

Read this post in context »

What is the relationship between django cms and custom plugin models?

Posted on April 19, 2014 at 9:57 AM by Stack Overflow RSS

I've been working with django cms recently for the first time and I've created a gallery plugin for uploading images. It's quite a simple plugin, using a Gallery model which inherits from CMSPluginBase and then an Image model which has a ForeignKey to the gallery. The gallery plugin is attached to pages using a placeholder and then to view the images within a gallery I have created an apphook to link the plugin template to a view similar to; def detail(request, page_id=None, gallery_id=None): """ View to display all the images in a chosen gallery and also provide links to the other galleries from the page """ gallery = get_object_or_404(pk=gallery_id) # Then get all the other galleries to allow linking to those # from within a gallery more_galleries = Gallery.objects.all().exclude( images = gallery.images_set.all() context = RequestContext(request.context, { 'images': images, 'gallery': gallery, 'more_galleries': more_galleries }) return render_to_template('gallery-page.html', context) Now the problem I have with this method is when you publish a page in CMS it duplicates all of the Gallery objects on that page, so when I'm viewing the images, I've got twice as many links to the other galleries and I've also noticed that those links (which point to this view) ...

Read this post in context »

@login_required on all child paths of url

Posted on April 19, 2014 at 9:45 AM by Stack Overflow RSS

How can I have the @login_required shortcut to automatically apply to all child paths of a url in django? For example can I say everything that follows foo/, e.g. foo/bar/, /foo/1, foo/etc in one place instead of checking it in each view function?

Read this post in context »

Django admin site action not working after adding an intermediate from

Posted on April 19, 2014 at 8:49 AM by Stack Overflow RSS

I have a dajngo model for which I want to add custom actions.Where in this action I need to add one intermediate page with choice form (drop-down selection). I used below code to get this. The Model Class: class VerificationAdmin(admin.ModelAdmin): list_display = ('id','asset_code', 'scan_time','credential','status','operator','location','auth_code','product_details') list_filter = ('status','operator','location') ordering = ('-scan_time',) search_fields = ('asset_code',) actions = ['set_interval'] class AddScanningIntervalForm(forms.Form): _selected_action = forms.CharField(widget=forms.MultipleHiddenInput) period_choice=["4 hrs","6 hrs","8 hrs","10 hrs","12 hrs"] interval = forms.ChoiceField(choices=[(x, x) for x in period_choice]) @csrf_exempt def set_interval(self, request, queryset): print "before action" form = None if 'apply' in request.POST: form = self.AddScanningIntervalForm(request.POST) print "action taken" if form.is_valid(): interval = form.cleaned_data['interval'] print interval count = 0 for vObj in queryset: print vObj.asset_code,vObj.status,interval at=AlertTable(asset_code=vObj.asset_code, status=vObj.status,interval=interval) count += 1 self.message_user(request, "Scanning Policy Successfully added to %s assets %s." %count) return HttpResponseRedirect(request.get_full_path()) if not form: form = self.AddScanningIntervalForm(initial={'_selected_action': request.POST.getlist(admin.ACTION_CHECKBOX_NAME)}) return render_to_response('admin/set_alert.html', {'verifications': queryset,'tag_form': form},context_instance=RequestContext(request)) set_interval.short_description = "Add Periodic Scanning Policy" Add the template part: <!DOCTYPE html> {% extends "admin/base_site.html" %} {% block content %} <p>Select tag to apply:</p> <form action="" method="post"> {{ tag_form }} {% csrf_token %} <p>The scanning policy will be applied to:</p> <ul>{{ verifications|unordered_list }}</ul> <input type="hidden" name="action" value="add_tag" /> <input type="submit" name="apply" value="Set Interval" /> </form> {% endblock %} ...

Read this post in context »

Last 10 mins query result wen wrong .

Posted on April 19, 2014 at 8:34 AM by Stack Overflow RSS

dt = datetime.datetime.strptime(rp('datetime'), "%d%m%Y%H%M%S") date = dt - relativedelta(minutes=10) l =LocationHistory.objects.filter(use=user,date_time__range=[date,dt],show_info='1').order_by('-id')[0] I'm Getting the whole days result when i'm filtering above queryset with datetime ="19042014105650". i need to Get only last 10 mins result .

Read this post in context »

Implement html output for a model field in Django

Posted on April 19, 2014 at 8:22 AM by Stack Overflow RSS

I've another quick question, I need to use very often a specific html representation for a model field. I know there is a lot of documentation for forms but what about simple model field ? For instance : class Status (models.Model): order = models.PositiveIntegerField(_(u'Order')) name = models.CharField(_(u'Name'), max_length=255, unique=True, db_index=True) color = models.CharField(_(u'Color'), max_length=6, null=True, blank=True) template.html {{status.order.as_span}} will be equivalent to <span>{{status.order}}<span> The first idea I have is to implement a function inside a manager but seems to break the MVC rules ... There is a proper way for this ?

Read this post in context »

is it possible to colspan in django tables 2

Posted on April 19, 2014 at 8:21 AM by Stack Overflow RSS

is it possible to use colspan in django tables 2? I have 5 rows with 4 cols, but i want my second row to be with 1 col colspan=4 How can i do this? Is it possible. Here is my code: class FavoriteContactTable(FavoriteTable): date_added = tables.Column() address = AddressColumn(empty_values=(), orderable=False) email = tables.EmailColumn(accessor='') phone = PhoneColumn(empty_values=()) class Meta: model = Favorite fields = ('address', 'email', 'phone', 'date_added') attrs = {"class": "table table-condensed table-striped table-hover"}

Read this post in context »

How to insert data to django database without forms

Posted on April 19, 2014 at 8:11 AM by Stack Overflow RSS

Hi I am trying to insert data to the database in django without forms. This is my file def updatetrans(request): json_data=open('/home/ttt/Abc/a.json').read() data = json.loads(json_data) for pk, pv in data.iteritems(): for k,v in pv.iteritems(): try: print k, " =>> ", pv['transcript'][1] except: pass This is my file url(r'^updatetrans/$', 'booki.account.views.updatetrans', name='updatetrans'), Here is my file. I have created two tables. And want to insert data in both of them seperately. class TransType(models.Model): name = models.TextField() def __unicode__(self): return class Trans(models.Model): trans = models.ForeignKey(TransType) script = models.CharField(max_length=200) def __unicode__(self): return self.trans I am getting the output on console. That output I want to save to the database. Plz help.

Read this post in context »

Nginx responds with 502 error

Posted on April 19, 2014 at 7:32 AM by Stack Overflow RSS

While trying to deploy my app to Digital ocean I did everything according to this tutorial: How To Deploy a Local Django App to a VPS. While Gunicorn is working perfectly and opens my app, Nginx, however, does not work, or causes a 502 error. Nginx log says, that : 2014/04/19 02:43:52 [error] 896#0: *62 connect() failed (111: Connection refused) while connecting to upstream, client:, server:, request: "GET / HTTP/1.1", upstream: "", host: "" My nginx configuration file looks like this: server { listen 80 default_server; listen [::]:80 default_server ipv6only=on; server_name; access_log off; location /static/ { alias /opt/myenv/static/; } location / { proxy_pass; proxy_set_header X-Forwarded-Host $server_name; proxy_set_header X-Real-IP $remote_addr; add_header P3P 'CP="ALL DSP COR PSAa PSDa OUR NOR ONL UNI COM NAV"'; } In Django.settings I have ALLOWED_HOSTS set to '[*]' Nginx is listening to port 80: tcp 0 0* LISTEN 894/nginx tcp6 0 0 :::80 :::* LISTEN 894/nginx I think that the point is that Nginx does not point user to Gunicorn for some reason...

Read this post in context »