Community

Django community: Django Q&A RSS

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

Django ManyToMany Relationship Raises error?

Posted on April 18, 2014 at 3:38 AM by Stack Overflow RSS

I am new to Django and need to create a form for team scheduling. The form reads the voter ID through a checkbox, and then add the object of voter ID to the particular Choice. Choice has a field named voters = ManyToMany(Voter) Now, what I do is: v = Voter.objects.filter(voter_name__icontains=request.POST.get('voter')) selected_choice.voter.add(v[0]) But this won't prevent them from voting twice. Does add() give an silenced error if the voter selected is already in the Choice? Many Thanks

Read this post in context »

How to see or show IN LIVE the samples of google api client for python?

Posted on April 18, 2014 at 2:40 AM by Stack Overflow RSS

From the Google Code Site I downloaded the file "google-api-python-client.zip" with the python samples for google app engine, this ZIP file contains the next samples: adexchangebuyer adexchangeseller adsense adsensehost analytics api-python-client-doc appengine audit blogger coordinate customsearch dfareporting django_sample groupssettings lista maps_engine plus prediction searchforshopping service_account storage storage_serviceaccount_appengine tasks_appengine translate urlshortener youtube I'm interested in the "django_sample" sample, however I like review all samples. The zip file downloaded has one setup file but I cannot run it.

Read this post in context »

How to auto generate __unicode__ methods on all my models?

Posted on April 18, 2014 at 12:49 AM by Stack Overflow RSS

I'm dealing with some django code in which all models have __unicode__ methods that look something like this: def __unicode__(self): return str(self.id) + "; " + ", " + self.first_name + " " + self.last_name (the format in all cases being: print self.id and then the rest of the fields separated by commas). What's the best way to clean up this sort of boilerplate? I was thinking of declaring a MyModel class with a __unicode__ method which lists all fields by inspection, and then having all my current models inherit from MyModel instead of the current django.db.models.Model. But doing so would change the underlying MySQL tables and I'd hate to have to do such a massive migration for a petty thing like this.

Read this post in context »

Django: How do I use Cache Machine to cache a model that uses GeoManager?

Posted on April 18, 2014 at 12:31 AM by Stack Overflow RSS

I'm using Cache Machine's Cache Manager on my non-geographic models using the pattern in the docs: from django.db import models from caching.base imoprt CachingManager, CachingMixin class Zomg(CachingMixin, models.Model): val = models.IntegerField() objects = CachingManager() But I have several models containing GeoDjango field types, and therefore must use GeoManager, e.g. class RecordArea(models.Model): polygon = models.MultiPolygonField(srid=4326) name = models.CharField(max_length=100) ... objects = models.GeoManager() How can I integrate these two managers on my geographic models? I'm on Django 1.5 / Python 2.7.5.

Read this post in context »

list as value of session variable in Django

Posted on April 18, 2014 at 12:27 AM by Stack Overflow RSS

I'm building a small Django app. The user is to build up a list of pairs of strings, by repeatedly submitting a pair of forms. But there is a problem. When the list is displayed, the strings which were to be elements of the pairs in the list wind up getting prefixed by the letter u. So for example instead of ['a','b'] ['c','d'] we get [u'a',u'b'] [u'c',u'd'] My impression is that Django treats values of session variables as strings. So maybe the problem has something to do with the conversion of lists. Here is the source of the view. def plisting(request): if 'plist' not in request.session: request.session['plist']=[] plist = request.session['plist'] if 'entry' in request.POST: entry = str(request.POST['entry']) key = str(request.POST['key']) plist = plist+[[entry,key]] request.session['plist'] = plist return render(request,'evaluator/plisting.html',{'plist':plist}) Thanks in advance for help, Max

Read this post in context »

Django: Problems uploading files with AJAX

Posted on April 17, 2014 at 11:33 PM by Stack Overflow RSS

I have a problem when I try to upload files with Ajax in Django. I'm using FormData on Javascript. But the problem is in the server side. The files arrive to request.POST as dataURL, it should arrive to request.FILES, but it's empty. This is my code: var form_data = new FormData(document.getElementById("form-theme-edit")), url = "/theme/edit/1"; $.ajax({ "url" : url, "method" : "POST", "enctype": "multipart/form-data", "data" : form_data, "processData" : false });

Read this post in context »

Django haystack, multiple applications url structre

Posted on April 17, 2014 at 11:15 PM by Stack Overflow RSS

i have two application in my django project. One is 'blog' the other is 'web' i have created search indexes and search templates for both. i want to create my urls like: blog/search/? web/search/? But how can i direct those urls to do seperate searches for blog and web?

Read this post in context »

How to setup DreamPie to mimic "manage.py shell" functionality

Posted on April 17, 2014 at 11:05 PM by Stack Overflow RSS

I would like to use DreamPie, a python shell, as a CLI that functions the same way that manage.py shell works. Additionally, it would be very nice to have some way to automatically run some code when the shell starts, like a set of import statements. If you are unfamiliar with the specifics of getting this to work with DreamPie, I could also appreciate knowing what it is that manage.py shell does so I could apply it to another shell environment/interpreter.

Read this post in context »

Why can't I call a method with arguments inside get_context_data?

Posted on April 17, 2014 at 10:53 PM by Stack Overflow RSS

I don't understand why can't I call a method with arguments inside get_context_data. By removing the argument It works. What's the recommended way of changing the class based view context before sending to the template ? class CustomerReportView(TemplateView): """Generate Customer Reports based on acct_id""" def whoami(self, username ): """ returns following information about the currently logged-in user {'Name':'', 'Email':''} """ records = {'Name':username, 'Email':'john.doe@email.com'} return records def get_context_data(self, **kwargs): context = super(CustomerReportView, self).get_context_data(**kwargs) context['now'] = CustomerReportView.whoami(self, 'john.doe@email.com') return context

Read this post in context »

Django haystack pages without models

Posted on April 17, 2014 at 10:51 PM by Stack Overflow RSS

I'm using django haystack to search content across my site. However, I have a few pages with do not have models. How do I add them to be indexed and searchable? I have a contact page (/contact), which contains no model. How do I get it to appear in the search results when a user queries 'contact' or 'contact us', etc? I have a store that is hosted on a different site. There is no view or model for this in my project. I just have a url redirect in urls.py. I'd like it to show up in the search results. For example, when a user searches for 'store', how do I get it to appear in the search results?

Read this post in context »

AWS S3 backend for ajax Django upload

Posted on April 17, 2014 at 10:30 PM by Stack Overflow RSS

I'm trying to implement an ajax upload in my DJANGO app using (ajax-ajax-uploader). everything seems to work fine but when i upload a file i get upload failed with a 500 error caused by a bad response from AWS S3: S3ResponseError at /ajax-upload↵S3ResponseError: 400 Bad Request↵<Error><Code>MalformedXML</Code><Message>The XML you provided was not well-formed or did not validate... here is my backend class : from ajaxuploader.backends.base import AbstractUploadBackend class S3Upload(AbstractUploadBackend): NUM_PARALLEL_PROCESSES = 4 def upload_chunk(self, chunk, *args, **kwargs): self._counter += 1 buffer = StringIO() buffer.write(chunk) self._pool.apply_async( self._mp.upload_part_from_file(buffer, self._counter)) buffer.close() def setup(self, filename, *args, **kwargs): self._bucket = boto.connect_s3( settings.AWS_ACCESS_KEY_ID, settings.AWS_SECRET_ACCESS_KEY ).lookup(settings.AWS_BUCKET_NAME) self._mp = self._bucket.initiate_multipart_upload(filename) self._pool = Pool(processes=self.NUM_PARALLEL_PROCESSES) self._counter = 0 def upload_complete(self, request, filename, *args, **kwargs): # Tie up loose ends, and finish the upload self._pool.close() self._pool.join() self._mp.complete_upload()

Read this post in context »

django: foreign key triggers as many queries as objects returned

Posted on April 17, 2014 at 10:23 PM by Stack Overflow RSS

I defined a UserProfile with a OneToOne rel to User. Basically: class UserProfile(models.Model): user = models.OneToOneField(User, related_name='profile', unique=True) When I query the UserProfile, I am surprised to see a query for each user in addition to the main query. For example, I have 6 users / userprofiles, in a shell, I do: from django.db import connection connection.queries = [] # reset UserProfile.objects.all() len(connection.queries) # 7 queries Looking at the queries, the first query is on the UserProfile table as expected but then there are 6 queries on the User table, one per user. Is that normal? I thought the FK were queried when accessed... SELECT "test_userprofile"."id", "test_userprofile"."created", "test_userprofile"."modified", "test_userprofile"."time_zone", "test_userprofile"."user_id" FROM "test_userprofile" LIMIT 21 SELECT "auth_user"."id", "auth_user"."password", "auth_user"."last_login", "auth_user"."is_superuser", "auth_user"."username", "auth_user"."first_name", "auth_user"."last_name", "auth_user"."email", "auth_user"."is_staff", "auth_user"."is_active", "auth_user"."date_joined" FROM "auth_user" WHERE "auth_user"."id" = 1 SELECT "auth_user"."id", "auth_user"."password", "auth_user"."last_login", "auth_user"."is_superuser", "auth_user"."username", "auth_user"."first_name", "auth_user"."last_name", "auth_user"."email", "auth_user"."is_staff", "auth_user"."is_active", "auth_user"."date_joined" FROM "auth_user" WHERE "auth_user"."id" = 2 etc.

Read this post in context »

Django is not printing _id to console

Posted on April 17, 2014 at 10:09 PM by Stack Overflow RSS

I have a simple Question and Answer app in Django 1.6 and I'm having trouble getting the question_id to print in the console. The answer submitted is printing just fine but no luck getting the question_id. It's not throwing any errors Here is my models.py. from django.db import models from django.contrib.auth.models import User # Create your models here. class Question(models.Model): user = models.ForeignKey(User) question = models.CharField(max_length=120) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) update = models.DateTimeField(auto_now_add=False, auto_now=True) def __unicode__(self): return self.question class Answer(models.Model): question = models.ForeignKey(Question) answer = models.CharField(max_length=120) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) update = models.DateTimeField(auto_now_add=False, auto_now=True) def __unicode__(self): return self.answer class UserAnswer(models.Model): user = models.ForeignKey(User) question = models.ForeignKey(Question) answer = models.ForeignKey(Answer, null=True, blank=True) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) update = models.DateTimeField(auto_now_add=False, auto_now=True) def __unicode__(self): return self.answer.answer Here is my views.py from django.contrib import messages from django.contrib.auth.models import User from django.shortcuts import render_to_response, RequestContext, Http404, HttpResponseRedirect from .models import Question, Answer, UserAnswer def all_questions(request): questions = Question.objects.all() if request.method == 'POST': print request.POST['question_id'] print request.POST['answer'] return render_to_response('questions/all.html', locals(), context_instance=RequestContext(request)) and here is my template. {% extends 'base.html' %} {% block content %} <div class='row'> {% for question in questions %} {{ question }}<br/> <form method='POST' action=''>{% csrf_token %} <input type='hidden' vlaue='{{ question.id }}' name='question_id'/> ...

Read this post in context »

Installing mezzanine, failed on pillow

Posted on April 17, 2014 at 10:09 PM by Stack Overflow RSS

I cannot get pillow installed. (env)noah:cupalensic2 broinjc$ which cc /usr/bin/cc (env)noah:cupalensic2 broinjc$ cc --version Apple LLVM version 5.1 (clang-503.0.40) (based on LLVM 3.4svn) Target: x86_64-apple-darwin13.1.0 Thread model: posix I ran pip install mezzanine and when it got to satisfying pillow it screwed up... cc -fno-strict-aliasing -fno-common -dynamic -g -Os -pipe -fno-common -fno-strict-aliasing -fwrapv -mno-fused-madd -DENABLE_DTRACE -DMACOSX -DNDEBUG -Wall -Wstrict-prototypes -Wshorten-64-to-32 -DNDEBUG -g -fwrapv -Os -Wall -Wstrict-prototypes -DENABLE_DTRACE -pipe -arch x86_64 -DHAVE_LIBZ -I/System/Library/Frameworks/Tcl.framework/Versions/8.5/Headers -I/System/Library/Frameworks/Tk.framework/Versions/8.5/Headers -I/opt/X11/include/freetype2 -I/Users/broinjc/cupalensic2/env/build/pillow/libImaging -I/Users/broinjc/cupalensic2/env/include -I/usr/local/include -I/opt/X11/include -I/usr/include -I/System/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -c _imaging.c -o build/temp.macosx-10.9-intel-2.7/_imaging.o clang: error: unknown argument: '-mno-fused-madd' [-Wunused-command-line-argument-hard-error-in-future] clang: note: this will be a hard error (cannot be downgraded to a warning) in the future error: command 'cc' failed with exit status 1 ---------------------------------------- Cleaning up... Command /Users/broinjc/cupalensic2/env/bin/python -c "import setuptools;__file__='/Users/broinjc/cupalensic2/env/build/pillow/setup.py';exec(compile(open(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /var/folders/lg/y_cwnrnd3rn4x_j1sbd1mg_h0000gn/T/pip-o0HQHe-record/install-record.txt --single-version-externally-managed --install-headers /Users/broinjc/cupalensic2/env/include/site/python2.7 failed with error code 1 in /Users/broinjc/cupalensic2/env/build/pillow Storing complete log in /Users/broinjc/.pip/pip.log Any idea what might be going on here?

Read this post in context »

Django Tastypie - adding Fields to resource

Posted on April 17, 2014 at 9:58 PM by Stack Overflow RSS

I have a Complex Django model with (1) alot of fields and (2) dynamically generated data for this model that is not stored on the model (See below for a simplified example of my current Complex Resource and response). Currently, my Complex endpoint /m/api/v1/complex/ successfully returns STORED data on the model. Problem: What I would like to do is to use prepend_urls to add a custom endpoint which will return all of the data. This way I wouldn't have to use dehydrate wastefully adding data every time I called my current endpoint. Question How do I go about creating a prepend_url which injects additional data into a resource? or is there a better design pattern for solving this altogether? Comlex Resource: class ComplexResource(resource): class Meta: allowed_methods = ('get','put','post','delete','patch') queryset = Complex.objects.all() serializer = CustomSerializer() authorization = Authorization() authentication = Authentication() always_return_data = True filtering = { "field_1" : ALL, "field_2" : ALL, "field_N" : ALL } ordering = ["field_1", "field_2", "field_n"] Complex Response: /m/api/v1/complex/ { "meta": { "limit": 20, "next": null, "offset": 0, "previous": null, "total_count": 1 }, "objects": [ {"field_1": "foo", "field_2": "bar", ... , "field_n": "foobar"} ] } Complex Response w/all data: /m/api/v1/complex/all/ { "meta": { "limit": 20, ...

Read this post in context »

DjangoCMS multilingual site (i18n) and intro page

Posted on April 17, 2014 at 9:57 PM by Stack Overflow RSS

Im using i18n_patterns for my multilingual django site and I want to create an intropage with logo and animation + language chooser. But if I enter my site, it autoredirects me from www.mysite.com => www.mysite.com/en/ ... How can I do it? Here is my urls.py urlpatterns = i18n_patterns('', url(r'^admin/', include(admin.site.urls)), url(r'^sitemap\.xml$', 'django.contrib.sitemaps.views.sitemap', {'sitemaps': {'cmspages': CMSSitemap}}), url(r'^', include('cms.urls')), )

Read this post in context »

how to delay redirecting to page till the data is loaded in django or jquery?

Posted on April 17, 2014 at 9:30 PM by Stack Overflow RSS

I have a scenario as follows: I have a search query form. Once the form is submitted, I am re-directing to a new page (/search/results) to show the results. The problem is these results are not available immediately, they have to fetched from internet (I have a function that does web scraping). Once all the data is fetched, I want to redirect to that page. so basically 1) upon clicking the submit form, it should not re-direct immediately but wait (showing some message such as "processing your request" till the function has returned. Then redirect to that page to show the results 2) I have no idea how to signal that my function has returned. 3) I have been thinking something along these http://jsfiddle.net/DLy6j/ and this. But here there is a fixed delay time (hard coded like 3 sec or so). I want that delay time to be determined when my function (that does web scraping) is returned. please share your thoughts on how to get this working let me know if this not clear. I am using Django framework. but I guess this feature may not be possible to implement Django. But Jquery and Ajax should be helpful here.

Read this post in context »

Django asynchronous json request

Posted on April 17, 2014 at 9:05 PM by Stack Overflow RSS

I have a simple form with the the following inputs: type (radio) and parent (select) Depending on the type selected, there should be different options for the select. So whenever type is selected, it should make the json request to get a list of parents based on the type. So far what I have: json request (in template page) $.getJSON("{% url 'locations_by_type' %}", {type: type}, function(locations) { var locations_select = $("select[name='parent']"); $.each(locations, function (index, value) { locations_select.append($("<option/>", { value: key, text: value })); }); }); forms.py class LocationForm(forms.Form): LOCATION_TYPE_COICES = ( ("country", "country"), ("state", "state"), ("county", "county"), ("town", "town"), ) PARENT_CHOICES = [(l.parent, l.parent) for l in Location.objects.all()] name = forms.CharField(max_length=45) type = forms.ChoiceField( choices=LOCATION_TYPE_COICES, widget=RadioSelect(), required=True, ) parent = forms.ChoiceField( label = 'Parent Location', widget = Select(), required = False, help_text = "If you do not choose a parent location, this location will not appear on the locations page" ) views.py def locations_by_type(request): locations = Location.objects.get(type=request.GET["type"]) return json.dumps(locations) urls.py individual pattern url(r'^/locations_by_type', views.locations_by_type, name='locations_by_type'), And when I load the form, the form itself loads fine, however I get an error from the request in the javascript console: GET http://locations_by_type/?type=state net::ERR_NAME_NOT_RESOLVED Any ideas as to what I am doing wrong ...

Read this post in context »

Django : How to rollback in save method

Posted on April 17, 2014 at 8:39 PM by Stack Overflow RSS

Our app need to sync his data within a LDAP backend. Eg : Each time a user in saved in django some of the data must be saved in LDAP. For that, we use the django ldap backend which work great. At start we wrote the sync code in post_save signal of the member. Sync work well, but this way, we can't rollback database save if LDAP fail for any reason. So we plane to wrote sync code in overridded save method. But here too we can't find a way to rollback. The closest solution we have is : @transaction.commit_manually def save(self, *args, **kwargs): super(MyModel, self).save(*args, **kwargs) try: self.sync_with_ldap() except: transaction.rollback() raise else: transaction.commit() This code return a TransactionManagementError : "This is forbidden when an 'atomic' block is active." How can we do to : Rollback inside a save method Or another way to get our two models synced each overs

Read this post in context »

How Django framework works behind the scenes?

Posted on April 17, 2014 at 8:24 PM by Stack Overflow RSS

This might sound stupid question so apologies in advance. I am trying to understand how Django framework actually works behind the scenes. It's my understanding that Django does not run all the time and gets invoked by uwsgi/gunicorn or anything else when a request comes in and processed as follows: WsgiHandler or ModPythonHandler Import settings, custom exceptions Load middleware Middleware -> URLResolver Middleware -> View -> Template Middleware -> HttpResponse But what I cannot understand that is there any part of Django which keeps running all the time like cache management or some other functions or instances rather being created per request. I would really appreciate if you can explain a bit or give pointers.

Read this post in context »

Migrating Parse.com passwords to Django

Posted on April 17, 2014 at 8:11 PM by Stack Overflow RSS

I am trying to migrate the data from Parse.com to our own servers. In order to do this, user passwords have to be migrated too. Parse.com uses standard bcrypt password encryption and passwords appear in the following format (How would I move passwords out of Parse to another server?): $2a$10$UpoNYQ0YE/FRVrh3xt6QQeQ3HmTmskbW2Sfg5DX9fDQJnIHQd1LqG How do I move this string to Django auth_user table so it will be accepted by Django

Read this post in context »

Having trouble viewing Django template

Posted on April 17, 2014 at 7:42 PM by Stack Overflow RSS

I'm working on a tutorial for Django(1.6) and and can't seem to figure part three out. I've read several similar questions on SO already but they have not helped. I want to view a saved .html template but when I go to the :8000/polls page all I see is the simple html text that I saved. views: from django.http import HttpResponse from django.template import RequestContext, loader from polls.models import Poll # Create your views here. def index(request): latest_poll_list = Poll.objects.order_by('-pub_date')[:5] template = loader.get_template('polls/index.html') context = RequestContext(request, { 'latest_poll_list': latest_poll_list, }) return HttpResponse(template.render(context)) def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id) def results(request, poll_id): return HttpResponse("You're looking at the results of poll %s." % poll_id) def vote(request, poll_id): return HttpResponse("You're voting on poll %s." % poll_id) polls/index.html : (% if latest_poll_list %) <ul> (% for poll in latest_poll_list %) <li><a href="/polls/{{ poll.id }}/">{{ poll.question }}</a></li> (% endfor %) </ul> (% else %) <p>No polls are available.</p> (% endif %) Actual view that I see at :8000/polls/ (% if latest_poll_list %) (% for poll in latest_poll_list %) <li></li> #comes out as an indented bullet point (% endfor %) (% else %) No polls are available. (% endif %) I ...

Read this post in context »

Resetting migrations in south leads to 'table already exists'

Posted on April 17, 2014 at 7:29 PM by Stack Overflow RSS

OK, this is driving me nuts. I'm trying to remove and reset all my south migrations in my DEV environment for two apps, and start again with a clean slate, as my migrations files list was getting very long and I don't need them, as the models are constantly changing, and it's just DEV. Whatever I try, South constantly complains that the DB tables are already there. Going on this answer on SO, I first remove my migrations dir entirely from each app: rm -r <my-app>/migrations No problem. Then reset the south tables: python manage.py reset south Again, no worries. Now tell south that I want those apps managed: python manage.py convert_to_south <appname> All seems fine, it even creates the initial migration and runs the --fake: Created 0001_initial.py. You can now apply this migration with: ./manage.py migrate CC - Soft matched migration 0001 to 0001_initial. Running migrations for CC: - Migrating forwards to 0001_initial. > CC:0001_initial (faked) OK, so according to my (incorrect) understanding, I now have my existing tables managed by south. South knows that the tables ALREADY exist, as we ran initial as --fake. Now I add a new field to a model, run schemamigration then migrate on ...

Read this post in context »

How to assign values to inline formset fields

Posted on April 17, 2014 at 7:07 PM by Stack Overflow RSS

How to assign values to inline formset fields in Admin, the documents suggest this code: #For example to attach request.user to each changed formset model instance: class ArticleAdmin(admin.ModelAdmin): def save_formset(self, request, form, formset, change): instances = formset.save(commit=False) for instance in instances: instance.user = request.user instance.save() formset.save_m2m() but this code doesn't work for me, I have to inline formsets, one I want to show to the user to insert his data, the second I don't want to show to the user and I want to assign the values my self. Any ideas? Thank you.

Read this post in context »

How to retain the values of django template variables after adding it dynamically by javascript innerHTML?

Posted on April 17, 2014 at 7:06 PM by Stack Overflow RSS

1.This code is in my django template: {% for var in var_list %} <div id="button1"> <a href="#" class="btn btn-primary btn-sm" href="#" onclick="changeButton( '{{ request.session.variable1 }}', '{{ var.fields.variable2}}');return false;">Click to Modify</a> </div> {% endfor %} 2. I am calling changeButton javascript function to change the interHTML as to change the button itself function changeButton(var1 , var2) { document.getElementById("button1").innerHTML='<div class="btn-group"><a href="#" class="btn btn-success btn-sm" onclick="revertButton();return false;">';} 3. Again the old button I am restoring it by revertButton javascript function function revertButton() { document.getElementById("button1").innerHTML='<a href="#" class="btn btn-primary btn-sm" href="#" onclick="changeButton( '{{ request.session.variable1 }}', '{{ var.fields.variable2}}');return false;">Click to Modify</a>';} 4. Now the second time I am only able to get var1 i.e session variable and not able to get var2 which is django template variable. How to resolve it?

Read this post in context »