python,django,django-cmsRelated issues-Collection of common programming errors
S.L. Barth
python list
I have two files and the content is as follows:Please only consider the bolded column and the red column. The remaining text is junk and unnecessary. As evident from the two files they are similar in many ways. I am trying to compare the bolded text in file_1 and file_2 (it is not bolded but hope you can make out it is the same column) and if they are different, I want to print out the red text from file_1. I achieved this by the following script:import string import itertoolschain_id=[] for fil
plaes
python openerp
I want to add lines to the object account.bank.statement.line through other object but I get this error: “dictionary update sequence element #0 has length 3; 2 is required”def action_account_line_create(self, cr, uid, ids):res = Falsecash_id = self.pool.get(‘account.bank.statement.line’)for exp in self.browse(cr, uid, ids):company_id = exp.company_id.id#statement_id = exp.statement_id.idlines = []for l in exp.line_ids:lines.append((0, 0, {‘name’: l.name,’date’: l.date,’amount’: l.amount,’type’:
turkishgold
python ms-access pyodbc
I am working on a Python script (Python version 2.5.1 on Windows XP) that involves connecting to a Microsoft Access (.mdb) database to read values from a table. I’m getting some unexpected results with one record whereby the field of interest precision is getting rounded. I know the Access table field of interest is a Double data type. But, the value that caused me to discover this in the table is 1107901035.43948. When I read the value in the Python code and print it out, it’s showing 110790103
Apalala
list zip python slice
Often enough, I’ve found the need to process a list by pairs. I was wondering which would be the pythonic and efficient way to do it, and found this on Google:pairs = zip(t[::2], t[1::2])I thought that was pythonic enough, but after a recent discussion involving idioms versus efficiency, I decided to do some tests:import time from itertools import islice, izipdef pairs_1(t):return zip(t[::2], t[1::2]) def pairs_2(t):return izip(t[::2], t[1::2]) def pairs_3(t):return izip(islice(t,None,None,2), i
Ceasar Bautista
python inheritance tuples
I have a class WeightedArc defined as follows:class Arc(tuple):@propertydef tail(self):return self[0]@propertydef head(self):return self[1]@propertydef inverted(self):return Arc((self.head, self.tail))def __eq__(self, other):return self.head == other.head and self.tail == other.tailclass WeightedArc(Arc):def __new__(cls, arc, weight):self.weight = weightreturn super(Arc, cls).__new__(arc)This code clearly doesn’t work, because self isn’t defined for WeightArc.__new__. How do I assign the attrib
Rosarch
python google-app-engine urlopen
I’m trying to upload data from a CSV to my app using the devserver:appcfg.py upload_data –config_file=”DataLoader.py” –filename=”data.csv” –kind=Foo –url=http://localhost:8083/remote_api “path/to/app”The result:Application: appname; version: 1. Uploading data records. [INFO ] Logging to bulkloader-log-20100626.181045 [INFO ] Throttling transfers: [INFO ] Bandwidth: 250000 bytes/second [INFO ] HTTP connections: 8/second [INFO ] Entities inserted/fetched/modified: 20/second [INF
Gary Fixler
python default mutable
New python users often get tripped up by mutable argument defaults. What are the gotchas and other issues of using this ‘feature’ on purpose, for example, to get tweakable defaults at runtime that continue to display properly in function signatures via help()?class MutableString (str):def __init__ (self, value):self.value = valuedef __str__ (self):return self.valuedef __repr__ (self):return “‘” + self.value + “‘”defaultAnimal = MutableString(‘elephant’)def getAnimal (species=defaultAnimal):’Retu
Jeff Bradberry
python django django-models
How do I have actions occur when a field gets changed in one of my models? In this particular case, I have this model:class Game(models.Model):STATE_CHOICES = ((‘S’, ‘Setup’),(‘A’, ‘Active’),(‘P’, ‘Paused’),(‘F’, ‘Finished’))name = models.CharField(max_length=100)owner = models.ForeignKey(User)created = models.DateTimeField(auto_now_add=True)started = models.DateTimeField(null=True)state = models.CharField(max_length=1, choices=STATE_CHOICES, default=’S’)and I would like to have Units created,
CharlesB
python python-import
Suppose I have a relatively long module, but need an external module or method only once.Is it considered OK to import that method or module in the middle of the module?Or should imports only be in the first part of the module.Example:import string, pythis, pythat … … … … def func():blahblah blahfrom pysomething import foofoo()etcetc etc … … …Please justify your answer and add links to PEPs or relevant sources
Martijn Pieters
python unicode utf-8 latin1
I was reading this high rated post in SO on unicodesHere is an `illustration given there :$ python>>> import sys>>> print sys.stdout.encoding UTF-8>>> print ‘\xe9′ # (1) é >>> print u’\xe9′ # (2) é >>> print u’\xe9’.encode(‘latin-1’) # (3) é >>>and the explanation were given as (1) python outputs binary string as is, terminal receives it and tries to match its value with latin-1 character map. In latin-1, 0xe9 or 233 yields the character “é”
Jeff Bradberry
python django django-models
How do I have actions occur when a field gets changed in one of my models? In this particular case, I have this model:class Game(models.Model):STATE_CHOICES = ((‘S’, ‘Setup’),(‘A’, ‘Active’),(‘P’, ‘Paused’),(‘F’, ‘Finished’))name = models.CharField(max_length=100)owner = models.ForeignKey(User)created = models.DateTimeField(auto_now_add=True)started = models.DateTimeField(null=True)state = models.CharField(max_length=1, choices=STATE_CHOICES, default=’S’)and I would like to have Units created,
Ben Roberts
python django django-admin
Assuming my model looks like this (this is a simplified example): class Person(Model):first_name = CharField(…)last_name = CharField(…)def name():return first_name + ‘ ‘ + last_nameDisplaying the name as a single column in the admin change list is easy enough. However, I need a single, editable “name” field that is editable from the list page, which I can then parse to extract and set the model field values. The parsing isn’t a concern. I am just wondering how to have an editable form field
Gill Bates
python sql django orm bulk
Business: I encountered a problem – when operating with large datasets with Django ORM, canonical way is manipulate with every single element. But of course this way is very inefficient. So I decided to use raw SQL.Substance: I have a basic code which forms SQL query, which updates rows of table, and commiting it:from myapp import Model from django.db import connection, transaction COUNT = Model.objects.count() MYDATA = produce_some_differentiated_data() #Creating individual value for each row c
Terry J
django django-forms django-widget django-fields
I have a multivaluefield with a charfield and choicefield. I need to pass choices to the choicefield constructor, however when I try to pass it into my custom multivaluefield I get an error __init__() got an unexpected keyword argument ‘choices’. I know the rest of the code works because when I remove the choices keyword argument from __init__ and super, the multivaluefield displays correctly but without any choices.This is how I setup my custom multivaluefield:class InputAndChoice(object):def _
robos85
django django-admin django-users
How can I hide fields in admin User edit? Mainly I want to hide permissions and groups selecting in some exceptions, but exclude variable doesn’t work :/
Xudonax
python django override
Because we need our ModelChoiceFields to have different (non-__unicode__) labels based on where they’re used, I thought it would be a smart idea to override the ModelChoiceField and make it accept an extra parameter that will be called instead of label_from_instance. I could’ve made a subclass for every instance we need, but that’s not really DRY, is it now?My new ModelChoiceField:import django.formsclass ModelChoiceField(django.forms.ModelChoiceField):”””Subclasses Django’s ModelChoiceField and
Nixarn
django caching
So, the @cache_page decorator is awesome. But for my blog I would like to keep a page in cache until someone comments on a post. This sounds like a great idea as people rarely comment so keeping the pages in memcached while nobody comments would be great. I’m thinking that someone must have had this problem before? And this is different than caching per url.So a solution I’m thinking of is:@cache_page( 60 * 15, “blog” ); def blog( request ) …And then I’d keep a list of all cache keys used for
BoltClock
rrauenza
python django django-models
I came across an unexpected exception (ha!) — a self.delete() was failing because it’s id was None.I found the issue which sort of comes about like this:class Resource(Model):name = CharField()def in_maintenance(self):try:return self.maintenance.in_maintenance()except Maintenance.DoesNotExist:return Falseclass Maintenance(Model):expire = DateTimeField()resource = OneToOneField(Resource)def in_maintenance(self):if self.expired():MaintenanceHistory.add(self.resource, self.expire, …)self.delete(
user2492270
javascript jquery python ajax django
I noticed that when Boolean data is sent from javascript to Django view, it is passed as “true”/”false” (lowercase) instead of “True”/”False”(uppercase). This causes an unexpected behavior in my application. For example:vote.js….var xhr = {‘isUpvote’: isUpvote};$.post(location.href, xhr, function(data) {doSomething()});return false; });views.pydef post(self, request, *args, **kwargs):isUpvote = request.POST.get(‘isUpvote’)vote, created = Vote.objects.get_or_create(user_voted=user_voted)vote.is
AlexG_1010100101
python django django-cms
I’m try to fix an app that worked with django 1.4 within a new installation where I’m using Django 1.5 when I try to syncdb I have:TypeError: __init__() got an unexpected keyword argument ‘verify_exists’That’s because my app model.py have inside:link = models.URLField(verify_exists=True, max_length=255, null=True, blank=True)with what I d replace ‘verify_exists’ to make it compatible with Django1.5?
Luke
django django-models django-queryset django-cms django-queries
I have an error using get_or_create on a queryset: “TypeError at … save() got an unexpected keyword argument ‘using’ “. I’m using django 1.4.3, but looking around i found that those problems were fixed in django 1.2. this is the code section:class MailingListSubscriptionForm(forms.ModelForm):”””Form for subscribing to a mailing list”””# Notes : This form will not check the uniquess of# the ’email’ field, by defining it explictly and setting# it the Meta.exclude list, for allowing registration
plumwd
django-templates django-registration django-cms
I’m currently working on a project that uses django-registration and Django CMS. When display the pages that implement django-registration my page titles do not render.Currently have <title>{% page_attribute page_title %}</title> in base.html which all my templates inherit from.In the pages that do not use django-registration the titles display just fine, but django-registration display as <title></title>My pages are all created within the CMS and everything else is rend
qdot
google-app-engine django-nonrel django-cms
I’m trying to get the django-cms to work on google-app-engine. Did anyone succeed in getting such a beast to work?I’ve got a sample django-norel app to work and deploy correctly, I’ve got the django-cms to locally crash in a bunch of absolutely cryptic ways.DatabaseError at / First ordering property must be the same as inequality filter property, if specified for this query; received site, expected publisher_stateBefore I spend a lot of time trying to bughunt it, any success stories?
AlexG_1010100101
django-cms django-filer
I have a django 1.4 installation and I have django-cms running. I’m try to install filer but when I syncdb or runserver I keep having this error.from filer.models import mixinsImportError: cannot import name mixinsIn my setting.py I have:INSTALLED_APPS = ( ‘django.contrib.auth’, ‘django.contrib.contenttypes’, ‘django.contrib.sessions’, ‘django.contrib.sites’, ‘django.contrib.messages’, ‘django.contrib.staticfiles’, # Uncomment the next line to enable the admin: ‘django.contrib.admin’, ‘cms’, ‘m
Ben Griffiths
jquery django django-cms
I’ve got a django site running quite happily with django-cms but now I want to include some of my own fancy javascript using jQuery. I’m rather new to django, so my problems might stem from this.Django-cms uses jQuery itself, and so if I add jquery to the header – things break rathter unsurprisingly. How do I add my own jQuery without affecting django-cms?At the moment my javascript files are stored in the media root which I’ve defined in the projects settings.py and, as mentioned, I reference t
supervacuo
django django-admin django-cms django-grappelli
I just installed grappelli into a Django-CMS site by following the standard routine – pip install django-grappelli, add it to INSTALLED_APPS, add in the url pattern, then syncdb and collectstatic. However, although all the other pages in the admin area look great with the new “theme”, the layout for CMS Pages settings in Django-CMS (the drag ‘n drop interface) are all messed up.Why is that, and is there a fix for this, yet?Thanks.EDIT: Thanks, Brandon for your reply. Is there a way to completely
Luke
python django django-admin django-cms django-file-upload
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 =
Rodrigo Guedes
django heroku amazon-s3 django-cms
I’ve a django project on heroku and amazon s3. I’m using django 1.4.2 and django-cms 2.3.4 My problem is that i can’t edit or add any plugins to pages. Yesterday it works perfect but after I have changed a few things in a textfield it all went wrong… The problem with the textfield is fixed now but i still can’t edit/add any plugins. the only things I know are the following error-messages:Failed to load resource: the server responded with a status of 403 (Forbidden) Failed to load resource: th
Luke
javascript django tinymce django-cms django-tinymce
i’m using django-tinymce in a django project. After following the setup as suggested from docs, i’ve experienced some problems while deploying it. In fact, with the same settings, with development runserver, I got it working locally, but on a test machine (NGinx + Gunicorn), i have this error on console:Uncaught TypeError: undefined is not a function tiny_mce.js:1k.create.init tiny_mce.js:1(anonymous function) tiny_mce.js:1(anonymous function) tiny_mce.js:1c.each tiny_mce.js:1o tiny_mce.js:1(ano
Web site is in building