Search Results

Search found 3554 results on 143 pages for 'django modelforms'.

Page 59/143 | < Previous Page | 55 56 57 58 59 60 61 62 63 64 65 66  | Next Page >

  • Iterating over a database column in Django

    - by curious
    I would like to iterate a calculation over a column of values in a MySQL database. I wondered if Django had any built-in functionality for doing this. Previously, I have just used the following to store each column as a list of tuples with the name table_column: import MySQLdb import sys try: conn = MySQLdb.connect (host = "localhost", user = "user", passwd="passwd", db="db") except MySQLdb.Error, e: print "Error %d: %s" % (e.args[0], e.args[1]) sys.exit (1) cursor = conn.cursor() for table in ['foo', 'bar']: for column in ['foobar1', 'foobar2']: cursor.execute('select %s from %s' % (column, table)) exec "%s_%s = cursor.fetchall()" % (table, column) cursor.close() conn.commit() conn.close() Is there any functionality built into Django to more conveniently iterate through the values of a column in a database table? I'm dealing with millions of rows so speed of execution is important.

    Read the article

  • TypeError while using django Form in editing an Entry

    - by damon
    I have an Entry model which can belong to a Category.I am providing a CategoryChoicesForm sothat the user can choose from various Categorys (from a dropdown list)when an Entry is created or edited. I am having trouble with the CategoryChoicesForm while editing the Entry.It throws a TypeError.. If somebody can make out what is happening..please advise me how to correct this. int() argument must be a string or a number, not 'QueryDict' /home/Django-1.4/django/db/models/fields/__init__.py in get_prep_value, line 537 ...views.py in edit_entry category_choices_form = CategoryChoicesForm(form_data) ... ...forms.py in __init__ self.fields['categoryoption'].queryset = Category.objects.filter(creator=self.creator) Here is the form class CategoryChoicesForm(forms.Form): categoryoption = forms.ModelChoiceField( queryset = Category.objects.none(), required=False,label='Category') def __init__(self, categorycreator,*args, **kwargs): super(CategoryChoicesForm, self).__init__(*args, **kwargs) self.creator=categorycreator self.fields['categoryoption'].queryset = Category.objects.filter(creator=self.creator) The edit_entry view is as follows @login_required @transaction.commit_on_success def edit_entry(request,id,template_name,page_title): form_data = get_form_data(request) entry = get_object_or_404(Entry,pk=id,author=request.user) ... category_choices_form = CategoryChoicesForm(form_data) ...

    Read the article

  • Django: IE doesn't load locahost or loads very SLOWLY

    - by reedvoid
    I'm just starting to learn Django, building a project on my computer, running Windows 7 64-bit, Python 2.7, Django 1.3. Basically whatever I write, it loads in Chrome and Firefox instantly. But for IE (version 9), it just stalls there, and does nothing. I can load up "http://127.0.0.1:8000" on IE and leave the computer on for hours and it doesn't load. Sometimes, when I refresh a couple of times or restart IE it'll work. If I change something in the code, again, Chrome and Firefox reflects changes instantly, whereas IE doesn't - if it loads the page at all. What is going on? I'm losing my mind here....

    Read the article

  • replay in django + apcahce + mod_wsgi ??

    - by Adam
    I have a simple django page that has a counter on it. I use Apache2 and mod_wsgi to serve it. First, when I enter this page, the counter shows 0, as it should. The second time when I enter the page the counter shows 1 - again, it is the right behavior. The problem begins now, cause when I enter this page the third time, I get 0 again. When I refresh it goes between 0, and 1, clearly using some cache or so. If I wait for some time and then try again, it will show 2, and 3, but will be stuck with those values, till this cache or whatever it is will be flushed, and then the counter continues. Does somebody knows how I can get it work right (the real scenario deals with getting data from the DB, but the problems with this strange cache are the same). BTW, I don't have any caching engine set in my django settings.

    Read the article

  • Django development server serving css but not js

    - by Wisco crew
    I am developing a django (1.4) app on my local machine. I am running the built-in development server with python manage.py runserver. In base.html I have: <link href="{{ STATIC_URL }}bootstrap.css" rel="stylesheet" type="text/css" /> <script src="{{ STATIC_URL }}boostrap-dropdown.js" type="text/javascript"></script> boostrap.css loads just fine when I load a page, but bootstrap-dropdown.js is 404'd. They are sitting right next to each other in my static directory. Relevant parts of settings.py: STATIC_URL = '/static/' STATICFILES_DIRS = ( '/home/username/projects/projectname/static',) Debug is set to True. I have tried it both with and without the staticfiles_urlpatterns trick. Django can find one file in the directory but not the other? I think I'm going crazy.

    Read the article

  • Value [...] not a valid choice, django-updown

    - by tamara
    I am trying to implemet django-updown https://github.com/weluse/django-updown. When I try to add vote trough the admin panel it says Value 1 not a valid choice. This is the models.py from the application: _SCORE_TYPE_CHOICES = ( ('-1', 'DISLIKE'), ('1', 'LIKE'), ) SCORE_TYPES = dict((value, key) for key, value in _SCORE_TYPE_CHOICES) class Vote(models.Model): content_type = models.ForeignKey(ContentType, related_name="updown_votes") object_id = models.PositiveIntegerField() key = models.CharField(max_length=32) score = models.SmallIntegerField(choices=_SCORE_TYPE_CHOICES) user = models.ForeignKey(User, blank=True, null=True, related_name="updown_votes") ip_address = models.IPAddressField() date_added = models.DateTimeField(default=datetime.datetime.now, editable=False) date_changed = models.DateTimeField(default=datetime.datetime.now, editable=False) Do you have an idea what could be wrong?

    Read the article

  • Migration for creating and deleting model in South

    - by Almad
    I've created a model and created initial migration for it: db.create_table('tvguide_tvguide', ( ('id', models.AutoField(primary_key=True)), ('date', models.DateField(_('Date'), auto_now=True, db_index=True)), )) db.send_create_signal('tvguide', ['TVGuide']) models = { 'tvguide.tvguide': { 'channels': ('models.ManyToManyField', ["orm['tvguide.Channel']"], {'through': "'ChannelInTVGuide'"}), 'date': ('models.DateField', ["_('Date')"], {'auto_now': 'True', 'db_index': 'True'}), 'id': ('models.AutoField', [], {'primary_key': 'True'}) } } complete_apps = ['tvguide'] Now, I'd like to drop it: db.drop_table('tvguide_tvguide') However, I have also deleted corresponding model. South (at least 0.6.2) is however trying to access it: (venv)[almad@eva-03 project]$ ./manage.py migrate tvguide Running migrations for tvguide: - Migrating forwards to 0002_removemodels. > tvguide: 0001_initial Traceback (most recent call last): File "./manage.py", line 27, in <module> execute_from_command_line() File "/usr/lib/python2.6/site-packages/django/core/management/__init__.py", line 353, in execute_from_command_line utility.execute() File "/usr/lib/python2.6/site-packages/django/core/management/__init__.py", line 303, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/lib/python2.6/site-packages/django/core/management/base.py", line 195, in run_from_argv self.execute(*args, **options.__dict__) File "/usr/lib/python2.6/site-packages/django/core/management/base.py", line 222, in execute output = self.handle(*args, **options) File "/home/almad/projects/mypage-all/lib/python2.6/site-packages/south/management/commands/migrate.py", line 91, in handle skip = skip, File "/home/almad/projects/mypage-all/lib/python2.6/site-packages/south/migration.py", line 581, in migrate_app result = run_forwards(mapp, [mname], fake=fake, db_dry_run=db_dry_run, verbosity=verbosity) File "/home/almad/projects/mypage-all/lib/python2.6/site-packages/south/migration.py", line 388, in run_forwards verbosity = verbosity, File "/home/almad/projects/mypage-all/lib/python2.6/site-packages/south/migration.py", line 287, in run_migrations orm = klass.orm File "/home/almad/projects/mypage-all/lib/python2.6/site-packages/south/orm.py", line 62, in __get__ self.orm = FakeORM(*self._args) File "/home/almad/projects/mypage-all/lib/python2.6/site-packages/south/orm.py", line 45, in FakeORM _orm_cache[args] = _FakeORM(*args) File "/home/almad/projects/mypage-all/lib/python2.6/site-packages/south/orm.py", line 106, in __init__ self.models[name] = self.make_model(app_name, model_name, data) File "/home/almad/projects/mypage-all/lib/python2.6/site-packages/south/orm.py", line 307, in make_model tuple(map(ask_for_it_by_name, bases)), File "/home/almad/projects/mypage-all/lib/python2.6/site-packages/south/utils.py", line 23, in ask_for_it_by_name ask_for_it_by_name.cache[name] = _ask_for_it_by_name(name) File "/home/almad/projects/mypage-all/lib/python2.6/site-packages/south/utils.py", line 17, in _ask_for_it_by_name return getattr(module, bits[-1]) AttributeError: 'module' object has no attribute 'TVGuide' Is there a way around?

    Read the article

  • installed openstack using devstack install shell script but getting 500 error when i try opening dashboard

    - by Arvind
    I followed the instructions at http://devstack.org/guides/single-machine.html to install OpenStack. I first installed Ubuntu on my Windows 7 PC using the officially supported Windows installer for Ubuntu 12.04 LTS. And after that I followed the instructions at above page to install OpenStack. As per instructions, I should be able to access the dashboard aka Horizon, at http://192.168.1.4/ (thats the IP of the PC on which I installed Ubuntu-OpenStack). However I am getting a 500 error web page when I open that. How do I resolve this error? I want to set up a dev environment for OpenStack. For your ref, the whole error message is given now-- FilterError at / /usr/bin/env: node: No such file or directory Request Method: GET Request URL: http://192.168.1.4/ Django Version: 1.4.2 Exception Type: FilterError Exception Value: /usr/bin/env: node: No such file or directory Exception Location: /usr/local/lib/python2.7/dist-packages/compressor/filters/base.py in input, line 133 Python Executable: /usr/bin/python Python Version: 2.7.3 Python Path: ['/opt/stack/horizon/openstack_dashboard/wsgi/../..', '/opt/stack/python-keystoneclient', '/opt/stack/python-novaclient', '/opt/stack/python-openstackclient', '/opt/stack/keystone', '/opt/stack/glance', '/opt/stack/python-glanceclient/setuptools_git-0.4.2-py2.7.egg', '/opt/stack/python-glanceclient', '/opt/stack/nova', '/opt/stack/horizon', '/opt/stack/cinder', '/opt/stack/python-cinderclient', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-linux2', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages/PIL', '/usr/lib/python2.7/dist-packages/gst-0.10', '/usr/lib/python2.7/dist-packages/gtk-2.0', '/usr/lib/pymodules/python2.7', '/usr/lib/python2.7/dist-packages/ubuntu-sso-client', '/usr/lib/python2.7/dist-packages/ubuntuone-client', '/usr/lib/python2.7/dist-packages/ubuntuone-control-panel', '/usr/lib/python2.7/dist-packages/ubuntuone-couch', '/usr/lib/python2.7/dist-packages/ubuntuone-storage-protocol', '/opt/stack/horizon/openstack_dashboard'] Server time: Sat, 27 Oct 2012 08:43:29 +0000 Error during template rendering In template /opt/stack/horizon/openstack_dashboard/templates/_stylesheets.html, error at line 3 /usr/bin/env: node: No such file or directory 1 {% load compress %} 2 3 {% compress css %} 4 <link href='{{ STATIC_URL }}dashboard/less/horizon.less' type='text/less' media='screen' rel='stylesheet' /> 5 {% endcompress %} 6 7 <link rel="shortcut icon" href="{{ STATIC_URL }}dashboard/img/favicon.ico"/> 8 Also, the traceback is now given below-- Environment: Request Method: GET Request URL: http://192.168.1.4/ Django Version: 1.4.2 Python Version: 2.7.3 Installed Applications: ('openstack_dashboard', 'django.contrib.contenttypes', 'django.contrib.auth', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'compressor', 'horizon', 'openstack_dashboard.dashboards.project', 'openstack_dashboard.dashboards.admin', 'openstack_dashboard.dashboards.settings', 'openstack_auth') Installed Middleware: ('django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'horizon.middleware.HorizonMiddleware', 'django.middleware.doc.XViewMiddleware', 'django.middleware.locale.LocaleMiddleware') Template error: In template /opt/stack/horizon/openstack_dashboard/templates/_stylesheets.html, error at line 3 /usr/bin/env: node: No such file or directory 1 : {% load compress %} 2 : 3 : {% compress css %} 4 : <link href='{{ STATIC_URL }}dashboard/less/horizon.less' type='text/less' media='screen' rel='stylesheet' /> 5 : {% endcompress %} 6 : 7 : <link rel="shortcut icon" href="{{ STATIC_URL }}dashboard/img/favicon.ico"/> 8 : Traceback: File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response 111. response = callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python2.7/dist-packages/django/views/decorators/vary.py" in inner_func 36. response = func(*args, **kwargs) File "/opt/stack/horizon/openstack_dashboard/wsgi/../../openstack_dashboard/views.py" in splash 38. return shortcuts.render(request, 'splash.html', {'form': form}) File "/usr/local/lib/python2.7/dist-packages/django/shortcuts/__init__.py" in render 44. return HttpResponse(loader.render_to_string(*args, **kwargs), File "/usr/local/lib/python2.7/dist-packages/django/template/loader.py" in render_to_string 176. return t.render(context_instance) File "/usr/local/lib/python2.7/dist-packages/django/template/base.py" in render 140. return self._render(context) File "/usr/local/lib/python2.7/dist-packages/django/template/base.py" in _render 134. return self.nodelist.render(context) File "/usr/local/lib/python2.7/dist-packages/django/template/base.py" in render 823. bit = self.render_node(node, context) File "/usr/local/lib/python2.7/dist-packages/django/template/debug.py" in render_node 74. return node.render(context) File "/usr/local/lib/python2.7/dist-packages/django/template/loader_tags.py" in render 155. return self.render_template(self.template, context) File "/usr/local/lib/python2.7/dist-packages/django/template/loader_tags.py" in render_template 137. output = template.render(context) File "/usr/local/lib/python2.7/dist-packages/django/template/base.py" in render 140. return self._render(context) File "/usr/local/lib/python2.7/dist-packages/django/template/base.py" in _render 134. return self.nodelist.render(context) File "/usr/local/lib/python2.7/dist-packages/django/template/base.py" in render 823. bit = self.render_node(node, context) File "/usr/local/lib/python2.7/dist-packages/django/template/debug.py" in render_node 74. return node.render(context) File "/usr/local/lib/python2.7/dist-packages/compressor/templatetags/compress.py" in render 147. return self.render_compressed(context, self.kind, self.mode, forced=forced) File "/usr/local/lib/python2.7/dist-packages/compressor/templatetags/compress.py" in render_compressed 107. rendered_output = self.render_output(compressor, mode, forced=forced) File "/usr/local/lib/python2.7/dist-packages/compressor/templatetags/compress.py" in render_output 119. return compressor.output(mode, forced=forced) File "/usr/local/lib/python2.7/dist-packages/compressor/css.py" in output 51. ret.append(subnode.output(*args, **kwargs)) File "/usr/local/lib/python2.7/dist-packages/compressor/css.py" in output 53. return super(CssCompressor, self).output(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/compressor/base.py" in output 230. content = self.filter_input(forced) File "/usr/local/lib/python2.7/dist-packages/compressor/base.py" in filter_input 192. for hunk in self.hunks(forced): File "/usr/local/lib/python2.7/dist-packages/compressor/base.py" in hunks 167. precompiled, value = self.precompile(value, **options) File "/usr/local/lib/python2.7/dist-packages/compressor/base.py" in precompile 210. command=command, filename=filename).input(**kwargs) File "/usr/local/lib/python2.7/dist-packages/compressor/filters/base.py" in input 133. raise FilterError(err) Exception Type: FilterError at / Exception Value: /usr/bin/env: node: No such file or directory

    Read the article

  • how to import csv data into django models

    - by little_fish
    i have some csv data and i want to export into django models the example of csv data 1;"02-01-101101";"Worm Gear HRF 50";"Ratio 1 : 10";"input shaft, output shaft, direction A, color dark green"; 2;"02-01-101102";"Worm Gear HRF 50";"Ratio 1 : 20";"input shaft, output shaft, direction A, color dark green"; 3;"02-01-101103";"Worm Gear HRF 50";"Ratio 1 : 30";"input shaft, output shaft, direction A, color dark green"; 4;"02-01-101104";"Worm Gear HRF 50";"Ratio 1 : 40";"input shaft, output shaft, direction A, color dark green"; 5;"02-01-101105";"Worm Gear HRF 50";"Ratio 1 : 50";"input shaft, output shaft, direction A, color dark green"; and i have some django models name Product in Product there is some fields like name, description and price and i want to something like this product=Product() product.name = "Worm Gear HRF 70(02-01-101116)" product.description = "input shaft, output shaft, direction A, color dark green" product.price = 100

    Read the article

  • nginx serving Django static media | 502 bad gateway

    - by MMRUser
    I'm trying to serve Django static media through nginx, Here's my nginx.conf server { listen 7777; listen localhost:7777; server_name example.com; location / { proxy_pass http://localhost:7777; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; client_max_body_size 10m; client_body_buffer_size 128k; proxy_connect_timeout 90; proxy_send_timeout 90; proxy_read_timeout 90; proxy_buffer_size 4k; proxy_buffers 4 32k; proxy_busy_buffers_size 64k; proxy_temp_file_write_size 64k; } location /test-app-media/ { root /sites/mysite/staticmedia/; expires max; } } but give a 502 bad gateway error, the path to /sites/mysite/staticmedia/ is in the nginx root/ is that the problem.. Django running on Apache 2.2 + mod_wsgi nginx 0.7.65 Thanks..

    Read the article

  • Django queryset not returning the same values as the generated sql

    - by HRCerqueira
    Hello guys, I have the following queryset: subscribers = User.objects.values('email', 'username').filter( Q(subscription_settings__new_question='i') | Q(subscription_settings__new_question_watched_tags='i', marked_tags__id__in=question.tags.values('id'), tag_selections__reason='good') ).exclude(id=question.author.id) The problem is that when I evaluate the query I get only the values that are filtered by the first Q object (even if I reverse the order of the objects). So lets say that I was expecting the user A, B, C and D, where A and B are filtered by the first Q object and C and D by the second. But the queryset only returns A and B. I used the django debug toolbar to see the query that was actually being executed (and then I used a direct print statement like "print subscriber.query.as_sql()" just to be sure) and then evaluated the query directly using psql (I'm using postgres by the way), and I get the results I expect. Here's the query btw: SELECT "auth_user"."email", "auth_user"."username" FROM "auth_user" LEFT OUTER JOIN "forum_markedtag" ON ("auth_user"."id" = "forum_markedtag"."user_id") INNER JOIN "forum_defaultsubscriptionsetting" ON ("auth_user"."id" = "forum_defaultsubscriptionsetting"."user_id") WHERE ((("forum_markedtag"."reason" = E'good' AND "forum_defaultsubscriptionsetting"."new_question_watched_tags" = E'i' AND "forum_markedtag"."tag_id" IN (SELECT U0."id" FROM "tag" U0 INNER JOIN "question_tags" U1 ON (U0."id" = U1."tag_id") WHERE U1."question_id" = 64 )) OR "forum_defaultsubscriptionsetting"."new_question" = E'i' ) AND NOT ("auth_user"."id" = 10 )) Thanks in advance EDIT: I tried to break the queryset into two, one that uses the first Q object as the filter and another one with the second Q object, and although the second queryset produces the correct sql that returns the correct values when evaluated directly, it still doesn't return nothing when evaluated as a django queryset. heres the alternative code: subscribers = User.objects.values('email', 'username').filter( subscription_settings__new_question='i').exclude(id=question.author.id) subscribers2 = User.objects.values('email', 'username').filter( subscription_settings__new_question_watched_tags='i', marked_tags__id__in=question.tags.values('id'), tag_selections__reason='good').exclude(id=question.author.id)

    Read the article

  • File Uploading In Google Application Engine Using Django

    - by Ayush
    I am using gae with django. I have an project named MusicSite with following url mapping- urls.py from django.conf.urls.defaults import * from MusicSite.views import MainHandler from MusicSite.views import UploadHandler from MusicSite.views import ServeHandler urlpatterns = patterns('',(r'^start/', MainHandler), (r'^upload/', UploadHandler), (r'^/serve/([^/]+)?', ServeHandler), ) There is an application MusicSite inside MusicFun with the following codes- views.py import os import urllib from google.appengine.ext import blobstore from google.appengine.ext import webapp from google.appengine.ext.webapp import blobstore_handlers from google.appengine.ext.webapp import template from google.appengine.ext.webapp.util import run_wsgi_app def MainHandler(request): response=HttpResponse() upload_url = blobstore.create_upload_url('http://localhost: 8000/upload/') response.write('') response.write('' % upload_url) response.write("""Upload File: """) return HttpResponse(response) def UploadHandler(request): upload_files=request.FILES['file'] blob_info = upload_files[0] response.redirect('http://localhost:8000/serve/%s' % blob_info.key()) class ServeHandler(blobstore_handlers.BlobstoreDownloadHandler): def get(self, resource): resource = str(urllib.unquote(resource)) blob_info = blobstore.BlobInfo.get(resource) self.send_blob(blob_info) now whenever a upload a file using /start and click Submit i am taken to a blank page with the following url- localhost:8000/_ah/upload/ahhnb29nbGUtYXBwLWVuZ2luZS1kamFuZ29yGwsSFV9fQmxvYlVwbG9hZFNlc3Npb25fXxgHDA These random alphabets keep varying but the result is same. A blank page after every upload. Somebody please help. The server responses are as below- INFO:root:"GET /start/ HTTP/1.1" 200 - INFO:root:"GET /favicon.ico HTTP/1.1" 404 - INFO:root:Internal redirection to http://localhost:8000/upload/ INFO:root:Upload handler returned 500 ERROR:root:Invalid upload handler response. Only 301, 302 and 303 statuses are permitted and it may not have a content body. INFO:root:"POST /_ah/upload/ ahhnb29nbGUtYXBwLWVuZ2luZS1kamFuZ29yGwsSFV9fQmxvYlVwbG9hZFNlc3Npb25fXxgCDA HTTP/1.1" 500 - INFO:root:"GET /favicon.ico HTTP/1.1" 404 -

    Read the article

  • Reversing Django URLs With Extra Options

    - by Justin Voss
    Suppose I have a URLconf like below, and 'foo' and 'bar' are valid values for page_slug. urlpatterns = patterns('', (r'^page/(?P<page_slug>.*)/', 'myapp.views.someview'), ) Then, I could reconstruct the URLs using the below, right? >>> from django.core.urlresolvers import reverse >>> reverse('myapp.views.someview', kwargs={'page_slug': 'foo'}) '/page/foo/' >>> reverse('myapp.views.someview', kwargs={'page_slug': 'bar'}) '/page/bar/' But what if I change my URLconf to this? urlpatterns = patterns('', (r'^foo-direct/', 'myapp.views.someview', {'page_slug': 'foo'}), (r'^my-bar-page/', 'myapp.views.someview', {'page_slug': 'bar'}), ) I expected this result: >>> from django.core.urlresolvers import reverse >>> reverse('myapp.views.someview', kwargs={'page_slug': 'foo'}) '/foo-direct/' >>> reverse('myapp.views.someview', kwargs={'page_slug': 'bar'}) '/my-bar-page/' However, this throws a NoReverseMatch exception. I suspect I'm trying to do something impossible. Any suggestions on a saner way to accomplish what I want? Named URLs aren't an option, since I don't want other apps that link to these to need to know about the specifics of the URL structure (encapsulation and all that).

    Read the article

  • Treebeard admin in Django

    - by Sharath
    I've setup Treebeard in Django and everything seems to have gone well. I tried to setup the admin system and I can see my models being presented in the admin interface. However, when I try to add new data using the admin interface, I get the following error in my template. The code still works fine, and I did a check in my DB and the data seems to be inserted properly. However, the view doesn't seem to load properly. Any idea about what is causing this?? The exception am getting is.. Caught an exception while rendering: Failed lookup for key [request] in u'[{\'action_index\': 0, \'block\': , , , , , , ]}, {\'block\': , , , ], , , , , \n \', ], , ], , , , ], , , \n \', , , , , , , , , ], , ], \n \']}, {\'cl\': , \'root_path\': None, \'actions_on_bottom\': False, \'title\': u\'Select album to change\', \'has_add_permission\': True, \'media\': , \'is_popup\': False, \'action_form\': , \'actions_on_top\': True, \'app_label\': \'gallery\'}, {\'MEDIA_URL\': \'\'}, {\'LANGUAGES\': ((\'ar\', \'Arabic\'), (\'bn\', \'Bengali\'), (\'bg\', \'Bulgarian\'), (\'ca\', \'Catalan\'), (\'cs\', \'Czech\'), (\'cy\', \'Welsh\'), (\'da\', \'Danish\'), (\'de\', \'German\'), (\'el\', \'Greek\'), (\'en\', \'English\'), (\'es\', \'Spanish\'), (\'et\', \'Estonian\'), (\'es-ar\', \'Argentinean Spanish\'), (\'eu\', \'Basque\'), (\'fa\', \'Persian\'), (\'fi\', \'Finnish\'), (\'fr\', \'French\'), (\'ga\', \'Irish\'), (\'gl\', \'Galician\'), (\'hu\', \'Hungarian\'), (\'he\', \'Hebrew\'), (\'hi\', \'Hindi\'), (\'hr\', \'Croatian\'), (\'is\', \'Icelandic\'), (\'it\', \'Italian\'), (\'ja\', \'Japanese\'), (\'ka\', \'Georgian\'), (\'ko\', \'Korean\'), (\'km\', \'Khmer\'), (\'kn\', \'Kannada\'), (\'lv\', \'Latvian\'), (\'lt\', \'Lithuanian\'), (\'mk\', \'Macedonian\'), (\'nl\', \'Dutch\'), (\'no\', \'Norwegian\'), (\'pl\', \'Polish\'), (\'pt\', \'Portuguese\'), (\'pt-br\', \'Brazilian Portuguese\'), (\'ro\', \'Romanian\'), (\'ru\', \'Russian\'), (\'sk\', \'Slovak\'), (\'sl\', \'Slovenian\'), (\'sr\', \'Serbian\'), (\'sv\', \'Swedish\'), (\'ta\', \'Tamil\'), (\'te\', \'Telugu\'), (\'th\', \'Thai\'), (\'tr\', \'Turkish\'), (\'uk\', \'Ukrainian\'), (\'zh-cn\', \'Simplified Chinese\'), (\'zh-tw\', \'Traditional Chinese\')), \'LANGUAGE_BIDI\': False, \'LANGUAGE_CODE\': \'en-us\'}, {}, {\'perms\': , \'messages\': [], \'user\': }, {}]' This happens after I hit the save button in Django admin. This is my admin.py implementation.. class MP_Album_Admin(TreeAdmin): pass admin.site.register(Album,MP_Album_Admin)

    Read the article

  • Django 404 page not showing up

    - by Matthew Doyle
    Hey all, I'm in the middle of putting up my first django application on shared hosting. This should be an easy thing, but I am just not seeing it. I tried to follow the directions of the django documentation, and created a 404.html page within my template folder. I just wrote "This is a 404 page." in the .html file. I also did the same thing for a 500.html page and wrote in it "This is a 500 page." However when I hit a 'bad page' I get a standard 404 page from the browser (Oops! This link appears to be broken. in Chrome) when I would expect "This is a 404 page." What's even more interesting is out of frustration I wrote {% asdfjasdf %} in the 404.html, and instead of getting the "Oops!..." error I get "This is a 500 page," so it definitely sees the 404.html template. Here's what I can confirm: Debug = False I am running apache on a shared hosting I have not done anything special with .htaccess and 404 errors. If I run with Debug = True, it says it's a 404 error. I am using FastCGI Anything else anyone think I could try? Thank you very much!

    Read the article

  • Django server side AJAX validation

    - by MMRUser
    Hi, Recently I'm trying to implement a simple Django application that include one server side AJAX validation, it's a simple form input field (username). I have used a pre-built in line AJAX validation library which uses jQuery. So the code goes like this HTML snippet <form id="simpleform" method="post" action="/done/"> Username:<input value="" class="validate[required,custom[noSpecialCaracters],length[0,20],ajax[ajaxUser]]" type="text" name="user" id="user" /> <input class="submit" type="submit" value="Validate"/> </form> The server side code snippet (embedded in to a php script) /* RECEIVE VALUE */ $validateValue=$_POST['validateValue']; $validateId=$_POST['validateId']; $validateError=$_POST['validateError']; /* RETURN VALUE */ $arrayToJs = array(); $arrayToJs[0] = $validateId; $arrayToJs[1] = $validateError; if($validateValue =="testname"){ // validate?? $arrayToJs[2] = "true"; // RETURN TRUE echo '{"jsonValidateReturn":'.json_encode($arrayToJs).'}'; // RETURN ARRAY WITH success }else{ for($x=0;$x<1000000;$x++){ if($x == 990000){ $arrayToJs[2] = "false"; echo '{"jsonValidateReturn":'.json_encode($arrayToJs).'}'; // RETURN ARRAY WITH ERROR } } } So my question is that how do I get this in to Python code (in order to use in Django environment) how do I get the user name from the input field in to the back end,I think the server side script snippet already does it but I want to know how to use this in my Pyhon code,and this is my first time using jQuery and I do need to use this same exact validation library. Your valuable corporation is needed. Thanks.

    Read the article

  • Mimic remote API or extend existing django model

    - by drozzy
    I am in a process of designing a client for a REST-ful web-service. What is the best way to go about representing the remote resource locally in my django application? For example if the API exposes resources such as: List of Cars Car Detail Car Search Dealership summary So far I have thought of two different approaches to take: Try to wrangle the django's models.Model to mimic the native feel of it. So I could try to get some class called Car to have methods like Car.objects.all() and such. This kind of breaks down on Car Search resources. Implement a Data Access Layer class, with custom methods like: Car.get_all() Car.get(id) CarSearch.search("blah") So I will be creating some custom looking classes. Has anyone encoutered a similar problem? Perhaps working with some external API's (i.e. twitter?) Any advice is welcome. PS: Please let me know if some part of question is confusing, as I had trouble putting it in precise terms.

    Read the article

  • Is it approproate it use django signals withing the same app

    - by Alex Lebedev
    Trying to add email notification to my app in the cleanest way possible. When certain fields of a model change, app should send a notification to a user. Here's my old solution: from django.contrib.auth import User class MyModel(models.Model): user = models.ForeignKey(User) field_a = models.CharField() field_b = models.CharField() def save(self, *args, **kwargs): old = self.__class__.objects.get(pk=self.pk) if self.pk else None super(MyModel, self).save(*args, **kwargs) if old and old.field_b != self.field_b: self.notify("b-changed") # Sevelar more events here # ... def notify(self, event) subj, text = self._prepare_notification(event) send_mail(subj, body, settings.DEFAULT_FROM_EMAIL, [self.user.email], fail_silently=True) This worked fine while I had one or two notification types, but after that just felt wrong to have so much code in my save() method. So, I changed code to signal-based: from django.db.models import signals def remember_old(sender, instance, **kwargs): """pre_save hanlder to save clean copy of original record into `old` attribute """ instance.old = None if instance.pk: try: instance.old = sender.objects.get(pk=instance.pk) except ObjectDoesNotExist: pass def on_mymodel_save(sender, instance, created, **kwargs): old = instance.old if old and old.field_b != instance.field_b: self.notify("b-changed") # Sevelar more events here # ... signals.pre_save.connect(remember_old, sender=MyModel, dispatch_uid="mymodel-remember-old") signals.post_save.connect(on_mymodel_save, sender=MyModel, dispatch_uid="mymodel-on-save") The benefit is that I can separate event handlers into different module, reducing size of models.py and I can enable/disable them individually. The downside is that this solution is more code and signal handlers are separated from model itself and unknowing reader can miss them altogether. So, colleagues, do you think it's worth it?

    Read the article

  • Web-based game in Python + Django and client browser polling

    - by ty
    I am creating a text-based game that implements a basic model in which multiple (10+) players interact with data and one moderator watches them and sets certain environmental statistics that affect gameplay. Recently I have begun to familiarize myself with Django. It seems to me that it would be an excellent tool for creating a game quickly, particularly because the nature of my game depends largely on sets of data (which lends itself quite well to a database). I am wondering how to "push" changes made by the game moderator to the players (for example, the moderator can decide to display an image to all players). The game is turn-based, not real-time, but certain messages need to be pushed out in roughly real-time. My thoughts: I could have each player's browser poll a status periodically (say, every 30 seconds) to see if there is a message from a moderator. But this forces a lag and means different players might receive it at different times. And reducing this interval to <10 seems like a bad idea for the server. Is there a better way to inform clients of changes? Would you suggest something other than using a web framework like Django? Thanks!

    Read the article

  • Django aggregate query generating SQL error

    - by meepmeep
    I'm using Django 1.1.1 on a SQL Server 2005 db using the latest sqlserver_ado library. models.py includes: class Project(models.Model): name = models.CharField(max_length=50) class Thing(models.Model): project = models.ForeignKey(Project) reference = models.CharField(max_length=50) class ThingMonth(models.Model): thing = models.ForeignKey(Thing) timestamp = models.DateTimeField() ThingMonthValue = models.FloatField() class Meta: db_table = u'ThingMonthSummary' In a view, I have retrieved a queryset called 'things' which contains 25 Things: things = Thing.objects.select_related().filter(project=1).order_by('reference') I then want to do an aggregate query to get the average ThingMonthValue for the first 20 of those Things for a certain period, and the same value for the last 5. For the first 20 I do: averageThingMonthValue = ThingMonth.objects.filter(turbine__in=things[:20],timestamp__range="2009-01-01 00:00","2010-03-00:00")).aggregate(Avg('ThingMonthValue'))['ThingMonthValue__avg'] This works fine, and returns the desired value. For the last 5 I do: averageThingMonthValue = ThingMonth.objects.filter(turbine__in=things[20:],timestamp__range="2009-01-01 00:00","2010-03-00:00")).aggregate(Avg('ThingMonthValue'))['ThingMonthValue__avg'] But for this I get an SQL error: 'Only one expression can be specified in the select list when the subquery is not introduced with EXISTS.' The SQL query being used by django reads: SELECT AVG([ThingMonthSummary].[ThingMonthValue]) AS [ThingMonthValue__avg] FROM [ThingMonthSummary] WHERE ([ThingMonthSummary].[thing_id] IN (SELECT _row_num, [id] FROM ( SELECT ROW_NUMBER() OVER ( ORDER BY [AAAA].[id] ASC) as _row_num, [AAAA].[id] FROM ( SELECT U0.[id] FROM [Thing] U0 WHERE U0.[project_id] = 1 ) AS [AAAA]) as QQQ where 20 < _row_num) AND [ThingMonthSummary].[timestamp] BETWEEN '01/01/09 00:00:00' and '03/01/10 00:00:00') Any idea why it works for one slice of the Things and not the second? I've checked and the two slices do contain the desired Things correctly.

    Read the article

  • Can someone help me with m Django localization?

    - by alex
    I have a template with has text in it. It's located in /templates under my project directory. I'm trying to do Japanese now. I create a directory called "locale" in my project directory. Then, I set up this in my settings: gettext = lambda s: s LANGUAGES = ( ('de', gettext('German')), ('en', gettext('English')), ('ja', gettext('Japanese')), ) After that, I run this command: django-admin.py makemessages -l ja The only problem is, this doesn't work! In my locale/ja/LC_MESSAGES/django.po: Isn't it supposed to scan my templates with .html extension and grab all the strings? # SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # FIRST AUTHOR <EMAIL@ADDRESS>, YEAR. # #, fuzzy msgid "" msgstr "" "Project-Id-Version: PACKAGE VERSION\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2010-05-20 22:45+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME <EMAIL@ADDRESS>\n" "Language-Team: LANGUAGE <[email protected]>\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" #: settings.py:101 msgid "German" msgstr "" #: settings.py:102 msgid "English" msgstr "" #: settings.py:103 msgid "Japanese" msgstr ""

    Read the article

  • spam and dirty words comment post filtering in python (django)

    - by sintaloo
    Hi All, My basic question is how to filter spam and dirty words in a comment post system under python (django). I have a collection of phrases (approximately 3000 phrases) to be filtered. Question (1), are there any existing open source python (or django) package/module/plugin which can handle this job? I knew there was one called Akismet. But from what I understood, it will not solve my problem. Akismet is just a web service and filter the words dictionary defined by Akismet. But I have my own collection of words. Please correct me if I am wrong. Question (2), If there is no such open source package I can use, how to create my own one? The only thing I can think of it's to use regular expression and join all the word phrases with 'or' in a regular expression. but I have 3000 phrases, I think it won't work in term of performance and filter every comment post. any suggestions where should I start from? Thank you very much for your help and time.

    Read the article

< Previous Page | 55 56 57 58 59 60 61 62 63 64 65 66  | Next Page >