Search Results

Search found 73266 results on 2931 pages for 'django file upload'.

Page 1/2931 | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Django CMS - not able to upload images through cmsplugin_filer_image

    - by Luke
    i have a problem with a local installation on django cms 2.3.3: i've installed it trough pip, in a separated virtualenv. next i followed the tutorial for settings.py configuration, i started the server. Then in the admin i created an page (home), and i've tried to add an image in the placeholder through the cmsplugin_filer_image, but the upload seems that doesn't work. here's my settings.py: # Django settings for cms1 project. # -*- coding: utf-8 -*- import os gettext = lambda s: s PROJECT_PATH = os.path.abspath(os.path.dirname(__file__)) DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', '[email protected]'), ) MANAGERS = ADMINS DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. 'NAME': 'cms1', # Or path to database file if using sqlite3. 'USER': 'cms', # Not used with sqlite3. 'PASSWORD': 'cms', # Not used with sqlite3. 'HOST': '', # Set to empty string for localhost. Not used with sqlite3. 'PORT': '', # Set to empty string for default. Not used with sqlite3. } } # Local time zone for this installation. Choices can be found here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # although not all choices may be available on all operating systems. # In a Windows environment this must be set to your system time zone. TIME_ZONE = 'Europe/Rome' # Language code for this installation. All choices can be found here: # http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE = 'it-it' SITE_ID = 1 # If you set this to False, Django will make some optimizations so as not # to load the internationalization machinery. USE_I18N = True # If you set this to False, Django will not format dates, numbers and # calendars according to the current locale. USE_L10N = True # If you set this to False, Django will not use timezone-aware datetimes. USE_TZ = True # Absolute filesystem path to the directory that will hold user-uploaded files. # Example: "/home/media/media.lawrence.com/media/" MEDIA_ROOT = os.path.join(PROJECT_PATH, "media") # URL that handles the media served from MEDIA_ROOT. Make sure to use a # trailing slash. # Examples: "http://media.lawrence.com/media/", "http://example.com/media/" MEDIA_URL = '/media/' # Absolute path to the directory static files should be collected to. # Don't put anything in this directory yourself; store your static files # in apps' "static/" subdirectories and in STATICFILES_DIRS. # Example: "/home/media/media.lawrence.com/static/" STATIC_ROOT = os.path.join(PROJECT_PATH, "static") STATIC_URL = "/static/" # Additional locations of static files STATICFILES_DIRS = ( os.path.join(PROJECT_PATH, "static_auto"), # Put strings here, like "/home/html/static" or "C:/www/django/static". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. ) # List of finder classes that know how to find static files in # various locations. STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', # 'django.contrib.staticfiles.finders.DefaultStorageFinder', ) # Make this unique, and don't share it with anybody. SECRET_KEY = '^c2q3d8w)f#gk%5i)(#i*lwt%lm-!2=(*1d!1cf+rg&-hqi_9u' # List of callables that know how to import templates from various sources. TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', # 'django.template.loaders.eggs.Loader', ) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'cms.middleware.multilingual.MultilingualURLMiddleware', 'cms.middleware.page.CurrentPageMiddleware', 'cms.middleware.user.CurrentUserMiddleware', 'cms.middleware.toolbar.ToolbarMiddleware', # Uncomment the next line for simple clickjacking protection: # 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) ROOT_URLCONF = 'cms1.urls' # Python dotted path to the WSGI application used by Django's runserver. WSGI_APPLICATION = 'cms1.wsgi.application' TEMPLATE_DIRS = ( os.path.join(PROJECT_PATH, "templates"), # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. ) CMS_TEMPLATES = ( ('template_1.html', 'Template One'), ('template_2.html', 'Template Two'), ) TEMPLATE_CONTEXT_PROCESSORS = ( 'django.contrib.auth.context_processors.auth', 'django.core.context_processors.i18n', 'django.core.context_processors.request', 'django.core.context_processors.media', 'django.core.context_processors.static', 'cms.context_processors.media', 'sekizai.context_processors.sekizai', ) LANGUAGES = [ ('it', 'Italiano'), ('en', 'English'), ] INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'cms', #django CMS itself 'mptt', #utilities for implementing a modified pre-order traversal tree 'menus', #helper for model independent hierarchical website navigation 'south', #intelligent schema and data migrations 'sekizai', #for javascript and css management #'cms.plugins.file', 'cms.plugins.flash', 'cms.plugins.googlemap', 'cms.plugins.link', #'cms.plugins.picture', 'cms.plugins.snippet', 'cms.plugins.teaser', 'cms.plugins.text', #'cms.plugins.video', 'cms.plugins.twitter', 'filer', 'cmsplugin_filer_file', 'cmsplugin_filer_folder', 'cmsplugin_filer_image', 'cmsplugin_filer_teaser', 'cmsplugin_filer_video', 'easy_thumbnails', 'PIL', # Uncomment the next line to enable the admin: 'django.contrib.admin', # Uncomment the next line to enable admin documentation: # 'django.contrib.admindocs', ) # A sample logging configuration. The only tangible logging # performed by this configuration is to send an email to # the site admins on every HTTP 500 error when DEBUG=False. # See http://docs.djangoproject.com/en/dev/topics/logging for # more details on how to customize your logging configuration. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse' } }, 'handlers': { 'mail_admins': { 'level': 'ERROR', 'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler' } }, 'loggers': { 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': True, }, } } when i try to upload an image, in the clipboard section i don't have the thumbnail, but just an 'undefined' message: and this is the runserver console while trying to upload: [20/Oct/2012 15:15:56] "POST /admin/filer/clipboard/operations/upload/?qqfile=29708_1306856312320_7706073_n.jpg HTTP/1.1" 500 248133 [20/Oct/2012 15:15:56] "GET /it/admin/filer/folder/unfiled_images/undefined HTTP/1.1" 301 0 [20/Oct/2012 15:15:56] "GET /it/admin/filer/folder/unfiled_images/undefined/ HTTP/1.1" 404 1739 Also, this is project filesystem: cms1 +-- cms1 ¦   +-- __init__.py ¦   +-- __init__.pyc ¦   +-- media ¦   ¦   +-- filer_public ¦   ¦   +-- 2012 ¦   ¦   +-- 10 ¦   ¦   +-- 20 ¦   ¦   +-- 29708_1306856312320_7706073_n_1.jpg ¦   ¦   +-- 29708_1306856312320_7706073_n_2.jpg ¦   ¦   +-- 29708_1306856312320_7706073_n_3.jpg ¦   ¦   +-- 29708_1306856312320_7706073_n_4.jpg ¦   ¦   +-- 29708_1306856312320_7706073_n_5.jpg ¦   ¦   +-- 29708_1306856312320_7706073_n_6.jpg ¦   ¦   +-- 29708_1306856312320_7706073_n_7.jpg ¦   ¦   +-- 29708_1306856312320_7706073_n.jpg ¦   ¦   +-- torrent-client-macosx.jpg ¦   +-- settings.py ¦   +-- settings.pyc ¦   +-- static ¦   +-- static_auto ¦   +-- static_manual ¦   +-- templates ¦   ¦   +-- base.html ¦   ¦   +-- template_1.html ¦   ¦   +-- template_2.html ¦   +-- urls.py ¦   +-- urls.pyc ¦   +-- wsgi.py ¦   +-- wsgi.pyc +-- manage.py So files are uploaded, but they are not accessible to cms. there's a similar question here, but doens't help me so much. It would be very helpful any help on this issue to me. Thanks, luke

    Read the article

  • django: failing tests from django.contrib.auth

    - by gruszczy
    When I run my django test I get following errors, that are outside of my test suite: ====================================================================== ERROR: test_known_user (django.contrib.auth.tests.remote_user.RemoteUserCustomTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/usr/lib/pymodules/python2.6/django/contrib/auth/tests/remote_user.py", line 160, in test_known_user super(RemoteUserCustomTest, self).test_known_user() File "/usr/lib/pymodules/python2.6/django/contrib/auth/tests/remote_user.py", line 67, in test_known_user self.assertEqual(response.context['user'].username, 'knownuser') TypeError: 'NoneType' object is unsubscriptable ====================================================================== ERROR: test_last_login (django.contrib.auth.tests.remote_user.RemoteUserCustomTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/usr/lib/pymodules/python2.6/django/contrib/auth/tests/remote_user.py", line 87, in test_last_login self.assertNotEqual(default_login, response.context['user'].last_login) TypeError: 'NoneType' object is unsubscriptable ====================================================================== ERROR: test_no_remote_user (django.contrib.auth.tests.remote_user.RemoteUserCustomTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/usr/lib/pymodules/python2.6/django/contrib/auth/tests/remote_user.py", line 33, in test_no_remote_user self.assert_(isinstance(response.context['user'], AnonymousUser)) TypeError: 'NoneType' object is unsubscriptable ====================================================================== ERROR: test_unknown_user (django.contrib.auth.tests.remote_user.RemoteUserCustomTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/usr/lib/pymodules/python2.6/django/contrib/auth/tests/remote_user.py", line 168, in test_unknown_user super(RemoteUserCustomTest, self).test_unknown_user() File "/usr/lib/pymodules/python2.6/django/contrib/auth/tests/remote_user.py", line 51, in test_unknown_user self.assertEqual(response.context['user'].username, 'newuser') TypeError: 'NoneType' object is unsubscriptable ====================================================================== ERROR: test_known_user (django.contrib.auth.tests.remote_user.RemoteUserNoCreateTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/usr/lib/pymodules/python2.6/django/contrib/auth/tests/remote_user.py", line 67, in test_known_user self.assertEqual(response.context['user'].username, 'knownuser') TypeError: 'NoneType' object is unsubscriptable ====================================================================== ERROR: test_last_login (django.contrib.auth.tests.remote_user.RemoteUserNoCreateTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/usr/lib/pymodules/python2.6/django/contrib/auth/tests/remote_user.py", line 87, in test_last_login self.assertNotEqual(default_login, response.context['user'].last_login) TypeError: 'NoneType' object is unsubscriptable ====================================================================== ERROR: test_no_remote_user (django.contrib.auth.tests.remote_user.RemoteUserNoCreateTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/usr/lib/pymodules/python2.6/django/contrib/auth/tests/remote_user.py", line 33, in test_no_remote_user self.assert_(isinstance(response.context['user'], AnonymousUser)) TypeError: 'NoneType' object is unsubscriptable ====================================================================== ERROR: test_unknown_user (django.contrib.auth.tests.remote_user.RemoteUserNoCreateTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/usr/lib/pymodules/python2.6/django/contrib/auth/tests/remote_user.py", line 118, in test_unknown_user self.assert_(isinstance(response.context['user'], AnonymousUser)) TypeError: 'NoneType' object is unsubscriptable ====================================================================== ERROR: test_known_user (django.contrib.auth.tests.remote_user.RemoteUserTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/usr/lib/pymodules/python2.6/django/contrib/auth/tests/remote_user.py", line 67, in test_known_user self.assertEqual(response.context['user'].username, 'knownuser') TypeError: 'NoneType' object is unsubscriptable ====================================================================== ERROR: test_last_login (django.contrib.auth.tests.remote_user.RemoteUserTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/usr/lib/pymodules/python2.6/django/contrib/auth/tests/remote_user.py", line 87, in test_last_login self.assertNotEqual(default_login, response.context['user'].last_login) TypeError: 'NoneType' object is unsubscriptable ====================================================================== ERROR: test_no_remote_user (django.contrib.auth.tests.remote_user.RemoteUserTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/usr/lib/pymodules/python2.6/django/contrib/auth/tests/remote_user.py", line 33, in test_no_remote_user self.assert_(isinstance(response.context['user'], AnonymousUser)) TypeError: 'NoneType' object is unsubscriptable ====================================================================== ERROR: test_unknown_user (django.contrib.auth.tests.remote_user.RemoteUserTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/usr/lib/pymodules/python2.6/django/contrib/auth/tests/remote_user.py", line 51, in test_unknown_user self.assertEqual(response.context['user'].username, 'newuser') TypeError: 'NoneType' object is unsubscriptable ====================================================================== FAIL: test_current_site_in_context_after_login (django.contrib.auth.tests.views.LoginTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/usr/lib/pymodules/python2.6/django/contrib/auth/tests/views.py", line 190, in test_current_site_in_context_after_login self.assertEquals(response.status_code, 200) AssertionError: 302 != 200 Could anyone explain me, what am I doing wrong or what I should set to get those tests pass?

    Read the article

  • Change user email in Django without using django-profiles

    - by mridang
    Hi guys, In my Django application I would like the user to be able to change the email address. I've seen solution of StackOverflow pointing people to django-profiles. Unfortunately I don't want to use a full fledged profile module to accomplish a tiny feat of changing the users email. Has anyone seen this implemented anywhere. The email address verification procedure by sending a confirmation email is a requisite in this scenario. I've spent a great a deal of time trying to a find a solution that works but to no avail. Cheers.

    Read the article

  • Overriding the save() method of a model that uses django-mptt

    - by saturdayplace
    I've been using django-mptt in my project for a while now, it's fabulous. Recently, I've found a need to override a model's save() method that uses mptt, and I'm getting an error when I try to save a new instance of that model: Exception Type: ValueError at /admin/scrivener/page/add/ Exception Value: Cannot use None as a query value I'm assuming that this is a result of the fact that the instance hasn't been stuck into a tree yet, but I'm not sure how to go about fixing this. I added a comment about it onto a similar issue on the project's tracker, but I was hoping that someone here might be able to put me on the right track faster. Here's the traceback. Environment: Request Method: POST Request URL: http://localhost:8000/admin/scrivener/page/add/ Django Version: 1.2 rc 1 SVN-13117 Python Version: 2.6.4 Installed Applications: ['django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.admin', 'django.contrib.sitemaps', 'mptt', 'filebrowser', 'south', 'haystack', 'django_static', 'etc', 'scrivener', 'gregor', 'annunciator'] Installed Middleware: ('django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware') Traceback: File "B:\django-apps\3rd Party Source\django\core\handlers\base.py" in get_response 100. response = callback(request, *callback_args, **callback_kwargs) File "B:\django-apps\3rd Party Source\django\contrib\admin\options.py" in wrapper 239. return self.admin_site.admin_view(view)(*args, **kwargs) File "B:\django-apps\3rd Party Source\django\utils\decorators.py" in _wrapped_view 74. response = view_func(request, *args, **kwargs) File "B:\django-apps\3rd Party Source\django\views\decorators\cache.py" in _wrapped_view_func 69. response = view_func(request, *args, **kwargs) File "B:\django-apps\3rd Party Source\django\contrib\admin\sites.py" in inner 190. return view(request, *args, **kwargs) File "B:\django-apps\3rd Party Source\django\utils\decorators.py" in _wrapper 21. return decorator(bound_func)(*args, **kwargs) File "B:\django-apps\3rd Party Source\django\utils\decorators.py" in _wrapped_view 74. response = view_func(request, *args, **kwargs) File "B:\django-apps\3rd Party Source\django\utils\decorators.py" in bound_func 17. return func(self, *args2, **kwargs2) File "B:\django-apps\3rd Party Source\django\db\transaction.py" in _commit_on_success 299. res = func(*args, **kw) File "B:\django-apps\3rd Party Source\django\contrib\admin\options.py" in add_view 795. self.save_model(request, new_object, form, change=False) File "B:\django-apps\3rd Party Source\django\contrib\admin\options.py" in save_model 597. obj.save() File "B:\django-apps\scrivener\models.py" in save 205. self.url = self.get_absolute_url() File "B:\django-apps\3rd Party Source\django\utils\functional.py" in _curried 55. return _curried_func(*(args+moreargs), **dict(kwargs, **morekwargs)) File "B:\django-apps\3rd Party Source\django\db\models\base.py" in get_absolute_url 940. return settings.ABSOLUTE_URL_OVERRIDES.get('%s.%s' % (opts.app_label, opts.module_name), func)(self, *args, **kwargs) File "B:\django-apps\3rd Party Source\django\db\models\__init__.py" in inner 31. bits = func(*args, **kwargs) File "B:\django-apps\scrivener\models.py" in get_absolute_url 194. for ancestor in self.get_ancestors(): File "B:\django-apps\3rd Party Source\mptt\models.py" in get_ancestors 23. opts.tree_id_attr: getattr(self, opts.tree_id_attr), File "B:\django-apps\3rd Party Source\django\db\models\manager.py" in filter 141. return self.get_query_set().filter(*args, **kwargs) File "B:\django-apps\3rd Party Source\django\db\models\query.py" in filter 550. return self._filter_or_exclude(False, *args, **kwargs) File "B:\django-apps\3rd Party Source\django\db\models\query.py" in _filter_or_exclude 568. clone.query.add_q(Q(*args, **kwargs)) File "B:\django-apps\3rd Party Source\django\db\models\sql\query.py" in add_q 1131. can_reuse=used_aliases) File "B:\django-apps\3rd Party Source\django\db\models\sql\query.py" in add_filter 1000. raise ValueError("Cannot use None as a query value") Exception Type: ValueError at /admin/scrivener/page/add/ Exception Value: Cannot use None as a query value

    Read the article

  • Where is meta.local_fields set in django.db.models.base.py ?

    - by BryanWheelock
    I'm getting the error: Exception Value: (1110, "Column 'about' specified twice") As I was reviewing the Django error page, I noticed that the customizations the model User, seem to be appended to the List twice. This seems to be happening here in django/db/model/base.py in base_save(): values = [(f, f.get_db_prep_save(raw and getattr(self, f.attname) or f.pre_save(self, True))) for f in meta.local_fields] this is what Django error page shows values to be: values = [(<django.db.models.fields.CharField object at 0xa78996c>, u'kallie'), (<django.db.models.fields.CharField object at 0xa7899cc>, ''), (<django.db.models.fields.CharField object at 0xa789a2c>, ''), (<django.db.models.fields.EmailField object at 0xa789a8c>, u'[email protected]'), (<django.db.models.fields.CharField object at 0xa789b2c>, 'sha1$d4a80$0e5xxxxxxxxxxxxxxxxxxxxddadfb07'), (<django.db.models.fields.BooleanField object at 0xa789bcc>, False), (<django.db.models.fields.BooleanField object at 0xa789c6c>, True), (<django.db.models.fields.BooleanField object at 0xa789d2c>, False), (<django.db.models.fields.DateTimeField object at 0xa789dcc>, u'2010-02-03 14:54:35'), (<django.db.models.fields.DateTimeField object at 0xa789e2c>, u'2010-02-03 14:54:35'), # this is where the values from the User model customizations show up (<django.db.models.fields.BooleanField object at 0xa8c69ac>, False), (<django.db.models.fields.CharField object at 0xa8c688c>, None), (<django.db.models.fields.PositiveIntegerField object at 0xa8c69cc>, 1), (<django.db.models.fields.CharField object at 0xa8c69ec>, 'b5ab1603b2308xxxxxxxxxxx75bca1'), (<django.db.models.fields.SmallIntegerField object at 0xa8c6dac>, 0), (<django.db.models.fields.SmallIntegerField object at 0xa8c6e4c>, 0), (<django.db.models.fields.SmallIntegerField object at 0xa8c6e8c>, 0), (<django.db.models.fields.SmallIntegerField object at 0xa8c6ecc>, 10), (<django.db.models.fields.DateTimeField object at 0xa8c6eec>, u'2010-02-03 14:54:35'), (<django.db.models.fields.CharField object at 0xa8c6f2c>, ''), (<django.db.models.fields.URLField object at 0xa8c6f6c>, ''), (<django.db.models.fields.CharField object at 0xa8c6fac>, ''), (<django.db.models.fields.DateField object at 0xa8c6fec>, None), (<django.db.models.fields.TextField object at 0xa8cb04c>, ''), # at this point User model customizations repeats itself (<django.db.models.fields.BooleanField object at 0xa663b0c>, False), (<django.db.models.fields.CharField object at 0xaa1e94c>, None), (<django.db.models.fields.PositiveIntegerField object at 0xaa1e34c>, 1), (<django.db.models.fields.CharField object at 0xaa1e40c>, 'b5ab1603b2308050ebd62f49ca75bca1'), (<django.db.models.fields.SmallIntegerField object at 0xa8c6d8c>, 0), (<django.db.models.fields.SmallIntegerField object at 0xaa2378c>, 0), (<django.db.models.fields.SmallIntegerField object at 0xaa237ac>, 0), (<django.db.models.fields.SmallIntegerField object at 0xaa237ec>, 10), (<django.db.models.fields.DateTimeField object at 0xaa2380c>, u'2010-02-03 14:54:35'), (<django.db.models.fields.CharField object at 0xaa2384c>, ''), (<django.db.models.fields.URLField object at 0xaa2388c>, ''), (<django.db.models.fields.CharField object at 0xaa238cc>, ''), (<django.db.models.fields.DateField object at 0xaa2390c>, None), (<django.db.models.fields.TextField object at 0xaa2394c>, '')] Since this app is in Production, I can't figure out how to use pdb.set_trace() to see what's going on inside of save_base. The customizations to User are: User.add_to_class('email_isvalid', models.BooleanField(default=False)) User.add_to_class('email_key', models.CharField(max_length=16, null=True)) User.add_to_class('reputation', models.PositiveIntegerField(default=1)) User.add_to_class('gravatar', models.CharField(max_length=32)) User.add_to_class('email_feeds', generic.GenericRelation(EmailFeed)) User.add_to_class('favorite_questions', models.ManyToManyField(Question, through=FavoriteQuestion, related_name='favorited_by')) User.add_to_class('badges', models.ManyToManyField(Badge, through=Award, related_name='awarded_to')) User.add_to_class('gold', models.SmallIntegerField(default=0)) User.add_to_class('silver', models.SmallIntegerField(default=0)) User.add_to_class('bronze', models.SmallIntegerField(default=0)) User.add_to_class('questions_per_page', models.SmallIntegerField(choices=QUESTIONS_PER_PAGE_CHOICES, default=10)) User.add_to_class('last_seen', models.DateTimeField(default=datetime.datetime.now)) User.add_to_class('real_name', models.CharField(max_length=100, blank=True)) User.add_to_class('website', models.URLField(max_length=200, blank=True)) User.add_to_class('location', models.CharField(max_length=100, blank=True)) User.add_to_class('date_of_birth', models.DateField(null=True, blank=True)) User.add_to_class('about', models.TextField(blank=True)) Django1.1.1 Python 2.5

    Read the article

  • NTFS Corruption: Files created in Linux corrupted when Windows Boots

    - by Logan Mayfield
    I'm getting some file loss and corruption on my Win7/Ubuntu 12.04 dual boot setup. I have a large shared NTFS partition. I have my Windows Docs/Music/etc. directories on that file and have the comparable directors in Linux setup as a sym. link. I'm using ntfs-3g on the linux side of things to manage the ntfs partition. The shared partition is on a logical partition along with my Linux /home / and /swap partitions. The ntfs partition is mounted at boot time via fstab with the following options: ntfs-3g users,nls=utf8,locale=en_US.UTF-8,exec,rw The problem seems to be confined to newly created and recently edited files. I have not see data loss or corruption when creating/editing files in Windows and then moving over to Ubuntu. I've been using the sync command aggressively in Ubuntu to try to ensure everything is getting written to the HDD. I do not use hibernate in Windows so I know it's not the usual missing files due to Hibernation problem. I'm not seeing any mount related issues on dmesg. Most recently I had a set of files related to a LaTeX document go bad. Some of them show up in Ubuntu but I am unable to delete them. In the GUI file browser they are given thumbnails associated with files I created on my last boot of Windows. To be more specific: I created a few png files in Windows. The files corrupted by that Windows boot are associated with running PdfLatex on a file and are not image files. However, two of the corrupted files show up with the thumbnail image of one of the previously mentioned png files. The png files are not in the same directory as the latex files but they are both win the Document Folder tree. I've had sucess with using NTFS for shared data in the past and am hoping there's some quirk here I'm missing and it's not just bad luck. On one hand this appears to be some kind of Windows problem as data loss occurs when I boot to Windows after having worked in Ubuntu for a while. However, I'm assuming it's more on the Ubuntu end as it requires the special NTFS drivers. Edit for more info: This is a Lenovo Thinkpad L430. Purchased new in the last month. So it's a fairly fresh install. Many of the files on the shared partition were copied over from a previous NTFS formatted shared partition on another HDD. As requested: here's a sample chkdsk log. Some of the files its mentioning were files that got deleted off the partition while in Ubuntu. Others were created/edited but not deleted. Checking file system on D: Volume dismounted. All opened handles to this volume are now invalid. Volume label is Files. CHKDSK is verifying files (stage 1 of 3)... Attribute record of type 0x80 and instance tag 0x2 is cross linked starting at 0x789f47 for possibly 0x21 clusters. Some clusters occupied by attribute of type 0x80 and instance tag 0x2 in file 0x42 is already in use. Deleting corrupt attribute record (128, "") from file record segment 66. 86496 file records processed. File verification completed. 385 large file records processed. 0 bad file records processed. 0 EA records processed. 0 reparse records processed. CHKDSK is verifying indexes (stage 2 of 3)... Deleted invalid filename Screenshot from 2012-09-09 09:51:27.png (72) in directory 46. The NTFS file name attribute in file 0x48 is incorrect. 53 00 63 00 72 00 65 00 65 00 6e 00 73 00 68 00 S.c.r.e.e.n.s.h. 6f 00 74 00 20 00 66 00 72 00 6f 00 6d 00 20 00 o.t. .f.r.o.m. . 32 00 30 00 31 00 32 00 2d 00 30 00 39 00 2d 00 2.0.1.2.-.0.9.-. 30 00 39 00 20 00 30 00 39 00 3a 00 35 00 31 00 0.9. .0.9.:.5.1. 3a 00 32 00 37 00 2e 00 70 00 6e 00 67 00 0d 00 :.2.7...p.n.g... 00 00 00 00 00 00 90 94 49 1f 5e 00 00 80 d4 00 ......I.^.... File 72 has been orphaned since all its filenames were invalid Windows will recover the file in the orphan recovery phase. Correcting minor file name errors in file 72. Index entry found.000 of index $I30 in file 0x5 points to unused file 0x11. Deleting index entry found.000 in index $I30 of file 5. Index entry found.001 of index $I30 in file 0x5 points to unused file 0x16. Deleting index entry found.001 in index $I30 of file 5. Index entry found.002 of index $I30 in file 0x5 points to unused file 0x15. Deleting index entry found.002 in index $I30 of file 5. Index entry DOWNLO~1 of index $I30 in file 0x28 points to unused file 0x2b6. Deleting index entry DOWNLO~1 in index $I30 of file 40. Unable to locate the file name attribute of index entry Screenshot from 2012-09-09 09:51:27.png of index $I30 with parent 0x2e in file 0x48. Deleting index entry Screenshot from 2012-09-09 09:51:27.png in index $I30 of file 46. An index entry of index $I30 in file 0x32 points to file 0x151e8 which is beyond the MFT. Deleting index entry latexsheet.tex in index $I30 of file 50. An index entry of index $I30 in file 0x58bc points to file 0x151eb which is beyond the MFT. Deleting index entry D8CZ82PK in index $I30 of file 22716. An index entry of index $I30 in file 0x58bc points to file 0x151f7 which is beyond the MFT. Deleting index entry EGA4QEAX in index $I30 of file 22716. An index entry of index $I30 in file 0x58bc points to file 0x151e9 which is beyond the MFT. Deleting index entry NGTB469M in index $I30 of file 22716. An index entry of index $I30 in file 0x58bc points to file 0x151fb which is beyond the MFT. Deleting index entry WU5RKXAB in index $I30 of file 22716. Index entry comp220-lab3.synctex.gz of index $I30 in file 0xda69 points to unused file 0xd098. Deleting index entry comp220-lab3.synctex.gz in index $I30 of file 55913. Unable to locate the file name attribute of index entry comp220-numberGrammars.aux of index $I30 with parent 0xda69 in file 0xa276. Deleting index entry comp220-numberGrammars.aux in index $I30 of file 55913. The file reference 0x500000000cd43 of index entry comp220-numberGrammars.out of index $I30 with parent 0xda69 is not the same as 0x600000000cd43. Deleting index entry comp220-numberGrammars.out in index $I30 of file 55913. The file reference 0x500000000cd45 of index entry comp220-numberGrammars.pdf of index $I30 with parent 0xda69 is not the same as 0xc00000000cd45. Deleting index entry comp220-numberGrammars.pdf in index $I30 of file 55913. An index entry of index $I30 in file 0xda69 points to file 0x15290 which is beyond the MFT. Deleting index entry gram.aux in index $I30 of file 55913. An index entry of index $I30 in file 0xda69 points to file 0x15291 which is beyond the MFT. Deleting index entry gram.out in index $I30 of file 55913. An index entry of index $I30 in file 0xda69 points to file 0x15292 which is beyond the MFT. Deleting index entry gram.pdf in index $I30 of file 55913. Unable to locate the file name attribute of index entry comp230-quiz1.synctex.gz of index $I30 with parent 0xda6f in file 0xd183. Deleting index entry comp230-quiz1.synctex.gz in index $I30 of file 55919. An index entry of index $I30 in file 0xf3cc points to file 0x15283 which is beyond the MFT. Deleting index entry require-transform.rkt in index $I30 of file 62412. An index entry of index $I30 in file 0xf3cc points to file 0x15284 which is beyond the MFT. Deleting index entry set.rkt in index $I30 of file 62412. An index entry of index $I30 in file 0xf497 points to file 0x15280 which is beyond the MFT. Deleting index entry logger.rkt in index $I30 of file 62615. An index entry of index $I30 in file 0xf497 points to file 0x15281 which is beyond the MFT. Deleting index entry misc.rkt in index $I30 of file 62615. An index entry of index $I30 in file 0xf497 points to file 0x15282 which is beyond the MFT. Deleting index entry more-scheme.rkt in index $I30 of file 62615. An index entry of index $I30 in file 0xf5bf points to file 0x15285 which is beyond the MFT. Deleting index entry core-layout.rkt in index $I30 of file 62911. An index entry of index $I30 in file 0xf5e0 points to file 0x15286 which is beyond the MFT. Deleting index entry ref.scrbl in index $I30 of file 62944. An index entry of index $I30 in file 0xf6f0 points to file 0x15287 which is beyond the MFT. Deleting index entry base-render.rkt in index $I30 of file 63216. An index entry of index $I30 in file 0xf6f0 points to file 0x15288 which is beyond the MFT. Deleting index entry html-properties.rkt in index $I30 of file 63216. An index entry of index $I30 in file 0xf6f0 points to file 0x15289 which is beyond the MFT. Deleting index entry html-render.rkt in index $I30 of file 63216. An index entry of index $I30 in file 0xf6f0 points to file 0x1528b which is beyond the MFT. Deleting index entry latex-prefix.rkt in index $I30 of file 63216. An index entry of index $I30 in file 0xf6f0 points to file 0x1528c which is beyond the MFT. Deleting index entry latex-render.rkt in index $I30 of file 63216. An index entry of index $I30 in file 0xf6f0 points to file 0x1528e which is beyond the MFT. Deleting index entry scribble.tex in index $I30 of file 63216. An index entry of index $I30 in file 0xf717 points to file 0x1528a which is beyond the MFT. Deleting index entry lang.rkt in index $I30 of file 63255. An index entry of index $I30 in file 0xf721 points to file 0x1528d which is beyond the MFT. Deleting index entry lang.rkt in index $I30 of file 63265. An index entry of index $I30 in file 0xf764 points to file 0x1528f which is beyond the MFT. Deleting index entry lang.rkt in index $I30 of file 63332. An index entry of index $I30 in file 0x14261 points to file 0x15270 which is beyond the MFT. Deleting index entry fddff3ae9ae2221207f144821d475c08ec3d05 in index $I30 of file 82529. An index entry of index $I30 in file 0x14621 points to file 0x15268 which is beyond the MFT. Deleting index entry FETCH_HEAD in index $I30 of file 83489. An index entry of index $I30 in file 0x14650 points to file 0x15272 which is beyond the MFT. Deleting index entry 86 in index $I30 of file 83536. An index entry of index $I30 in file 0x14651 points to file 0x15266 which is beyond the MFT. Deleting index entry pack-7f54ce9f8218d2cd8d6815b8c07461b50584027f.idx in index $I30 of file 83537. An index entry of index $I30 in file 0x14651 points to file 0x15265 which is beyond the MFT. Deleting index entry pack-7f54ce9f8218d2cd8d6815b8c07461b50584027f.pack in index $I30 of file 83537. An index entry of index $I30 in file 0x146f1 points to file 0x15275 which is beyond the MFT. Deleting index entry master in index $I30 of file 83697. An index entry of index $I30 in file 0x146f6 points to file 0x15276 which is beyond the MFT. Deleting index entry remotes in index $I30 of file 83702. An index entry of index $I30 in file 0x1477d points to file 0x15278 which is beyond the MFT. Deleting index entry pad.rkt in index $I30 of file 83837. An index entry of index $I30 in file 0x14797 points to file 0x1527c which is beyond the MFT. Deleting index entry pad1.rkt in index $I30 of file 83863. An index entry of index $I30 in file 0x14810 points to file 0x1527d which is beyond the MFT. Deleting index entry cm.rkt in index $I30 of file 83984. An index entry of index $I30 in file 0x14926 points to file 0x1527e which is beyond the MFT. Deleting index entry multi-file-search.rkt in index $I30 of file 84262. An index entry of index $I30 in file 0x149ef points to file 0x1527f which is beyond the MFT. Deleting index entry com.rkt in index $I30 of file 84463. An index entry of index $I30 in file 0x14b47 points to file 0x15202 which is beyond the MFT. Deleting index entry COMMIT_EDITMSG in index $I30 of file 84807. An index entry of index $I30 in file 0x14b47 points to file 0x15279 which is beyond the MFT. Deleting index entry index in index $I30 of file 84807. An index entry of index $I30 in file 0x14b4c points to file 0x15274 which is beyond the MFT. Deleting index entry master in index $I30 of file 84812. An index entry of index $I30 in file 0x14b61 points to file 0x1520b which is beyond the MFT. Deleting index entry 02 in index $I30 of file 84833. An index entry of index $I30 in file 0x14b61 points to file 0x1525a which is beyond the MFT. Deleting index entry 28 in index $I30 of file 84833. An index entry of index $I30 in file 0x14b61 points to file 0x15208 which is beyond the MFT. Deleting index entry 29 in index $I30 of file 84833. An index entry of index $I30 in file 0x14b61 points to file 0x1521f which is beyond the MFT. Deleting index entry 2c in index $I30 of file 84833. An index entry of index $I30 in file 0x14b61 points to file 0x15261 which is beyond the MFT. Deleting index entry 2e in index $I30 of file 84833. An index entry of index $I30 in file 0x14b61 points to file 0x151f0 which is beyond the MFT. Deleting index entry 45 in index $I30 of file 84833. An index entry of index $I30 in file 0x14b61 points to file 0x1523e which is beyond the MFT. Deleting index entry 47 in index $I30 of file 84833. An index entry of index $I30 in file 0x14b61 points to file 0x151e5 which is beyond the MFT. Deleting index entry 49 in index $I30 of file 84833. An index entry of index $I30 in file 0x14b61 points to file 0x15214 which is beyond the MFT. Deleting index entry 58 in index $I30 of file 84833. Index entry 6e of index $I30 in file 0x14b61 points to unused file 0xd182. Deleting index entry 6e in index $I30 of file 84833. Unable to locate the file name attribute of index entry a0 of index $I30 with parent 0x14b61 in file 0xd29c. Deleting index entry a0 in index $I30 of file 84833. An index entry of index $I30 in file 0x14b61 points to file 0x1521b which is beyond the MFT. Deleting index entry cd in index $I30 of file 84833. An index entry of index $I30 in file 0x14b61 points to file 0x15249 which is beyond the MFT. Deleting index entry d6 in index $I30 of file 84833. An index entry of index $I30 in file 0x14b61 points to file 0x15242 which is beyond the MFT. Deleting index entry df in index $I30 of file 84833. An index entry of index $I30 in file 0x14b61 points to file 0x15227 which is beyond the MFT. Deleting index entry ea in index $I30 of file 84833. An index entry of index $I30 in file 0x14b61 points to file 0x1522e which is beyond the MFT. Deleting index entry f3 in index $I30 of file 84833. An index entry of index $I30 in file 0x14b61 points to file 0x151f2 which is beyond the MFT. Deleting index entry ff in index $I30 of file 84833. An index entry of index $I30 in file 0x14b62 points to file 0x15254 which is beyond the MFT. Deleting index entry 1ed39b36ad4bd48c91d22cbafd7390f1ea38da in index $I30 of file 84834. An index entry of index $I30 in file 0x14b75 points to file 0x15224 which is beyond the MFT. Deleting index entry 96260247010fe9811fea773c08c5f3a314df3f in index $I30 of file 84853. An index entry of index $I30 in file 0x14b79 points to file 0x15219 which is beyond the MFT. Deleting index entry 8f689724ca23528dd4f4ab8b475ace6edcb8f5 in index $I30 of file 84857. An index entry of index $I30 in file 0x14b7c points to file 0x15223 which is beyond the MFT. Deleting index entry 1df17cf850656be42c947cba6295d29c248d94 in index $I30 of file 84860. An index entry of index $I30 in file 0x14b7c points to file 0x15217 which is beyond the MFT. Deleting index entry 31db8a3c72a3e44769bbd8db58d36f8298242c in index $I30 of file 84860. An index entry of index $I30 in file 0x14b7c points to file 0x15267 which is beyond the MFT. Deleting index entry 8e1254d755ff1882d61c07011272bac3612f57 in index $I30 of file 84860. An index entry of index $I30 in file 0x14b82 points to file 0x15246 which is beyond the MFT. Deleting index entry f959bfaf9643c1b9e78d5ecf8f669133efdbf3 in index $I30 of file 84866. An index entry of index $I30 in file 0x14b88 points to file 0x151fe which is beyond the MFT. Deleting index entry 7e9aa15b1196b2c60116afa4ffa613397f2185 in index $I30 of file 84872. An index entry of index $I30 in file 0x14b8a points to file 0x151ea which is beyond the MFT. Deleting index entry 73cb0cd248e494bb508f41b55d862e84cdd6e0 in index $I30 of file 84874. An index entry of index $I30 in file 0x14b8e points to file 0x15264 which is beyond the MFT. Deleting index entry bd555d9f0383cc14c317120149e9376a8094c4 in index $I30 of file 84878. An index entry of index $I30 in file 0x14b96 points to file 0x15212 which is beyond the MFT. Deleting index entry 630dba40562d991bc6cbb6fed4ba638542e9c5 in index $I30 of file 84886. An index entry of index $I30 in file 0x14b99 points to file 0x151ec which is beyond the MFT. Deleting index entry 478be31ca8e538769246e22bba3330d81dc3c8 in index $I30 of file 84889. An index entry of index $I30 in file 0x14b99 points to file 0x15258 which is beyond the MFT. Deleting index entry 66c60c0a0f3253bc9a5112697e4cbb0dfc0c78 in index $I30 of file 84889. An index entry of index $I30 in file 0x14b9c points to file 0x15238 which is beyond the MFT. Deleting index entry 1c7ceeddc2953496f9ffbfc0b6fb28846e3fe3 in index $I30 of file 84892. An index entry of index $I30 in file 0x14b9c points to file 0x15247 which is beyond the MFT. Deleting index entry ae6e32ffc49d897d8f8aeced970a90d3653533 in index $I30 of file 84892. An index entry of index $I30 in file 0x14ba0 points to file 0x15233 which is beyond the MFT. Deleting index entry f71c7d874e45179a32e138b49bf007e5bbf514 in index $I30 of file 84896. Index entry 2e04fefbd794f050d45e7a717d009e39204431 of index $I30 in file 0x14ba7 points to unused file 0xd097. Deleting index entry 2e04fefbd794f050d45e7a717d009e39204431 in index $I30 of file 84903. An index entry of index $I30 in file 0x14baa points to file 0x15241 which is beyond the MFT. Deleting index entry 0dda7dec1c635cd646dfef308e403c2843d5dc in index $I30 of file 84906. An index entry of index $I30 in file 0x14baa points to file 0x151fc which is beyond the MFT. Deleting index entry 98151e654dd546edcfdec630bc82d90619ac8e in index $I30 of file 84906. An index entry of index $I30 in file 0x14bb1 points to file 0x151e9 which is beyond the MFT. Deleting index entry 1997c5be62ffeebc99253cced7608415e38e4e in index $I30 of file 84913. An index entry of index $I30 in file 0x14bb1 points to file 0x1521d which is beyond the MFT. Deleting index entry 6bf3aedefd3ac62d9c49cad72d05e8c0ad242c in index $I30 of file 84913. An index entry of index $I30 in file 0x14bb1 points to file 0x151f4 which is beyond the MFT. Deleting index entry 907b755afdca14c00be0010962d0861af29264 in index $I30 of file 84913. An index entry of index $I30 in file 0x14bb3 points to file 0x15218 which is beyond the MFT. Deleting index entry

    Read the article

  • sort django queryset by latest instance of a subset of related model

    - by rsp
    I have an Order model and order_event model. Each order_event has a foreignkey to order. so from an order instance i can get: myorder.order_event_set. I want to get a list of all orders but i want them to be sorted by the date of the last event. A statement like this works to sort by the latest event date: queryset = Order.objects.all().annotate(latest_event_date=Max('order_event__event_datetime')).order_by('latest_event_date') However, what I really need is a list of all orders sorted by latest date of A SUBSET OF EVENTS. For example my events are categorized into "scheduling", "processing", etc. So I should be able to get a list of all orders sorted by the latest scheduling event. This django doc (https://docs.djangoproject.com/en/dev/topics/db/aggregation/#filter-and-exclude) shows how I can get the latest schedule event using a filter but this excludes orders without a scheduling event. I thought I could combine the filtered queryset with a queryset that includes back those orders that are missing a scheduling event...but I'm not quite sure how to do this. I saw answers related to using python list but it would be much more useful to have a proper django queryset (ie for a view with pagination, etc.)

    Read the article

  • Django-admin.py not working (-bash:django-admin.py: command not found)

    - by Diego
    I'm having trouble getting django-admin.py to work... it's in this first location: /Users/mycomp/bin/ but I think I need it in another location for the terminal to recognize it, no? Noob, Please help. Thanks!! my-computer:~/Django-1.1.1 mycomp$ sudo ln -s /Users/mycomp/bin/django-admin.py /Users/mycomp/django-1.1.1/django-admin.py Password: ln: /Users/mycomp/django-1.1.1/django-admin.py: File exists my-computer:~/Django-1.1.1 mycomp$ django-admin.py --version -bash: django-admin.py: command not found

    Read the article

  • Django 1.2 + South 0.7 + django-annoying's AutoOneToOneField leads to TypeError: 'LegacyConnection'

    - by konrad
    I'm using Django 1.2 trunk with South 0.7 and an AutoOneToOneField copied from django-annoying. South complained that the field does not have rules defined and the new version of South no longer has an automatic field type parser. So I read the South documentation and wrote the following definition (basically an exact copy of the OneToOneField rules): rules = [ ( (AutoOneToOneField), [], { "to": ["rel.to", {}], "to_field": ["rel.field_name", {"default_attr": "rel.to._meta.pk.name"}], "related_name": ["rel.related_name", {"default": None}], "db_index": ["db_index", {"default": True}], }, ) ] from south.modelsinspector import add_introspection_rules add_introspection_rules(rules, ["^myapp"]) Now South raises the following error when I do a schemamigration. Traceback (most recent call last): File "manage.py", line 11, in <module> execute_manager(settings) File "django/core/management/__init__.py", line 438, in execute_manager utility.execute() File "django/core/management/__init__.py", line 379, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "django/core/management/base.py", line 196, in run_from_argv self.execute(*args, **options.__dict__) File "django/core/management/base.py", line 223, in execute output = self.handle(*args, **options) File "South-0.7-py2.6.egg/south/management/commands/schemamigration.py", line 92, in handle (k, v) for k, v in freezer.freeze_apps([migrations.app_label()]).items() File "South-0.7-py2.6.egg/south/creator/freezer.py", line 33, in freeze_apps model_defs[model_key(model)] = prep_for_freeze(model) File "South-0.7-py2.6.egg/south/creator/freezer.py", line 65, in prep_for_freeze fields = modelsinspector.get_model_fields(model, m2m=True) File "South-0.7-py2.6.egg/south/modelsinspector.py", line 322, in get_model_fields args, kwargs = introspector(field) File "South-0.7-py2.6.egg/south/modelsinspector.py", line 271, in introspector arg_defs, kwarg_defs = matching_details(field) File "South-0.7-py2.6.egg/south/modelsinspector.py", line 187, in matching_details if any([isinstance(field, x) for x in classes]): TypeError: 'LegacyConnection' object is not iterable Is this related to a recent change in Django 1.2 trunk? How do I fix this? I use this field as follows: class Bar(models.Model): foo = AutoOneToOneField("foo.Foo", primary_key=True, related_name="bar") For reference the field code from django-tagging: class AutoSingleRelatedObjectDescriptor(SingleRelatedObjectDescriptor): def __get__(self, instance, instance_type=None): try: return super(AutoSingleRelatedObjectDescriptor, self).__get__(instance, instance_type) except self.related.model.DoesNotExist: obj = self.related.model(**{self.related.field.name: instance}) obj.save() return obj class AutoOneToOneField(OneToOneField): def contribute_to_related_class(self, cls, related): setattr(cls, related.get_accessor_name(), AutoSingleRelatedObjectDescriptor(related))

    Read the article

  • Django - How best to handle ValidationErrors after form.save(commit=False)

    - by orokusaki
    This is a fragment of my code from a view: if form.is_valid(): instance = form.save(commit=False) try: instance.account = request.account instance.full_clean() except ValidationError, e: # Do something with the errors here... I don't know what the best thing to do here is, but I certainly don't want to do it 180 times. This is an utter mess. Who would want to handle validation errors manually in every view. If you're not modifying the instance after save(commit=False), you don't have to worry about this, but what about in my case where every model has a foreign key to account which is set behind the scenes and hidden from the user? Any help is really appreciated.

    Read the article

  • django: error while migrating from 1.1 to 1.2

    - by gruszczy
    I am trying to migrate our django project from 1.1 to 1.2, but I get following error: Traceback (most recent call last): File "./manage.py", line 11, in <module> execute_manager(settings) File "/usr/local/lib/python2.6/dist-packages/django/core/management/__init__.py", line 438, in execute_manager utility.execute() File "/usr/local/lib/python2.6/dist-packages/django/core/management/__init__.py", line 379, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python2.6/dist-packages/django/core/management/base.py", line 191, in run_from_argv self.execute(*args, **options.__dict__) File "/usr/local/lib/python2.6/dist-packages/django/core/management/base.py", line 209, in execute translation.activate('en-us') File "/usr/local/lib/python2.6/dist-packages/django/utils/translation/__init__.py", line 66, in activate return real_activate(language) File "/usr/local/lib/python2.6/dist-packages/django/utils/functional.py", line 55, in _curried return _curried_func(*(args+moreargs), **dict(kwargs, **morekwargs)) File "/usr/local/lib/python2.6/dist-packages/django/utils/translation/__init__.py", line 36, in delayed_loader return getattr(trans, real_name)(*args, **kwargs) File "/usr/local/lib/python2.6/dist-packages/django/utils/translation/trans_real.py", line 193, in activate _active[currentThread()] = translation(language) File "/usr/local/lib/python2.6/dist-packages/django/utils/translation/trans_real.py", line 176, in translation default_translation = _fetch(settings.LANGUAGE_CODE) File "/usr/local/lib/python2.6/dist-packages/django/utils/translation/trans_real.py", line 159, in _fetch app = import_module(appname) File "/usr/local/lib/python2.6/dist-packages/django/utils/importlib.py", line 35, in import_module __import__(name) File "/home/gruszczy/Programy/bozorth/../bozorth/notifications/__init__.py", line 2, in <module> from django.db.models.signals import post_save File "/usr/local/lib/python2.6/dist-packages/django/db/__init__.py", line 75, in <module> connection = connections[DEFAULT_DB_ALIAS] File "/usr/local/lib/python2.6/dist-packages/django/db/utils.py", line 92, in __getitem__ conn = backend.DatabaseWrapper(db, alias) File "/usr/local/lib/python2.6/dist-packages/django/db/backends/sqlite3/base.py", line 154, in __init__ super(DatabaseWrapper, self).__init__(*args, **kwargs) TypeError: __init__() takes exactly 2 arguments (3 given) Anyone encountered this problem and know, how to solve?

    Read the article

  • Can't set up image upload in Django

    - by culebrón
    I can't understand what's not working here: 1) settings MEDIA_ROOT = '/var/www/satel/media' MEDIA_URL = 'http://media.satel.culebron' ADMIN_MEDIA_PREFIX = '/media/' 2) models class Photo(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length = 200) desc = models.TextField(max_length = 1000) img = models.ImageField(upload_to = 'upload') 3) access rights: drwxr-xrwx 3 culebron culebron 4.0K 2010-04-14 21:13 media drwxr-xrwx 2 culebron culebron 4.0K 2010-04-14 19:04 upload 4) SQL: CREATE TABLE "photos_photo" ( "id" integer NOT NULL PRIMARY KEY, "name" varchar(200) NOT NULL, "desc" text NOT NULL, "img" varchar(100) NOT NULL ); 4) run Django test server as myself. 5) result: SuspiciousOperation at /admin/photos/author/add/ Attempted access to '/var/www/satel/upload/OpenStreetMap.png' denied. Not a PIL & jpeg issue, seems not to be access rights issue. But what's wrong?

    Read the article

  • How do I upgrade django on ubuntu 9.04?

    - by Lorin Hochstein
    I've got Django 1.0.2 installed on Ubuntu 9.04. I'd like to upgrade Django, because I have an app that needs Django 1.1 or greater. I tried using pip to do the upgrade, but got the following: $ sudo pip install Django==1.1 Downloading/unpacking Django==1.1 Downloading Django-1.1.tar.gz (5.6Mb): 5.6Mb downloaded Running setup.py egg_info for package Django Installing collected packages: Django Found existing installation: Django 1.0.2-final Not uninstalling Django at /var/lib/python-support/python2.6, outside environment /usr Running setup.py install for Django changing mode of build/scripts-2.6/django-admin.py from 644 to 755 changing mode of /usr/local/bin/django-admin.py to 755 Successfully installed Django It seems like it worked, but it refuses to remove the original Django 1.02, and sure enough: $ pip freeze | grep -i django Django==1.0.2-final django-debug-toolbar==0.8.3 django-sphinx==2.2.3 $ /usr/local/bin/django-admin.py --version 1.0.2 final The problem, apparently, is that pip won't uninstall files outside of /usr. I'd like to remove the existing Django files manually, but I have no idea how to do that, because I'm unfamiliar with how Python packages are laid out in Ubuntu. It looks pretty complicated. The site-packages directory is: $ python -c "from distutils.sysconfig import get_python_lib; print get_python_lib()" /usr/lib/python2.6/dist-packages However, that's not where the django files live: $ ls -ld /usr/lib/python2.6/dist-packages/[Dd]jango* ls: cannot access /usr/lib/python2.6/dist-packages/[Dd]jango*: No such file or directory There's a /var/lib/python-support/python2.6/django directory, and the __init__.py file in that directory points to /usr/share/python-support/python-django/django/__init__.py. Clearly, pip is able to figure out where the files live. Is there any way to retrieve the list of files associated with the django package so I can just delete them manually?

    Read the article

  • Upload Image with Django Model Form

    - by jmitchel3
    I'm having difficulty uploading the following model with model form. I can upload fine in the admin but that's not all that useful for a project that limits admin access. #Models.py class Profile(models.Model): name = models.CharField(max_length=128) user = models.ForeignKey(User) profile_pic = models.ImageField(upload_to='img/profile/%Y/%m/') #views.py def create_profile(request): try: profile = Profile.objects.get(user=request.user) except: pass form = CreateProfileForm(request.POST or None, instance=profile) if form.is_valid(): new = form.save(commit=False) new.user = request.user new.save() return render_to_response('profile.html', locals(), context_instance=RequestContext(request)) #Profile.html <form enctype="multipart/form-data" method="post">{% csrf_token %} <tr><td>{{ form.as_p }}</td></tr> <tr><td><button type="submit" class="btn">Submit</button></td></tr> </form> Note: All the other data in the form saves perfectly well, the photo does not upload at all. Thank you for your help!

    Read the article

  • why are read only form fields in django a bad idea?

    - by jamida
    I've been looking for a way to create a read-only form field and every article I've found on the subject comes with a statement that "this is a bad idea". Now for an individual form, I can understand that there are other ways to solve the problem, but using a read only form field in a modelformset seems like a completely natural idea. Consider a teacher grade book application where the teacher would like to be able to enter all the students' (note the plural students) grades with a single SUBMIT. A modelformset could iterate over all the student-grades in such a way that the student name is read-only and the grade is the editable field. I like the power and convenience of the error checking and error reporting you get with a modelformset but leaving the student name editable in such a formset is crazy. Since the expert django consensus is that read-only form fields are a bad idea, I was wondering what the standard django best practice is for the example student-grade example above?

    Read the article

  • Customizing Django form widgets? - Django

    - by RadiantHex
    Hi folks, I'm having a little problem here! I have discovered the following as being the globally accepted method for customizing Django admin field. from django import forms from django.utils.safestring import mark_safe class AdminImageWidget(forms.FileInput): """ A ImageField Widget for admin that shows a thumbnail. """ def __init__(self, attrs={}): super(AdminImageWidget, self).__init__(attrs) def render(self, name, value, attrs=None): output = [] if value and hasattr(value, "url"): output.append(('<a target="_blank" href="%s">' '<img src="%s" style="height: 28px;" /></a> ' % (value.url, value.url))) output.append(super(AdminImageWidget, self).render(name, value, attrs)) return mark_safe(u''.join(output)) I need to have access to other field of the model in order to decide how to display the field! For example: If I am keeping track of a value, let us call it "sales". If I wish to customize how sales is displayed depending on another field, let us call it "conversion rate". I have no obvious way of accessing the conversion rate field when overriding the sales widget! Any ideas to work around this would be highly appreciated! Thanks :)

    Read the article

  • Django not recognizing django admin urls

    - by colorfulgrayscale
    I just registered my models my models with django admin. I navigate to the django admin at /admin. I log in sucessfully and I can see all my models. great so far. But now if I try to click one of the links, for Ex: 'users', django gives me a 404 saying The current URL, admin/auth/user/, didn't match any of these. Its really weird because in my urls.py I have it mapped correctly (r'^admin/', include(admin.site.urls)), I have all the required middleware enabled and have these in my installed apps 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.admin', anyone have any idea? Thanks.

    Read the article

  • Django automatically compress Model Field on save() and decompress when field is accessed

    - by Brian M. Hunt
    Given a Django model likeso: from django.db import models class MyModel(models.Model): textfield = models.TextField() How can one automatically compress textfield (e.g. with zlib) on save() and decompress it when the property textfield is accessed (i.e. not on load), with a workflow like this: m = MyModel() textfield = "Hello, world, how are you?" m.save() # compress textfield on save m.textfield # no decompression id = m.id() m = MyModel.get(pk=id) # textfield still compressed m.textfield # textfield decompressed I'd be inclined to think that you would overload MyModel.save, but I don't know the pattern for in-place modification of the element when saving. I also don't know the best way in Django to decompress when the field when it's accessed (overload __getattr__?). Or would a better way to do this be to have a custom field type? I'm certain I've seen an example of almost exactly this, but alas I've not been able to find it recently. Thank you for reading – and for any input you may be able to provide.

    Read the article

  • Django cannot find my templatetags, even though it's in INSTALLED_APPS and has a __init__.py

    - by Vivian Short
    I just installed django-compress (http://code.google.com/p/django-compress) into /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/compress. I added 'compress' to INSTALLED_APPS. In my template file, I wrote {% load compressed %}. I got the error: 'compressed' is not a valid tag library: Could not load template library from django.templatetags.compressed, No module named compressed I verified that there is an init.py in compress, as well as in compress/templatetags/. I tried putting the compress directory into PYTHONPATH. I ran python and wrote "import compress" and that worked. Your suggestions would be very appreciated! What else can I try?

    Read the article

  • Proper way to add record to many to many relationship in Django

    - by blcArmadillo
    First off, I'm planning on running my project on google app engine so I'm using djangoappengine which as far as I know doesn't support django's ManyToManyField type. Because of this I've setup my models like this: from django.db import models from django.contrib.auth.models import User class Group(models.Model): name = models.CharField(max_length=200) class UserGroup(models.Model): user = models.ForeignKey(User) group = models.ForeignKey(Group) On a page I have a form field where people can enter a group name. I want the results from this form field to create a UserGroup object for the user - group combination and if the group doesn't yet exist create a new Group object. At first I started putting this logic in the UserGroup class with a add_group method but quickly realized that it doesn't really make sense to put this in the UserGroup class. What would the proper way of doing this be? I saw some stuff about model managers. Is this what those are for?

    Read the article

  • Upload File to Windows Azure Blob in Chunks through ASP.NET MVC, JavaScript and HTML5

    - by Shaun
    Originally posted on: http://geekswithblogs.net/shaunxu/archive/2013/07/01/upload-file-to-windows-azure-blob-in-chunks-through-asp.net.aspxMany people are using Windows Azure Blob Storage to store their data in the cloud. Blob storage provides 99.9% availability with easy-to-use API through .NET SDK and HTTP REST. For example, we can store JavaScript files, images, documents in blob storage when we are building an ASP.NET web application on a Web Role in Windows Azure. Or we can store our VHD files in blob and mount it as a hard drive in our cloud service. If you are familiar with Windows Azure, you should know that there are two kinds of blob: page blob and block blob. The page blob is optimized for random read and write, which is very useful when you need to store VHD files. The block blob is optimized for sequential/chunk read and write, which has more common usage. Since we can upload block blob in blocks through BlockBlob.PutBlock, and them commit them as a whole blob with invoking the BlockBlob.PutBlockList, it is very powerful to upload large files, as we can upload blocks in parallel, and provide pause-resume feature. There are many documents, articles and blog posts described on how to upload a block blob. Most of them are focus on the server side, which means when you had received a big file, stream or binaries, how to upload them into blob storage in blocks through .NET SDK.  But the problem is, how can we upload these large files from client side, for example, a browser. This questioned to me when I was working with a Chinese customer to help them build a network disk production on top of azure. The end users upload their files from the web portal, and then the files will be stored in blob storage from the Web Role. My goal is to find the best way to transform the file from client (end user’s machine) to the server (Web Role) through browser. In this post I will demonstrate and describe what I had done, to upload large file in chunks with high speed, and save them as blocks into Windows Azure Blob Storage.   Traditional Upload, Works with Limitation The simplest way to implement this requirement is to create a web page with a form that contains a file input element and a submit button. 1: @using (Html.BeginForm("About", "Index", FormMethod.Post, new { enctype = "multipart/form-data" })) 2: { 3: <input type="file" name="file" /> 4: <input type="submit" value="upload" /> 5: } And then in the backend controller, we retrieve the whole content of this file and upload it in to the blob storage through .NET SDK. We can split the file in blocks and upload them in parallel and commit. The code had been well blogged in the community. 1: [HttpPost] 2: public ActionResult About(HttpPostedFileBase file) 3: { 4: var container = _client.GetContainerReference("test"); 5: container.CreateIfNotExists(); 6: var blob = container.GetBlockBlobReference(file.FileName); 7: var blockDataList = new Dictionary<string, byte[]>(); 8: using (var stream = file.InputStream) 9: { 10: var blockSizeInKB = 1024; 11: var offset = 0; 12: var index = 0; 13: while (offset < stream.Length) 14: { 15: var readLength = Math.Min(1024 * blockSizeInKB, (int)stream.Length - offset); 16: var blockData = new byte[readLength]; 17: offset += stream.Read(blockData, 0, readLength); 18: blockDataList.Add(Convert.ToBase64String(BitConverter.GetBytes(index)), blockData); 19:  20: index++; 21: } 22: } 23:  24: Parallel.ForEach(blockDataList, (bi) => 25: { 26: blob.PutBlock(bi.Key, new MemoryStream(bi.Value), null); 27: }); 28: blob.PutBlockList(blockDataList.Select(b => b.Key).ToArray()); 29:  30: return RedirectToAction("About"); 31: } This works perfect if we selected an image, a music or a small video to upload. But if I selected a large file, let’s say a 6GB HD-movie, after upload for about few minutes the page will be shown as below and the upload will be terminated. In ASP.NET there is a limitation of request length and the maximized request length is defined in the web.config file. It’s a number which less than about 4GB. So if we want to upload a really big file, we cannot simply implement in this way. Also, in Windows Azure, a cloud service network load balancer will terminate the connection if exceed the timeout period. From my test the timeout looks like 2 - 3 minutes. Hence, when we need to upload a large file we cannot just use the basic HTML elements. Besides the limitation mentioned above, the simple HTML file upload cannot provide rich upload experience such as chunk upload, pause and pause-resume. So we need to find a better way to upload large file from the client to the server.   Upload in Chunks through HTML5 and JavaScript In order to break those limitation mentioned above we will try to upload the large file in chunks. This takes some benefit to us such as - No request size limitation: Since we upload in chunks, we can define the request size for each chunks regardless how big the entire file is. - No timeout problem: The size of chunks are controlled by us, which means we should be able to make sure request for each chunk upload will not exceed the timeout period of both ASP.NET and Windows Azure load balancer. It was a big challenge to upload big file in chunks until we have HTML5. There are some new features and improvements introduced in HTML5 and we will use them to implement our solution.   In HTML5, the File interface had been improved with a new method called “slice”. It can be used to read part of the file by specifying the start byte index and the end byte index. For example if the entire file was 1024 bytes, file.slice(512, 768) will read the part of this file from the 512nd byte to 768th byte, and return a new object of interface called "Blob”, which you can treat as an array of bytes. In fact,  a Blob object represents a file-like object of immutable, raw data. The File interface is based on Blob, inheriting blob functionality and expanding it to support files on the user's system. For more information about the Blob please refer here. File and Blob is very useful to implement the chunk upload. We will use File interface to represent the file the user selected from the browser and then use File.slice to read the file in chunks in the size we wanted. For example, if we wanted to upload a 10MB file with 512KB chunks, then we can read it in 512KB blobs by using File.slice in a loop.   Assuming we have a web page as below. User can select a file, an input box to specify the block size in KB and a button to start upload. 1: <div> 2: <input type="file" id="upload_files" name="files[]" /><br /> 3: Block Size: <input type="number" id="block_size" value="512" name="block_size" />KB<br /> 4: <input type="button" id="upload_button_blob" name="upload" value="upload (blob)" /> 5: </div> Then we can have the JavaScript function to upload the file in chunks when user clicked the button. 1: <script type="text/javascript"> 1: 2: $(function () { 3: $("#upload_button_blob").click(function () { 4: }); 5: });</script> Firstly we need to ensure the client browser supports the interfaces we are going to use. Just try to invoke the File, Blob and FormData from the “window” object. If any of them is “undefined” the condition result will be “false” which means your browser doesn’t support these premium feature and it’s time for you to get your browser updated. FormData is another new feature we are going to use in the future. It could generate a temporary form for us. We will use this interface to create a form with chunk and associated metadata when invoked the service through ajax. 1: $("#upload_button_blob").click(function () { 2: // assert the browser support html5 3: if (window.File && window.Blob && window.FormData) { 4: alert("Your brwoser is awesome, let's rock!"); 5: } 6: else { 7: alert("Oh man plz update to a modern browser before try is cool stuff out."); 8: return; 9: } 10: }); Each browser supports these interfaces by their own implementation and currently the Blob, File and File.slice are supported by Chrome 21, FireFox 13, IE 10, Opera 12 and Safari 5.1 or higher. After that we worked on the files the user selected one by one since in HTML5, user can select multiple files in one file input box. 1: var files = $("#upload_files")[0].files; 2: for (var i = 0; i < files.length; i++) { 3: var file = files[i]; 4: var fileSize = file.size; 5: var fileName = file.name; 6: } Next, we calculated the start index and end index for each chunks based on the size the user specified from the browser. We put them into an array with the file name and the index, which will be used when we upload chunks into Windows Azure Blob Storage as blocks since we need to specify the target blob name and the block index. At the same time we will store the list of all indexes into another variant which will be used to commit blocks into blob in Azure Storage once all chunks had been uploaded successfully. 1: $("#upload_button_blob").click(function () { 2: // assert the browser support html5 3: ... ... 4: // start to upload each files in chunks 5: var files = $("#upload_files")[0].files; 6: for (var i = 0; i < files.length; i++) { 7: var file = files[i]; 8: var fileSize = file.size; 9: var fileName = file.name; 10:  11: // calculate the start and end byte index for each blocks(chunks) 12: // with the index, file name and index list for future using 13: var blockSizeInKB = $("#block_size").val(); 14: var blockSize = blockSizeInKB * 1024; 15: var blocks = []; 16: var offset = 0; 17: var index = 0; 18: var list = ""; 19: while (offset < fileSize) { 20: var start = offset; 21: var end = Math.min(offset + blockSize, fileSize); 22:  23: blocks.push({ 24: name: fileName, 25: index: index, 26: start: start, 27: end: end 28: }); 29: list += index + ","; 30:  31: offset = end; 32: index++; 33: } 34: } 35: }); Now we have all chunks’ information ready. The next step should be upload them one by one to the server side, and at the server side when received a chunk it will upload as a block into Blob Storage, and finally commit them with the index list through BlockBlobClient.PutBlockList. But since all these invokes are ajax calling, which means not synchronized call. So we need to introduce a new JavaScript library to help us coordinate the asynchronize operation, which named “async.js”. You can download this JavaScript library here, and you can find the document here. I will not explain this library too much in this post. We will put all procedures we want to execute as a function array, and pass into the proper function defined in async.js to let it help us to control the execution sequence, in series or in parallel. Hence we will define an array and put the function for chunk upload into this array. 1: $("#upload_button_blob").click(function () { 2: // assert the browser support html5 3: ... ... 4:  5: // start to upload each files in chunks 6: var files = $("#upload_files")[0].files; 7: for (var i = 0; i < files.length; i++) { 8: var file = files[i]; 9: var fileSize = file.size; 10: var fileName = file.name; 11: // calculate the start and end byte index for each blocks(chunks) 12: // with the index, file name and index list for future using 13: ... ... 14:  15: // define the function array and push all chunk upload operation into this array 16: blocks.forEach(function (block) { 17: putBlocks.push(function (callback) { 18: }); 19: }); 20: } 21: }); 22: }); As you can see, I used File.slice method to read each chunks based on the start and end byte index we calculated previously, and constructed a temporary HTML form with the file name, chunk index and chunk data through another new feature in HTML5 named FormData. Then post this form to the backend server through jQuery.ajax. This is the key part of our solution. 1: $("#upload_button_blob").click(function () { 2: // assert the browser support html5 3: ... ... 4: // start to upload each files in chunks 5: var files = $("#upload_files")[0].files; 6: for (var i = 0; i < files.length; i++) { 7: var file = files[i]; 8: var fileSize = file.size; 9: var fileName = file.name; 10: // calculate the start and end byte index for each blocks(chunks) 11: // with the index, file name and index list for future using 12: ... ... 13: // define the function array and push all chunk upload operation into this array 14: blocks.forEach(function (block) { 15: putBlocks.push(function (callback) { 16: // load blob based on the start and end index for each chunks 17: var blob = file.slice(block.start, block.end); 18: // put the file name, index and blob into a temporary from 19: var fd = new FormData(); 20: fd.append("name", block.name); 21: fd.append("index", block.index); 22: fd.append("file", blob); 23: // post the form to backend service (asp.net mvc controller action) 24: $.ajax({ 25: url: "/Home/UploadInFormData", 26: data: fd, 27: processData: false, 28: contentType: "multipart/form-data", 29: type: "POST", 30: success: function (result) { 31: if (!result.success) { 32: alert(result.error); 33: } 34: callback(null, block.index); 35: } 36: }); 37: }); 38: }); 39: } 40: }); Then we will invoke these functions one by one by using the async.js. And once all functions had been executed successfully I invoked another ajax call to the backend service to commit all these chunks (blocks) as the blob in Windows Azure Storage. 1: $("#upload_button_blob").click(function () { 2: // assert the browser support html5 3: ... ... 4: // start to upload each files in chunks 5: var files = $("#upload_files")[0].files; 6: for (var i = 0; i < files.length; i++) { 7: var file = files[i]; 8: var fileSize = file.size; 9: var fileName = file.name; 10: // calculate the start and end byte index for each blocks(chunks) 11: // with the index, file name and index list for future using 12: ... ... 13: // define the function array and push all chunk upload operation into this array 14: ... ... 15: // invoke the functions one by one 16: // then invoke the commit ajax call to put blocks into blob in azure storage 17: async.series(putBlocks, function (error, result) { 18: var data = { 19: name: fileName, 20: list: list 21: }; 22: $.post("/Home/Commit", data, function (result) { 23: if (!result.success) { 24: alert(result.error); 25: } 26: else { 27: alert("done!"); 28: } 29: }); 30: }); 31: } 32: }); That’s all in the client side. The outline of our logic would be - Calculate the start and end byte index for each chunks based on the block size. - Defined the functions of reading the chunk form file and upload the content to the backend service through ajax. - Execute the functions defined in previous step with “async.js”. - Commit the chunks by invoking the backend service in Windows Azure Storage finally.   Save Chunks as Blocks into Blob Storage In above we finished the client size JavaScript code. It uploaded the file in chunks to the backend service which we are going to implement in this step. We will use ASP.NET MVC as our backend service, and it will receive the chunks, upload into Windows Azure Bob Storage in blocks, then finally commit as one blob. As in the client side we uploaded chunks by invoking the ajax call to the URL "/Home/UploadInFormData", I created a new action under the Index controller and it only accepts HTTP POST request. 1: [HttpPost] 2: public JsonResult UploadInFormData() 3: { 4: var error = string.Empty; 5: try 6: { 7: } 8: catch (Exception e) 9: { 10: error = e.ToString(); 11: } 12:  13: return new JsonResult() 14: { 15: Data = new 16: { 17: success = string.IsNullOrWhiteSpace(error), 18: error = error 19: } 20: }; 21: } Then I retrieved the file name, index and the chunk content from the Request.Form object, which was passed from our client side. And then, used the Windows Azure SDK to create a blob container (in this case we will use the container named “test”.) and create a blob reference with the blob name (same as the file name). Then uploaded the chunk as a block of this blob with the index, since in Blob Storage each block must have an index (ID) associated with so that finally we can put all blocks as one blob by specifying their block ID list. 1: [HttpPost] 2: public JsonResult UploadInFormData() 3: { 4: var error = string.Empty; 5: try 6: { 7: var name = Request.Form["name"]; 8: var index = int.Parse(Request.Form["index"]); 9: var file = Request.Files[0]; 10: var id = Convert.ToBase64String(BitConverter.GetBytes(index)); 11:  12: var container = _client.GetContainerReference("test"); 13: container.CreateIfNotExists(); 14: var blob = container.GetBlockBlobReference(name); 15: blob.PutBlock(id, file.InputStream, null); 16: } 17: catch (Exception e) 18: { 19: error = e.ToString(); 20: } 21:  22: return new JsonResult() 23: { 24: Data = new 25: { 26: success = string.IsNullOrWhiteSpace(error), 27: error = error 28: } 29: }; 30: } Next, I created another action to commit the blocks into blob once all chunks had been uploaded. Similarly, I retrieved the blob name from the Request.Form. I also retrieved the chunks ID list, which is the block ID list from the Request.Form in a string format, split them as a list, then invoked the BlockBlob.PutBlockList method. After that our blob will be shown in the container and ready to be download. 1: [HttpPost] 2: public JsonResult Commit() 3: { 4: var error = string.Empty; 5: try 6: { 7: var name = Request.Form["name"]; 8: var list = Request.Form["list"]; 9: var ids = list 10: .Split(',') 11: .Where(id => !string.IsNullOrWhiteSpace(id)) 12: .Select(id => Convert.ToBase64String(BitConverter.GetBytes(int.Parse(id)))) 13: .ToArray(); 14:  15: var container = _client.GetContainerReference("test"); 16: container.CreateIfNotExists(); 17: var blob = container.GetBlockBlobReference(name); 18: blob.PutBlockList(ids); 19: } 20: catch (Exception e) 21: { 22: error = e.ToString(); 23: } 24:  25: return new JsonResult() 26: { 27: Data = new 28: { 29: success = string.IsNullOrWhiteSpace(error), 30: error = error 31: } 32: }; 33: } Now we finished all code we need. The whole process of uploading would be like this below. Below is the full client side JavaScript code. 1: <script type="text/javascript" src="~/Scripts/async.js"></script> 2: <script type="text/javascript"> 3: $(function () { 4: $("#upload_button_blob").click(function () { 5: // assert the browser support html5 6: if (window.File && window.Blob && window.FormData) { 7: alert("Your brwoser is awesome, let's rock!"); 8: } 9: else { 10: alert("Oh man plz update to a modern browser before try is cool stuff out."); 11: return; 12: } 13:  14: // start to upload each files in chunks 15: var files = $("#upload_files")[0].files; 16: for (var i = 0; i < files.length; i++) { 17: var file = files[i]; 18: var fileSize = file.size; 19: var fileName = file.name; 20:  21: // calculate the start and end byte index for each blocks(chunks) 22: // with the index, file name and index list for future using 23: var blockSizeInKB = $("#block_size").val(); 24: var blockSize = blockSizeInKB * 1024; 25: var blocks = []; 26: var offset = 0; 27: var index = 0; 28: var list = ""; 29: while (offset < fileSize) { 30: var start = offset; 31: var end = Math.min(offset + blockSize, fileSize); 32:  33: blocks.push({ 34: name: fileName, 35: index: index, 36: start: start, 37: end: end 38: }); 39: list += index + ","; 40:  41: offset = end; 42: index++; 43: } 44:  45: // define the function array and push all chunk upload operation into this array 46: var putBlocks = []; 47: blocks.forEach(function (block) { 48: putBlocks.push(function (callback) { 49: // load blob based on the start and end index for each chunks 50: var blob = file.slice(block.start, block.end); 51: // put the file name, index and blob into a temporary from 52: var fd = new FormData(); 53: fd.append("name", block.name); 54: fd.append("index", block.index); 55: fd.append("file", blob); 56: // post the form to backend service (asp.net mvc controller action) 57: $.ajax({ 58: url: "/Home/UploadInFormData", 59: data: fd, 60: processData: false, 61: contentType: "multipart/form-data", 62: type: "POST", 63: success: function (result) { 64: if (!result.success) { 65: alert(result.error); 66: } 67: callback(null, block.index); 68: } 69: }); 70: }); 71: }); 72:  73: // invoke the functions one by one 74: // then invoke the commit ajax call to put blocks into blob in azure storage 75: async.series(putBlocks, function (error, result) { 76: var data = { 77: name: fileName, 78: list: list 79: }; 80: $.post("/Home/Commit", data, function (result) { 81: if (!result.success) { 82: alert(result.error); 83: } 84: else { 85: alert("done!"); 86: } 87: }); 88: }); 89: } 90: }); 91: }); 92: </script> And below is the full ASP.NET MVC controller code. 1: public class HomeController : Controller 2: { 3: private CloudStorageAccount _account; 4: private CloudBlobClient _client; 5:  6: public HomeController() 7: : base() 8: { 9: _account = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("DataConnectionString")); 10: _client = _account.CreateCloudBlobClient(); 11: } 12:  13: public ActionResult Index() 14: { 15: ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application."; 16:  17: return View(); 18: } 19:  20: [HttpPost] 21: public JsonResult UploadInFormData() 22: { 23: var error = string.Empty; 24: try 25: { 26: var name = Request.Form["name"]; 27: var index = int.Parse(Request.Form["index"]); 28: var file = Request.Files[0]; 29: var id = Convert.ToBase64String(BitConverter.GetBytes(index)); 30:  31: var container = _client.GetContainerReference("test"); 32: container.CreateIfNotExists(); 33: var blob = container.GetBlockBlobReference(name); 34: blob.PutBlock(id, file.InputStream, null); 35: } 36: catch (Exception e) 37: { 38: error = e.ToString(); 39: } 40:  41: return new JsonResult() 42: { 43: Data = new 44: { 45: success = string.IsNullOrWhiteSpace(error), 46: error = error 47: } 48: }; 49: } 50:  51: [HttpPost] 52: public JsonResult Commit() 53: { 54: var error = string.Empty; 55: try 56: { 57: var name = Request.Form["name"]; 58: var list = Request.Form["list"]; 59: var ids = list 60: .Split(',') 61: .Where(id => !string.IsNullOrWhiteSpace(id)) 62: .Select(id => Convert.ToBase64String(BitConverter.GetBytes(int.Parse(id)))) 63: .ToArray(); 64:  65: var container = _client.GetContainerReference("test"); 66: container.CreateIfNotExists(); 67: var blob = container.GetBlockBlobReference(name); 68: blob.PutBlockList(ids); 69: } 70: catch (Exception e) 71: { 72: error = e.ToString(); 73: } 74:  75: return new JsonResult() 76: { 77: Data = new 78: { 79: success = string.IsNullOrWhiteSpace(error), 80: error = error 81: } 82: }; 83: } 84: } And if we selected a file from the browser we will see our application will upload chunks in the size we specified to the server through ajax call in background, and then commit all chunks in one blob. Then we can find the blob in our Windows Azure Blob Storage.   Optimized by Parallel Upload In previous example we just uploaded our file in chunks. This solved the problem that ASP.NET MVC request content size limitation as well as the Windows Azure load balancer timeout. But it might introduce the performance problem since we uploaded chunks in sequence. In order to improve the upload performance we could modify our client side code a bit to make the upload operation invoked in parallel. The good news is that, “async.js” library provides the parallel execution function. If you remembered the code we invoke the service to upload chunks, it utilized “async.series” which means all functions will be executed in sequence. Now we will change this code to “async.parallel”. This will invoke all functions in parallel. 1: $("#upload_button_blob").click(function () { 2: // assert the browser support html5 3: ... ... 4: // start to upload each files in chunks 5: var files = $("#upload_files")[0].files; 6: for (var i = 0; i < files.length; i++) { 7: var file = files[i]; 8: var fileSize = file.size; 9: var fileName = file.name; 10: // calculate the start and end byte index for each blocks(chunks) 11: // with the index, file name and index list for future using 12: ... ... 13: // define the function array and push all chunk upload operation into this array 14: ... ... 15: // invoke the functions one by one 16: // then invoke the commit ajax call to put blocks into blob in azure storage 17: async.parallel(putBlocks, function (error, result) { 18: var data = { 19: name: fileName, 20: list: list 21: }; 22: $.post("/Home/Commit", data, function (result) { 23: if (!result.success) { 24: alert(result.error); 25: } 26: else { 27: alert("done!"); 28: } 29: }); 30: }); 31: } 32: }); In this way all chunks will be uploaded to the server side at the same time to maximize the bandwidth usage. This should work if the file was not very large and the chunk size was not very small. But for large file this might introduce another problem that too many ajax calls are sent to the server at the same time. So the best solution should be, upload the chunks in parallel with maximum concurrency limitation. The code below specified the concurrency limitation to 4, which means at the most only 4 ajax calls could be invoked at the same time. 1: $("#upload_button_blob").click(function () { 2: // assert the browser support html5 3: ... ... 4: // start to upload each files in chunks 5: var files = $("#upload_files")[0].files; 6: for (var i = 0; i < files.length; i++) { 7: var file = files[i]; 8: var fileSize = file.size; 9: var fileName = file.name; 10: // calculate the start and end byte index for each blocks(chunks) 11: // with the index, file name and index list for future using 12: ... ... 13: // define the function array and push all chunk upload operation into this array 14: ... ... 15: // invoke the functions one by one 16: // then invoke the commit ajax call to put blocks into blob in azure storage 17: async.parallelLimit(putBlocks, 4, function (error, result) { 18: var data = { 19: name: fileName, 20: list: list 21: }; 22: $.post("/Home/Commit", data, function (result) { 23: if (!result.success) { 24: alert(result.error); 25: } 26: else { 27: alert("done!"); 28: } 29: }); 30: }); 31: } 32: });   Summary In this post we discussed how to upload files in chunks to the backend service and then upload them into Windows Azure Blob Storage in blocks. We focused on the frontend side and leverage three new feature introduced in HTML 5 which are - File.slice: Read part of the file by specifying the start and end byte index. - Blob: File-like interface which contains the part of the file content. - FormData: Temporary form element that we can pass the chunk alone with some metadata to the backend service. Then we discussed the performance consideration of chunk uploading. Sequence upload cannot provide maximized upload speed, but the unlimited parallel upload might crash the browser and server if too many chunks. So we finally came up with the solution to upload chunks in parallel with the concurrency limitation. We also demonstrated how to utilize “async.js” JavaScript library to help us control the asynchronize call and the parallel limitation.   Regarding the chunk size and the parallel limitation value there is no “best” value. You need to test vary composition and find out the best one for your particular scenario. It depends on the local bandwidth, client machine cores and the server side (Windows Azure Cloud Service Virtual Machine) cores, memory and bandwidth. Below is one of my performance test result. The client machine was Windows 8 IE 10 with 4 cores. I was using Microsoft Cooperation Network. The web site was hosted on Windows Azure China North data center (in Beijing) with one small web role (1.7GB 1 core CPU, 1.75GB memory with 100Mbps bandwidth). The test cases were - Chunk size: 512KB, 1MB, 2MB, 4MB. - Upload Mode: Sequence, parallel (unlimited), parallel with limit (4 threads, 8 threads). - Chunk Format: base64 string, binaries. - Target file: 100MB. - Each case was tested 3 times. Below is the test result chart. Some thoughts, but not guidance or best practice: - Parallel gets better performance than series. - No significant performance improvement between parallel 4 threads and 8 threads. - Transform with binaries provides better performance than base64. - In all cases, chunk size in 1MB - 2MB gets better performance.   Hope this helps, Shaun All documents and related graphics, codes are provided "AS IS" without warranty of any kind. Copyright © Shaun Ziyan Xu. This work is licensed under the Creative Commons License.

    Read the article

  • *UPDATED* help with django and accented characters?

    - by Asinox
    Hi guys, i have a problem with my accented characters, Django admin save my data without encoding to something like "&aacute;" Example: if im trying a word like " Canción ", i would like to save in this way: Canci&oacute;n, and not Canción. im usign Sociable app: {% load sociable_tags %} {% get_sociable Facebook TwitThis Google MySpace del.icio.us YahooBuzz Live as sociable_links with url=object.get_absolute_url title=object.titulo %} {% for link in sociable_links %} <a href="{{ link.link }}"><img alt="{{ link.site }}" title="{{ link.site }}" src="{{ link.image }}" /></a> {% endfor %} But im getting error if my object.titulo (title of the article) have a accented word. aught KeyError while rendering: u'\xfa' Any idea ? i had in my SETTING: DEFAULT_CHARSET = 'utf-8' i had in my mysql database: utf8_general_ci COMPLETED ERROR: Traceback: File "C:\wamp\bin\Python26\lib\site-packages\django\core\handlers\base.py" in get_response 100. response = callback(request, *callback_args, **callback_kwargs) File "C:\wamp\bin\Python26\lib\site-packages\django\views\generic\date_based.py" in object_detail 366. response = HttpResponse(t.render(c), mimetype=mimetype) File "C:\wamp\bin\Python26\lib\site-packages\django\template\__init__.py" in render 173. return self._render(context) File "C:\wamp\bin\Python26\lib\site-packages\django\template\__init__.py" in _render 167. return self.nodelist.render(context) File "C:\wamp\bin\Python26\lib\site-packages\django\template\__init__.py" in render 796. bits.append(self.render_node(node, context)) File "C:\wamp\bin\Python26\lib\site-packages\django\template\debug.py" in render_node 72. result = node.render(context) File "C:\wamp\bin\Python26\lib\site-packages\django\template\loader_tags.py" in render 125. return compiled_parent._render(context) File "C:\wamp\bin\Python26\lib\site-packages\django\template\__init__.py" in _render 167. return self.nodelist.render(context) File "C:\wamp\bin\Python26\lib\site-packages\django\template\__init__.py" in render 796. bits.append(self.render_node(node, context)) File "C:\wamp\bin\Python26\lib\site-packages\django\template\debug.py" in render_node 72. result = node.render(context) File "C:\wamp\bin\Python26\lib\site-packages\django\template\loader_tags.py" in render 62. result = block.nodelist.render(context) File "C:\wamp\bin\Python26\lib\site-packages\django\template\__init__.py" in render 796. bits.append(self.render_node(node, context)) File "C:\wamp\bin\Python26\lib\site-packages\django\template\debug.py" in render_node 72. result = node.render(context) File "C:\wamp\bin\Python26\lib\site-packages\sociable\templatetags\sociable_tags.py" in render 37. 'link': sociable.genlink(site, **self.values), File "C:\wamp\bin\Python26\lib\site-packages\sociable\sociable.py" in genlink 20. values['title'] = quote_plus(kwargs['title']) File "C:\wamp\bin\Python26\lib\urllib.py" in quote_plus 1228. s = quote(s, safe + ' ') File "C:\wamp\bin\Python26\lib\urllib.py" in quote 1222. res = map(safe_map.__getitem__, s) Exception Type: TemplateSyntaxError at /noticia/2010/jun/10/matan-domingo-paquete-en-la-avenida-san-vicente-de-paul/ Exception Value: Caught KeyError while rendering: u'\xfa' thanks, sorry with my English

    Read the article

  • Numerology with Python And Django

    - by Asinox
    Hi guys, i have a function that give me the result that im expecting in console mode, but if i try to use the function with Django, the page never load and just have a loop calculating and never end. Any idea ? *sorry with my english Console function (WORK GREAT): def sum_digitos(n): sum = 0; while n != 0: sum += n % 10 n /= 10 if sum > 9: x = str(sum) y =list(x) sum = int(y[0]) + int(y[1]) return sum print sum_digitos(2461978) Django views: def Calcular(request): if request.method == 'POST': form = NumerologiaForm(request.POST) if form.is_valid(): sum = 0; ano = str(request.POST['fecha_year']) mes = str(request.POST['fecha_month']) dia = str(request.POST['fecha_day']) data = dia + mes + ano fecha = int(data) while fecha != 0: f = fecha sum += f % 10 f /= 10 if sum > 9: x = str(sum) y =list(x) sum = int(y[0]) + int(y[1]) resultado = get_object_or_404(Numero,numero = sum) return HttpResponseRedirect(resultado.get_absolute_url()) else: form = NumerologiaForm() return render_to_response('numerologiaForm.html',{'form':form})

    Read the article

  • Deploying Django on EC2 using Bitnami Djangostack: WSGI script cannot be loadded

    - by Arman
    I've been struggling to deploy Django application on Amazon EC2 using Bitnami Djangostack for the last couple of days. When I go to http://dewey.io I see the default bitnami page (/opt/bitnami/apache2/htdocs/index.html), however, when I open http://dewey.io/portnoy, I get 'Internal Server Error'. But it's known that if mod_wsgi is setup correctly, the DocumentRoot value from httpd.conf is ignored, thus, I should see my Django application when accessing http://dewey.io. Essentially, the main error is this - 'Target WSGI script cannot be loaded as Python module'. Two questions: 1) any ideas how to fix these mod_wsgi errors (the Apache logs are below)? 2) how to disable the default /opt/bitnami/apache2/htdocs/index.html page and show my homepage from django application when accessing http://dewey.io? Thank you in advance! The details On my EC2 instance I"m running 64-bit Ubuntu 12.04 with DjangoStack 1.4-1. My Django project is located here - /opt/bitnami/apps/django/django_projects/portnoy. root@dewey:/opt/bitnami/apps/django/django_projects/portnoy# ls manage.py README.md settings.py site_media users Procfile sandbox static test.py topics urls.py views.py __init__.pyc templates testviews.py Apache error logs (/opt/bitnami/apache2/logs/error_log): [Wed Jul 04 02:29:00 2012] [error] [client 140.180.6.212] File does not exist: /opt/bitnami/apache2/htdocs/favicon.ico [Wed Jul 04 02:29:15 2012] [error] [client 140.180.6.212] mod_wsgi (pid=3990): Target WSGI script '/opt/bitnami/apps/django/scripts/django.wsgi' cannot be loaded as Python module. [Wed Jul 04 02:29:15 2012] [error] [client 140.180.6.212] mod_wsgi (pid=3990): Exception occurred processing WSGI script '/opt/bitnami/apps/django/scripts/django.wsgi'. [Wed Jul 04 02:29:15 2012] [error] [client 140.180.6.212] Traceback (most recent call last): [Wed Jul 04 02:29:15 2012] [error] [client 140.180.6.212] File "/opt/bitnami/apps/django/scripts/django.wsgi", line 8, in <module> [Wed Jul 04 02:29:15 2012] [error] [client 140.180.6.212] import django.core.handlers.wsgi [Wed Jul 04 02:29:15 2012] [error] [client 140.180.6.212] File "/opt/bitnami/apps/django/lib/python2.7/site-packages/django/core/handlers/wsgi.py", line 8, in <module> [Wed Jul 04 02:29:15 2012] [error] [client 140.180.6.212] from django import http [Wed Jul 04 02:29:15 2012] [error] [client 140.180.6.212] File "/opt/bitnami/apps/django/lib/python2.7/site-packages/django/http/__init__.py", line 119, in <module> [Wed Jul 04 02:29:15 2012] [error] [client 140.180.6.212] from django.http.multipartparser import MultiPartParser [Wed Jul 04 02:29:15 2012] [error] [client 140.180.6.212] File "/opt/bitnami/apps/django/lib/python2.7/site-packages/django/http/multipartparser.py", line 13, in <module> [Wed Jul 04 02:29:15 2012] [error] [client 140.180.6.212] from django.utils.text import unescape_entities [Wed Jul 04 02:29:15 2012] [error] [client 140.180.6.212] File "/opt/bitnami/apps/django/lib/python2.7/site-packages/django/utils/text.py", line 4, in <module> [Wed Jul 04 02:29:15 2012] [error] [client 140.180.6.212] from gzip import GzipFile [Wed Jul 04 02:29:15 2012] [error] [client 140.180.6.212] File "/opt/bitnami/python/lib/python2.7/gzip.py", line 10, in <module> [Wed Jul 04 02:29:15 2012] [error] [client 140.180.6.212] import io [Wed Jul 04 02:29:15 2012] [error] [client 140.180.6.212] File "/opt/bitnami/python/lib/python2.7/io.py", line 60, in <module> [Wed Jul 04 02:29:15 2012] [error] [client 140.180.6.212] import _io [Wed Jul 04 02:29:15 2012] [error] [client 140.180.6.212] ImportError: /opt/bitnami/python/lib/python2.7/lib-dynload/_io.so: undefined symbol: PyUnicodeUCS2_AsEncodedString [Wed Jul 04 02:29:15 2012] [error] [client 140.180.6.212] File does not exist: /opt/bitnami/apache2/htdocs/favicon.ico [Wed Jul 04 02:44:00 2012] [error] [client 140.180.6.212] File does not exist: /opt/bitnami/apache2/htdocs/favicon.ico Let me quickly introduce the contents of the files to make the case more concrete. This is my /etc/apache2/sites-available/default file <VirtualHost *:80> ServerAdmin [email protected] ServerName dewey.io Alias /site_media/ /opt/bitnami/apps/django/django_projects/portnoy/site_media/ Alias /static/ /opt/bitnami/apps/django/lib/python2.7/site-packages/django/contrib/admin/static/ Alias /robots.txt /opt/bitnami/apps/django/django_projects/portnoy/site_media/robots.txt Alias /favicon.ico /opt/bitnami/apps/django/django_projects/portnoy/site_media/favicon.ico CustomLog "|/usr/sbin/rotatelogs /opt/bitnami/apps/django/django_projects/logs/access.log.%Y%m%d-%H%M%S 5M" combined ErrorLog "|/usr/sbin/rotatelogs /opt/bitnami/apps/django/django_projects/logs/error.log.%Y%m%d-%H%M%S 5M" LogLevel warn WSGIProcessGroup dewey.io WSGIScriptAlias / /opt/bitnami/apps/django/scripts/django.wsgi <Directory /opt/bitnami/apps/django/django_projects/portnoy/site_media> Order deny,allow Allow from all Options -Indexes FollowSymLinks </Directory> <Directory /opt/bitnami/apps/django/django_projects/portnoy/conf/apache> Order deny,allow Allow from all </Directory> </VirtualHost> This is my /opt/bitnami/apps/django/scripts/django.wsgi file import os, sys sys.path.append('/opt/bitnami/apps/django/lib/python2.7/site-packages/') sys.path.append('/opt/bitnami/apps/django/django_projects') sys.path.append('/opt/bitnami/apps/django/django_projects/portnoy') os.environ['DJANGO_SETTINGS_MODULE'] = 'portnoy.settings' import django.core.handlers.wsgi application = django.core.handlers.wsgi.WSGIHandler() Here is the relevant portion of /opt/bitnami/apache2/conf/httpd.conf file: ServerRoot "/opt/bitnami/apache2" Listen 80 ServerName dewey.io DocumentRoot "/opt/bitnami/apache2/htdocs" LoadModule wsgi_module modules/mod_wsgi.so WSGIPythonHome /opt/bitnami/python Include "/opt/bitnami/apache2/conf/ssi.conf" Include "/opt/bitnami/apps/django/conf/django.conf" Include "/opt/bitnami/apache2/conf/bitnami/httpd.conf"

    Read the article

  • Return template as string - Django

    - by Ninefingers
    Hi All, I'm still not sure this is the correct way to go about this, maybe not, but I'll ask anyway. I'd like to re-write wordpress (justification: because I can) albeit more simply myself in Django and I'm looking to be able to configure elements in different ways on the page. So for example I might have: Blog models A site update message model A latest comments model. Now, for each page on the site I want the user to be able to choose the order of and any items that go on it. In my thought process, this would work something like: class Page(models.Model) Slug = models.CharField(max_length=100) class PageItem(models.Model) Page = models.ForeignKey(Page) ItemType = models.CharField(max_length=100) InstanceNum = models.IntegerField() # all models have primary keys. Then, ideally, my template would loop through all the PageItems in a page which is easy enough to do. But what if my page item is a site update as opposed to a blog post? Basically, I am thinking I'd like to pull different item types back in different orders and display them using the appropriate templates. Now, I thought one way to do this would be to, in views.py, to loop through all of the objects and call the appropriate view function, return a bit of html as a string and then pipe that into the resultant template. My question is - is this the best way to go about doing things? If so, how do I do it? If not, which way should I be going? I'm pretty new to Django so I'm still learning what it can and can't do, so please bear with me. I've checked SO for dupes and don't think this has been asked before...

    Read the article

1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >