Django community: Django Q&A RSS

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

Django - Idea for building a field calculator

Posted on April 23, 2014 at 6:37 PM by Stack Overflow RSS

I was looking for a field calculator plugin, but I think none exists. I would like to have ideas or hints about the best way (simplest is the best) I could develop a plugin that allow user to make calculations on fields using mathematical expression. For beginning I would just let user type an expression in a form and send it through ajax: 'field4' = ('field1' + 'field2') / 'field3' Then, I wonder how I could take such expression and do the calculation in the server side? def fieldCalculator(request): expression = request.GET['expression'] queryset = Models.objects.all() for object in queryset: #I wonder how to do this part using expression object.field4 = (object.field1 + oject.field2) / object.field3

Read this post in context »

Django NoReverseMatch on URL

Posted on April 23, 2014 at 6:31 PM by Stack Overflow RSS

I'm running Django 1.4 w/ Python 2.7 on Ubuntu 12.04. I have a website that I've added a URL namespace and am accessing it through the template {% url common:utilities:index %}. Everything works fine locally. I have a staging server that is failing (good thing I have a staging server :)). Error from the Django debug: Exception Type: NoReverseMatch Exception Value: u'utilities' is not a registered namespace inside 'common' <a href="{% url common:utilities:index %}" class="responsive-tooltip" data-placement="right" title="Utilities"> I've double checked all the files and have verified the namespacing is correct - everyone in my team has verified this locally. project urlpatterns = patterns('', url(r'^common/', include('common.urls', namespace='common')), ) common utilitiespatterns = patterns('', url(r'^$', views.ConversionUploadView.as_view(), name='index'), ) urlpatterns = patterns('common.views', url(r'^utilities/$', include(utilitiespatterns, namespace='utilities')), ) Obviously there are a lot more url routes than what I've put here. This is just for the sake of the reader. On the server I've cleared all the .pyc files. I've restarted nginx. I've cleared browser cache and opened in incognito. After all that failed I actually got into the server shell and used the urlresolvers to verify the namespacing. In [1]: from django.core import urlresolvers as u In [2]: u.reverse('common:utilities:index') Out[2]: '/common/utilities/' I ...

Read this post in context »

Django Admin Custom Button Not Working

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

For my Django custom user model, I have a license_key field. On the admin interface, for ease of usability, I am trying to create a button, which generates a new license_key for the user you are currently looking at. Here is me overriding the change_form.html, like suggested in the Django docs. /main/templates/admin/main/MyUser/change_form.html: {% extends "admin/change_form.html" %} {% load i18n admin_urls %} {% block form_top %} <form class="form-horizontal" method="POST" action="/auth/gen_new_aero_license/"> {% csrf_token %} <div class="control-group"> <div class="controls controls-row"> <button type="submit" class="btn btn-primary"> Generate new license </button> </div> </div> </form> {% endblock %} This form calls a function I have defined in my main views file... main/ def auth_gen_new_aero_license(request): u = MyUser.objects.get(username=request.user.username) u.license_key = 'XXX' return redirect('/') And here's my definition for this new function, because it may help: url(r'^auth/gen_new_aero_license/$', 'main.views.auth_gen_new_aero_license', name='auth_gen_new_aero_license'), I am not even calling the script to generate a new dynamic license_key within I am just setting it to some random value for testing purposes. So here's the problem: when I click the button, it just refreshes the current user I am on and all the values have been deleted, thus giving me errors. It is as if it tried to delete all the fields and ...

Read this post in context »

Using Javascript to dynamically add Django formsets

Posted on April 23, 2014 at 6:16 PM by Stack Overflow RSS

I'm trying to implement this django snippet into my code. the instructions state to "Handle the 'click' event for your add and delete buttons", but I'm new to using Javascript and am having a hard time figuring out the last configuration step. Here's what I've got: {% extends "base.html" %} {% block base_content %} <script src="{{ STATIC_URL }}js/jquery.min.js"></script> <script src="{{ STATIC_URL }}js/dynamic-formset.js"></script> <script src="{{ STATIC_URL }}js/jquery.formset.js"></script> <script type="text/javascript"> $(function() { $(".inline.{{ serial_form.prefix }}").formset({ prefix: "{{ serial_form.prefix }}", }) $(".inline.{{ part_form.prefix }}").formset({ prefix: "{{ part_form.prefix }}", }) }) </script> <script type="text/javascript"> $(function () { $('.add-row').click(function() { return addForm(this, 'form'); }); $('.delete-row').click(function() { return deleteForm(this, 'form'); }) }) </script> <div class="content"> <h1>Create new tool:</h1> </div> <div> <form method="post"> {% csrf_token %} <table> {% for field in form %} {% if field.label != "Old control number" %} <tr><td>{{ field.label_tag }}:</td><td>{{ field }}</td></tr> {% endif %} {% endfor %} {{ serial_form.management_form }} {{ serial_form.non_form_errors }} {% for form in serial_form %} <tr class="dynamic-form"> <td>{{ form.label_tag }}</td> <td>{{ form }}</td> </tr> {% endfor %} <tr> <td colspan="4"><a href="javascript:void(0)" class="add-row"> Add another serial number</a></td></tr> {{ part_form.management_form }} {{ part_form.non_form_errors }} {% for form in part_form %} <tr><td>{{ form.label_tag }}</td><td>{{ form }}</td></tr> {% endfor %} </table> <input ...

Read this post in context »

Statics Files Django on Heroku Deployment

Posted on April 23, 2014 at 6:09 PM by Stack Overflow RSS

I have my app runnning in Heroku, everything works really good with my models and forms, but there is a problem, I can't see any of my styles neither for my templates not for Django Grappelli, how can I solve this problem? Thank you.

Read this post in context »

using django-waffle flags with google app engine

Posted on April 23, 2014 at 6:06 PM by Stack Overflow RSS

I just installed django-waffle to my app that's running on google app engine. But when I try to manage my flags from the command line using the wrapper, I get this error: AssertionError: No api proxy found for service "memcache" Any ideas for how to manage this?

Read this post in context »

Read radio choice using POST dictionary in Django form

Posted on April 23, 2014 at 6:05 PM by Stack Overflow RSS

I have form <form method = "POST"> <input type = "radio" name = "dummy" value "foo">Apple</input> <input type = "radio" name = "dummy" value "bar">Orange</input> </form> I am not able to read value(foo|bar) in def main(request): print request.POST['dummy'] #It doesn't print print request.POST.get('dummy','') #It doesn't print Where am I wrong?

Read this post in context »

Django Forms: How to validate if two fields are the same, e.g. email or password?

Posted on April 23, 2014 at 5:52 PM by Stack Overflow RSS

I have scoured related SO posts and Django docs, can't quite get it to work. My form: from django import forms class SignUpForm(forms.Form): (...) email = forms.EmailField(max_length=50) email_conf = forms.EmailField(max_length=50) def clean(self): form_data = self.cleaned_data if form_data['email'] != form_data['email_conf']: self._errors['email_conf'] = 'Emails do not match.' # attempt A self.add_error('email', 'Emails do not match.') # attempt B raise forms.ValidationError('Emails do not match.') # attempt C return form_data If the emails do NOT match, I'd like for Django to use my message string in the same manner as its other validations -- as a <li> element of <ul class='errorlist'> under the 'email_conf' field. From the three attempts above, the only one that actually seems to do something is #A, but the message is inserted into the {{ form.email_conf.errors }} template as a plain string (not as a list item). The other two attempts do not do anything, and in ALL cases if either field is empty, Django now throws KeyError. Would love to know what's the correct way to achieve the result I'm after. Thanks!

Read this post in context »

Implementing a chat on a server

Posted on April 23, 2014 at 5:34 PM by Stack Overflow RSS

Im developing a user based androaid app. And I want to add the option for users to comunicate with each other. In addition I want to allow users to see whos online. I using android as client side. And python as server side. I can lmagen its not simple, but I have no clue how to start. So I will appretiate every help. Thank you

Read this post in context »

Fetch data from DB on every pageload

Posted on April 23, 2014 at 5:28 PM by Stack Overflow RSS

I basically need to make a DB query on every view within an app, in order to pass some data to my templates. Since views are not classes, but simple functions, I can't have a construct, where I can do the query. So, structurally speaking, what is the best practice on where to put this kind of logic? I probably could just create a template tag and do the queries there, but it seems like not very well organized to me.

Read this post in context »

Django complex query and display

Posted on April 23, 2014 at 5:25 PM by Stack Overflow RSS

I'll try to make my requirements clear. Say, I have a Project model, with some instances in it. Then I have another model Progress to keep the progress of each project every month. Here is the model: class Progress(models.Model): project = models.ForeignKey(Project) month = models.DateField() # just use the first day to refer the month, not the key point value = models.IntegerField() However, projects may not start at the same time. So in our database, we may have rows like: id | project_id | month | value 1 | 1 | 2014-01-01 | 10 2 | 1 | 2014-02-01 | 20 3 | 2 | 2014-02-01 | 15 4 | 1 | 2014-03-01 | 30 5 | 2 | 2014-03-01 | 30 I want to have an output like this: | 14-01 | 14-02 | 14-03 project1 | 10 | 20 | 30 project2 | / | 15 | 30 For empty cells, both slash or zero will be ok. I don't know how to generate 6 cells with 5 rows of data. Should I implement this in template or in view? I tried in template, but since django template doesn't support break, continue of loop, it may not be ...

Read this post in context »

ImportError: No module named rest_framework.authtoken

Posted on April 23, 2014 at 5:19 PM by Stack Overflow RSS

I'm using django rest-framework's, (DRF), token authentication in my project to create tokens when a user is created. Everything works great until I add this line from the DRF docs: url(r'^api-token-auth/', 'rest_framework.authtoken.views.obtain_auth_token'), to create an endpoint that returns the token for a user after correctly posting the username and password. It throws this error: ImportError: No module named rest_framework.authtoken This is strange because DRF is fine with out this line, so it must be included in my PYTHONPATH. I've also run python syncdb and the appropriate migrations. Any idea what could be wrong? THIRD_PARTY_APPS = ( 'south', # Database migration helpers: 'crispy_forms', # Form layouts 'avatar', # for user avatars 'rest_framework', # for rest 'django_rq', # for aysnc 'rest_framework_swagger', # for exploring the api 'rest_framework.authtoken', ) INSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + LOCAL_APPS Full stack trace: Unhandled exception in thread started by <function wrapper at 0x1046096e0> Traceback (most recent call last): File "/Users/admin/dev/ncla-web/env/lib/python2.7/site-packages/django/utils/", line 93, in wrapper fn(*args, **kwargs) File "/Users/admin/dev/ncla-web/env/lib/python2.7/site-packages/django/core/management/commands/", line 101, in inner_run self.validate(display_num_errors=True) File "/Users/admin/dev/ncla-web/env/lib/python2.7/site-packages/django/core/management/", line 310, in validate num_errors = get_validation_errors(s, app) File "/Users/admin/dev/ncla-web/env/lib/python2.7/site-packages/django/core/management/", line 34, in get_validation_errors for (app_name, error) in get_app_errors().items(): File "/Users/admin/dev/ncla-web/env/lib/python2.7/site-packages/django/db/models/", line 196, in get_app_errors self._populate() File "/Users/admin/dev/ncla-web/env/lib/python2.7/site-packages/django/db/models/", line 78, ...

Read this post in context »

Is web2py better or worse than Django? Why?

Posted on April 23, 2014 at 5:15 PM by Quora RSS

0 AnswersWrite an answer on Quora

Read this post in context »

Django/Python models - multifield options

Posted on April 23, 2014 at 4:48 PM by Stack Overflow RSS

Let's say I created a Model AnObject, and one of the fields would be shape. If I have 3 sets shape types that the model could be, circle, square, triangle. What is the best way to write out the model? Let us assume that these shapes are not models (so no foreignkey field should be used here) themselves, they are just shape types. class AnObject(models.Model): shape = ?

Read this post in context »

Celery is running tasks that I disabled in django admin

Posted on April 23, 2014 at 4:35 PM by Stack Overflow RSS

I have django / celery set up to run certain tasks on my site. The tasks are configured with crontab expressions. One of them was buggy, so I disabled it in /admin, and restarted the celeryd/celerybeat. However the task continues to run. Am I doing something wrong? My script to run celeryd/celerybeat is: for id in `ps -ax | grep -i -e celerybeat | awk '{ print $1 }'`; do kill -9 $id done for id in `ps -ax | grep -i -e celeryd | awk '{ print $1 }'`; do kill -9 $id done nohup ./ celerybeat &> $LOG2 & nohup ./ celeryd &> $LOG2 &

Read this post in context »

Celery Cloudamqp creates new connection for each task

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

I am currently using running Django with Celery and then Cloudamqp as my broker with the free plan (max 3 connections). I'm able to connect just find and start up a periodic task just fine. When I run celery -A proj worker -l info 2 connections are created immediately on Cloudamqp and I am able to manually create multiple tasks on a 3rd connection and all is well. However, when I run celery beat with celery -A proj worker -B -l info all 3 connections are used and if celery beat creates 1 or more new tasks, another 4th connection will be created thus going over the maximum connections allowed. I've tried and currently have set BROKER_POOL_LIMIT = 1 but that doesn't seem to limit the connections I've also tried celery -A proj worker -B -l info celery -A proj worker -B -l info -c 1 celery -A proj worker -B -l info --autoscale=1,1 -c 1 with no luck. Why is there 2 connections made immediately that are doing nothing? Is there someway limit the initial celery connections to 0 or 1 or have the tasks share/run on the celery beat connection?

Read this post in context »

Django: Remove duplicate messages from storage

Posted on April 23, 2014 at 4:08 PM by Stack Overflow RSS

I'm using messages to add flash messages to the template (just as you'd expect). The problem I have is that if you double click to a page that generates a message then the message appears twice. I understand the logic here but am wondering how I can remove duplicated messages. click url message generated, saved in storage click url again before page renders second message generated, saved in storage response adds all messages from storage renders with two messages Ultimately I would like this to be a middleware so it can cover off all requests.

Read this post in context »

Submit duplicated forms with one button using Javascript

Posted on April 23, 2014 at 4:05 PM by Stack Overflow RSS

I'm having a form that it can be duplicated with a click of a button add more. But I'm facing a problem submitting all the forms at once. I'm using Django and Javascript. How can I fix it. {% extends "base.html" %} {% load crispy_forms_tags %} {% block content %} <div id="content" class="span9"> {% if form.errors %} <div class="alert alert-error"> <h4>{{ form.errors }}</h4> </div> {% endif %} <div class="span9"> <h1>Add new Profile</h1> <button id="button" class="btn btn-success" onlick="duplicate()">Add more</button> <hr/> <form id = "duplicater" class="form-horizontal ajax" action="{% url 'create_profile' %}" method="post">{% csrf_token %} {{ form|crispy}} <div class="form-actions"> <a class="btn ajax" data-spinner="off" href="{% url 'home' %}">Cancel</a> <input class="btn btn-primary" type="submit" value="Save"/> <hr/> </div> </form> </div> </div> <script type="text/javascript"> document.getElementById('button').onclick = duplicate; var i = 0; var original = document.getElementById('duplicater'); function duplicate() { var clone = original.cloneNode(true); // "deep" clone = "duplicater" + ++i; // there can only be one element with an ID original.parentNode.appendChild(clone); } </script> {% endblock %}

Read this post in context »

See object changes in post_save in django rest framework

Posted on April 23, 2014 at 3:58 PM by Stack Overflow RSS

I am curious if there is a way to see what has changed on an object after saving it using the Django Rest Framework. I have some special behavior I need to check if a field has been changed from its original value that I was hoping to handle using the post_save on generics.RetrieveUpdateDestroyAPIView. My first thought was to check using pre_save but it seems that pre_save's object argument already has the changes applied to it.

Read this post in context »

How to override Django model creation without affecting update?

Posted on April 23, 2014 at 3:24 PM by Stack Overflow RSS

I overrided the save() method of my Fooclass sothat when I create a Foo instance, some logic occurs. It works well. Nevertheless, I have other methods in other classes that update Foo instances, and of course, I have to save changes calling the save() method. But I want them to directly update without passing into the logic I made for object creation. Is there an elegant solution to that? What about overriding __init__() method instead of save()? (I was told it was a bad practice, but not sure to understand why) Thank you.

Read this post in context »

Django TypeError JSON not serializable when calling model.objects.values

Posted on April 23, 2014 at 3:08 PM by Stack Overflow RSS

In my application, users can create projects, and then create assets for that project. I want them to be able to sort through their assets for keywords or boolean fields, and then I want them to have the ability to download those sort results in a CSV file. I can do the sort just fine, but when I try to save the query to a session, I get a failure. Right now I'm just trying to save the description into the session, but I get this error: Exception Type: TypeError Exception Value: [{'description': u'The Sidekick. Totally badass'}] is not JSON serializable Does it have anything to do with unicode vs string? This is my views: def sort(request, project_id=1): thisuser = request.user project = Project.objects.get(id=project_id) if Project.objects.filter(Q(created_by=thisuser) | Q(project_access__access_list=thisuser), id=project_id).exists(): permission = 1 else: permission = None if Asset.objects.filter(project__id=project_id, unique_id=1): assets = 1 else: assets = None if request.POST: if request.POST.get('date_start') and request.POST.get('date_end'): date_start = datetime.strptime(request.POST['date_start'], '%m/%d/%Y') date_end = datetime.strptime(request.POST['date_end'], '%m/%d/%Y') q_date = Q(date_produced__range=[date_start, date_end]) else: q_date = Q(date_produced__isnull=False) | Q(date_produced__isnull=True) text_fields = { 'asset_type': request.POST.get('asset_type'), 'description': request.POST.get('description'), 'master_status': request.POST.get('master_status'), 'location': request.POST.get('location'), 'file_location': request.POST.get('file_location'), 'footage_format': request.POST.get('footage_format'), 'footage_region': request.POST.get('footage_region'), 'footage_type': request.POST.get('footage_type'), 'footage_fps': request.POST.get('footage_fps'), 'footage_url': request.POST.get('footage_url'), 'stills_credit': request.POST.get('stills_credit'), 'stills_url': request.POST.get('stills_url'), 'music_format': request.POST.get('music_format'), 'music_credit': ...

Read this post in context »

Automatically starting celery from within django app

Posted on April 23, 2014 at 2:39 PM by Stack Overflow RSS

I am getting a django 1.6 set up started on a linux (Debian Whiskey) server in Google Compute Engine. I've got celery 3.1 running in the background to help with some processes. When I start a new instance (using an snapshot I've created) I always need to start celery. I am looking for a way to start celery automatically on server-load. This is particularly helpful if the server decides to restart, as they seem to do now and then. To Achieve this I've edited the rc.local file $ sudo nano /etc/rc.local and this shows exit 0 [ -x /sbin/initctl ] && initctl emit --no-wait google-rc-local-has-run || true I've edited the file such that it reads cd /home/user/gce_app celery -A myapp.tasks --concurrency=1 --loglevel=info worker > output.log 2> errors.log & exit 0 [ -x /sbin/initctl ] && initctl emit --no-wait google-rc-local-has-run || true The directory /home/user/gce_app is where my django project resides and the directory I need to be in to start celery. However when, after restarting the instance, I type in: $ celery status Error: No nodes replied within time constraint. And opening the errors.log file I get /etc/rc.local: 14: /etc/rc.local: celery: not found Surely the cd at the start of ...

Read this post in context »

how to get data in 2D array in Django posted by AJAX

Posted on April 23, 2014 at 2:31 PM by Stack Overflow RSS

I am sending a 2D list through ajax to django here is my function for sending ajax request var tid = $(document).find(".table-box a").data("tid") var newFood = []; $('#order_table td.food_name').filter(function() { return $(this).data('status') == 'new'; }).each(function() { newFood.push( [$(this).text(), $(this).siblings('.quantity').text(), $(this).siblings('.price').text()] ); }); // This will create a 2D array like this [['food_name1','1','$10.00'],['foodname2', '2', '$11.00']] $.ajax({ type: "POST", url: $(this).data('url'), data: {tid:tid, newFood:newFood}, success: function success(data){ alert("Success") }, }); And I print the request.POST out in django and I get <QueryDict: {u'tid': [u'12'], u'newFood[0][]': [u'chick noodle', u'1', u'$2.00'], u'newFood[1][]': [u'Beef Rice', u'1', u'$29.00']}> when I print request.POST.get('newFood[0][]') , I get $2.00 I also tried request.POST.getlist('newFood[0]') but I get empty list [] Any ideas on how to fix this? How can I retrive each item one by one?

Read this post in context »

Django User Model Issue

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

I think i'm running into an error because of some sort of importing conflict, I don't really know. In one of the methods for for my UserProfile class I'm calling Event.objects.log(...) and in there i've got it to work correctly and add a new event record, however when I try and get the UserProfile to increment a notification for a user it encounters an error if I try an import it. Is there an error because UserProfile.update_user_level() calls Event.objects.log() which then calls UserProfile.objects.get()? I keep getting the following error when I try and import from accounts.models import UserProfile inside my events/ raise ImproperlyConfigured("AUTH_USER_MODEL refers to model '%s' that has not been installed" % settings.AUTH_USER_MODEL) django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'accounts.MyUser' that has not been installed This question is probably a bit awkward to explain, I just cannot seem to get this working

Read this post in context »

Getting Error while ordering a list in django

Posted on April 23, 2014 at 2:02 PM by Stack Overflow RSS

I am trying to order a queryset in the view. I get the following Error Message. Kindly help. SELECT DISTINCT ON expressions must match initial ORDER BY expressions class Op(models.Model): operator = models.ForeignKey(Employee, null=False) role = models.ForeignKey(Process, null=False) op = Op.objects.all().distinct('operator').order_by('operator__employeename')

Read this post in context »