Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
Lamacq
Jun 15, 2001

Breezeblock RIP
Seconding fabric, and I know with apache + mod_wsgi in daemon mode, you just have to touch the .wsgi file for your changes to go live (which can easily be done via a fabric command).

That said I'm thinking about moving from apache + mod_wsgi to nginx + uwsgi, since I'm already using nginx for my front-end server and I'm seeing occasional load spikes and memory issues that I blame on mod_wsgi (and I've read every last bit of documentation on it and tweaked every setting I can find for it).

Adbot
ADBOT LOVES YOU

Captain Capacitor
Jan 21, 2008

The code you say?
Puppet + nginx -> apache -> mod_wsgi. The proxy might be overkill, but I worry less about killing things overall when I restart one particular site.

Ferg
May 6, 2007

Lipstick Apathy
Oh poo poo Fabric looks awesome as hell. Exactly what I was looking for, thanks!

Yay
Aug 4, 2007
We're ghetto fabulous, and use bash/svn export/rsync. I tried showing my boss Fabric, and he didn't seem interested ("What does it get us that bash doesn't?" - I've not used Fabric, so couldn't easily answer).

king_kilr
May 25, 2007

Yay posted:

We're ghetto fabulous, and use bash/svn export/rsync. I tried showing my boss Fabric, and he didn't seem interested ("What does it get us that bash doesn't?" - I've not used Fabric, so couldn't easily answer).

It gets you the mantras of deployment:

Repeatability
Maintainability
and Anyone on the planet would actually want to work with this-ability

Ferg
May 6, 2007

Lipstick Apathy
Cross-posting this with the Python thread:

I'm trying to dynamically load a class from a specific module (called 'commands') and the code runs totally cool on my local setup running from a local Django server. This bombs out though when I deploy to Google App Engine. I've tried adding the commands module's parent module to the __import__ as well with no avail (on either setup in that case). Here's the code:

code:
mod = __import__('commands.%s' % command, globals(), locals(), [command])
return getattr(mod, command)
App Engine consistently throws an ImportError.

Edit: and the clarify, it doesn't bomb out on the commands module. If I have a command like 'commands.cat' it can't find 'cat'.

Ferg fucked around with this message at 17:50 on Dec 20, 2010

unixbeard
Dec 29, 2004

I have a library i use for generating images, I am using it to display images in one of my views.

It seems like django is caching the object created in the view, because when i send a request that should redraw the image completely there is old cruft from previous redraws around. E.g. in my views.py I have:

code:
def viewimage(request):

        #work out what to draw based on request.GET

        d = Drawing()

        #futz about parsing request.get

        data = d.make()
        return HttpResponse(data, mimetype="image/png")
any idea how to turn this off? i have not set up caching at all in django

Captain Capacitor
Jan 21, 2008

The code you say?

unixbeard posted:

I have a library i use for generating images, I am using it to display images in one of my views.

It seems like django is caching the object created in the view, because when i send a request that should redraw the image completely there is old cruft from previous redraws around. E.g. in my views.py I have:

code:
def viewimage(request):

        #work out what to draw based on request.GET

        d = Drawing()

        #futz about parsing request.get

        data = d.make()
        return HttpResponse(data, mimetype="image/png")
any idea how to turn this off? i have not set up caching at all in django

Try this

code:
from django.views.decorators.cache import cache_control

...

@cache_control(no_cache=True)
def viewimage(request):

        #work out what to draw based on request.GET

        d = Drawing()

        #futz about parsing request.get

        data = d.make()
        return HttpResponse(data, mimetype="image/png")

unixbeard
Dec 29, 2004

thank you, that didnt help but made me realize the problem was probably elsewhere.

what i had was:

code:
class Drawing(object):

        foo = 0
        bar = []

        def __init__(self, x=1):
                self.foo = x

        def add(self, val):
                self.bar.append(val)

if __name__ == '__main__':

        a = Drawing(2)
        a.add('a')
        a.add('b')

        print a.bar
        print a.foo

        b = Drawing(3)
        print b.bar
        print b.foo

which gives:

code:
['a', 'b']
2
['a', 'b']
3
so i just had to reset bar[] in __init__

i hadnt noticed it before because i had only been using it in separate programs that only ran once

Profane Obituary!
May 19, 2009

This Motherfucker is Dead

unixbeard posted:

thank you, that didnt help but made me realize the problem was probably elsewhere.

what i had was:

code:
class Drawing(object):

        foo = 0
        bar = []

        def __init__(self, x=1):
                self.foo = x

        def add(self, val):
                self.bar.append(val)

if __name__ == '__main__':

        a = Drawing(2)
        a.add('a')
        a.add('b')

        print a.bar
        print a.foo

        b = Drawing(3)
        print b.bar
        print b.foo

which gives:

code:
['a', 'b']
2
['a', 'b']
3
so i just had to reset bar[] in __init__

i hadnt noticed it before because i had only been using it in separate programs that only ran once

For what it's worth, this is because bar is a class variable in your example, you shouldn't put variables directly under the class def unless they are supposed to stay the same for every instance of the class.

unixbeard
Dec 29, 2004

Profane Obituary! posted:

For what it's worth, this is because bar is a class variable in your example, you shouldn't put variables directly under the class def unless they are supposed to stay the same for every instance of the class.

yes thank you i had forgotten and was never quite clear on the difference. So would you say as a rule of thumb all per-instance variables should be declared & set up in __init__ ?

also i thought class variables were normally accessed through Drawing.bar, and that if i was using self.bar it would be instance level?

unixbeard fucked around with this message at 19:26 on Jan 1, 2011

Profane Obituary!
May 19, 2009

This Motherfucker is Dead
As a rule of thumb yea instance level variables should be assigned in __init__.

I think (and on this i may be wrong), but ClassName.attribute vs self.attribute depends on how you want to access the data. ClassName.attribute will only ever get the attributes defined directly under the class whereas self.attribute will first access any instance attributes that may have been named the same, and then the class attributes.

code:
class Drawing(object):

    foo = [1]

    def __init__(self, bar=False):
        if bar:
            self.foo = [2]
        else:
            self.foo.append(2)

>>> Drawing.foo
[1]
>>> dwing = Drawing()
>>> dwing.foo
[1, 2]
>>> dwing2 = Drawing(True)
>>> dwing2.foo
[2]
>>> dwing3 = Drawing()
>>> dwing3.foo
[1, 2, 2]
>>> dwing.foo
[1, 2, 2]
In the above, if you used Drawing.foo, you would get the class attribute no matter what the __init__ in the example did, if you used self.attribute, on dwing2 you got the result that dwing2 overwrote.

This is a great trick for keeping a list of all instances of a certain class.

code:
class Tracker(object):

    instances = []

    def __init__(self, name):
        self.name = name

        self.instances.append(self)

    def __repr__(self):
        return self.name

>>> Tracker('Tracker 1')
Tracker 1
>>> Tracker('Tracker 2')
Tracker 2
>>> Tracker('Tracker 3')
Tracker 3
>>> Tracker.instances
[Tracker 1, Tracker 2, Tracker 3]
edit: Also note, that class attributes will seem to work as instance attributes if they are immutable. This is because the class attribute is actually a reference, and when you "modify" something that is immutable it actually has the attribute point to a different object, but when modifying something that is mutable, the reference never changes.

Profane Obituary! fucked around with this message at 20:17 on Jan 2, 2011

nbv4
Aug 21, 2002

by Duchess Gummybuns
how do you import models from an app in the management command folder? in appname/management/commands/something.py I want to import a model that is located in /app/models.py. Right now I'm doing from ..appname.models import MyModel. It looks ugly and was wondering how other people do this.

king_kilr
May 25, 2007
code:
from appname.models import Model

Surface
May 5, 2007
<3 boomstick
I am working on a Django app at my company that is going to be using Generic Relations, are there libraries/resources that add functionality to the Django Admin with regards to Generic Relations?

I found this but I was wondering if there was anything else?

Also, anyone have experience with EAV-Django?

chutwig
May 28, 2001

BURLAP SATCHEL OF CRACKERJACKS

I have a bit of a dilemma that I've been working on all morning. I have a Django app (displays statuses of many of our systems) that needs to interface with an external database updated by another application (Nagios). I wrote a controller that shims between this external DB and the rest of the app and mediates all access to it, and it generally works well.

The problem arises in the admin interface when you want to add a new host or service for display in my app. The list of hosts was originally built as a choices on the CharField like so:
code:
class Host(models.Model):
    nagios_ctl = nagios.controller()
    raw_host_list = nagios_ctl.enumerate_hosts()

    HOST_CHOICES = ()
    for i in raw_host_list:
        HOST_CHOICES += ((i[1], i[1]),)

    name = models.CharField(max_length=60, choices=HOST_CHOICES)
The obvious problem, and the one that I didn't see until recently, is that if you add a new host in Nagios, it won't show up here because HOST_CHOICES is created once and only once. To refresh it, I have to touch the WSGI script file to reload the interpreter.

I first tried to fix it by subclassing ChoiceField into LazyChoiceField from a Django snippet I found that was supposed to cause the list to be lazily evaluated and moving the part where it generates the list into a ModelForm for the Host class, but that didn't actually change anything. The list is still generated fine, it just doesn't update when Nagios does:
code:
class HostForm(forms.ModelForm):
    class Meta:
        model = Host
        fields = ('category', 'name', 'description', 'nagios_object_id')
    
    # provides a host list in the admin interface
    nagios_ctl = nagios.controller()
    raw_host_list = nagios_ctl.enumerate_hosts()

    HOST_CHOICES = ()
    for i in raw_host_list:
        HOST_CHOICES += ((i[1], i[1]),)
    
    name = LazyChoiceField(choices = HOST_CHOICES)
code:
class HostAdmin(admin.ModelAdmin):
    form = HostForm
    readonly_fields = ("nagios_object_id",)
    ordering = ['name']
    list_display = ('name', 'description', 'nagios_object_id')
    formfield_overrides = {
        LazyChoiceField: {'widget': widgets.Select},
    }
Does anyone have thoughts on what I can do to force the choices list to be evaluated every single time? I am positive that there's an easy solution staring me in the face and I'm overlooking it repeatedly because I've tunnel-visioned.

king_kilr
May 25, 2007
Take a look at how FilePathField is implemented (http://code.djangoproject.com/browser/django/trunk/django/db/models/fields/__init__.py#L817), now copy that for your logic.

sink
Sep 10, 2005

gerby gerb gerb in my mouf
Last page there was some discussion about automated tasks. I've been using django-chronograph for some fairly simple things and I like it. You set up a cronjob to hit chronograph admin command once a minute. Then it acts as a controller for other commands that you schedule via the admin web interface.

duck monster
Dec 15, 2004

Anyone ever encountred this. Happens the same in MySQL or Postgres (or more or less. Some sort of bitch-out about character lengths)

code:
bash-3.2# ./manage.py version
Unknown command: 'version'
Type 'manage.py help' for usage.
bash-3.2# ./manage.py syncdb
Syncing...
Creating table auth_permission
Creating table auth_group_permissions
Creating table auth_group
Creating table auth_user_user_permissions
Creating table auth_user_groups
Creating table auth_user
Creating table auth_message
Creating table django_content_type
Creating table django_admin_log
Creating table django_session
Creating table django_site
Creating table directory_account
Creating table directory_contactcard
Creating table directory_language
Creating table directory_biography
Creating table directory_keywords
Creating table directory_accountlanguage
Creating table directory_industryassociation
Creating table directory_industryassociationmembership
Creating table directory_socialnetwork
Creating table directory_marinadata
Creating table directory_publicity
Creating table directory_media
Creating table directory_exhibition
Creating table directory_exhibitor
Creating table directory_account_industryassociationmembership
Creating table south_migrationhistory

You just installed Django's auth system, which means you don't have any superusers defined.
Would you like to create one now? (yes/no): yyes^H^Hb
Please enter either "yes" or "no": yes
Username (Leave blank to use 'root'): 
E-mail address: w!w.w.w!~!
Error: That e-mail address is invalid.
E-mail address: [email]duckmonster@mydilz.nik[/email]
Password: 
Password (again): 
Superuser created successfully.
Traceback (most recent call last):
  File "./manage.py", line 11, in <module>
    execute_manager(settings)
  File "/Library/Python/2.6/site-packages/django/core/management/__init__.py", line 438, in execute_manager
    utility.execute()
  File "/Library/Python/2.6/site-packages/django/core/management/__init__.py", line 379, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/Library/Python/2.6/site-packages/django/core/management/base.py", line 191, in run_from_argv
    self.execute(*args, **options.__dict__)
  File "/Library/Python/2.6/site-packages/django/core/management/base.py", line 220, in execute
    output = self.handle(*args, **options)
  File "/Library/Python/2.6/site-packages/django/core/management/base.py", line 351, in handle
    return self.handle_noargs(**options)
  File "/Library/Python/2.6/site-packages/South-0.7.3-py2.6.egg/south/management/commands/syncdb.py", line 90, in handle_noargs
    syncdb.Command().execute(**options)
  File "/Library/Python/2.6/site-packages/django/core/management/base.py", line 220, in execute
    output = self.handle(*args, **options)
  File "/Library/Python/2.6/site-packages/django/core/management/base.py", line 351, in handle
    return self.handle_noargs(**options)
  File "/Library/Python/2.6/site-packages/django/core/management/commands/syncdb.py", line 103, in handle_noargs
    emit_post_sync_signal(created_models, verbosity, interactive, db)
  File "/Library/Python/2.6/site-packages/django/core/management/sql.py", line 182, in emit_post_sync_signal
    interactive=interactive, db=db)
  File "/Library/Python/2.6/site-packages/django/dispatch/dispatcher.py", line 172, in send
    response = receiver(signal=self, sender=sender, **named)
  File "/Library/Python/2.6/site-packages/django/contrib/auth/management/__init__.py", line 28, in create_permissions
    defaults={'name': name, 'content_type': ctype})
  File "/Library/Python/2.6/site-packages/django/db/models/manager.py", line 135, in get_or_create
    return self.get_query_set().get_or_create(**kwargs)
  File "/Library/Python/2.6/site-packages/django/db/models/query.py", line 379, in get_or_create
    obj.save(force_insert=True, using=self.db)
  File "/Library/Python/2.6/site-packages/django/db/models/base.py", line 456, in save
    self.save_base(using=using, force_insert=force_insert, force_update=force_update)
  File "/Library/Python/2.6/site-packages/django/db/models/base.py", line 549, in save_base
    result = manager._insert(values, return_id=update_pk, using=using)
  File "/Library/Python/2.6/site-packages/django/db/models/manager.py", line 195, in _insert
    return insert_query(self.model, values, **kwargs)
  File "/Library/Python/2.6/site-packages/django/db/models/query.py", line 1518, in insert_query
    return query.get_compiler(using=using).execute_sql(return_id)
  File "/Library/Python/2.6/site-packages/django/db/models/sql/compiler.py", line 788, in execute_sql
    cursor = super(SQLInsertCompiler, self).execute_sql(None)
  File "/Library/Python/2.6/site-packages/django/db/models/sql/compiler.py", line 732, in execute_sql
    cursor.execute(sql, params)
  File "/Library/Python/2.6/site-packages/django/db/backends/util.py", line 15, in execute
    return self.cursor.execute(sql, params)
  File "/Library/Python/2.6/site-packages/django/db/backends/postgresql_psycopg2/base.py", line 44, in execute
    return self.cursor.execute(query, args)
django.db.utils.DatabaseError: value too long for type character varying(50)
Unfortunately I cant seem to get the bloody thing to tell me what part of my code this is in, and I have no idea how to convince it to tell me.

FWIW Heres my models:

code:
# -*- coding: utf-8 -*-
# auto generated from an XMI file
from django.db import models

from django.utils.encoding import force_unicode

def getUnicode(object):
	if (object == None):
		return u""
	else:
		return force_unicode(object)
		

#
class Account(models.Model):
	companyname = models.CharField(max_length=255, null=False, default="", blank=True, )
	user = models.IntegerField(null=True, blank=True, )
	registrationdate = models.DateTimeField(null=True, blank=True, )
	modificationdate = models.DateTimeField(null=True, blank=True, )
	newsletter = models.BooleanField(default=False, null=False, blank=False, )
	listingtype = models.IntegerField(null=True, blank=True, )
	termsandconditionsversion = models.IntegerField(null=True, blank=True, )
	parentaccount = models.IntegerField(null=True, blank=True, )
	servicingregion = models.CharField(max_length=32, null=False, default="", blank=True, )
	servicingcountry = models.CharField(max_length=32, null=False, default="", blank=True, )
	servicingcity = models.CharField(max_length=32, null=False, default="", blank=True, )
	servicingradius = models.CharField(max_length=32, null=False, default="", blank=True, )
	contact = models.ForeignKey('ContactCard', blank=False, null=False, default=1, related_name='%(class)s_contact', )
 	billing = models.ForeignKey('ContactCard', blank=False, null=False, default=1, related_name='%(class)s_billing', )
 	parent = models.ForeignKey('self', blank=True, null=True, related_name='%(class)s_parent', )
 
	class Meta:
		verbose_name = 'Account'
		verbose_name_plural = 'Accounts'
		

	table_group = ''


#
class ContactCard(models.Model):
	telephone = models.CharField(max_length=32, null=False, default="", blank=True, )
	email = models.CharField(max_length=32, null=False, default="", blank=True, )
	website = models.CharField(max_length=32, null=False, default="", blank=True, )
	addressline1 = models.CharField(max_length=255, null=False, default="", blank=True, )
	addressline2 = models.CharField(max_length=255, null=False, default="", blank=True, )
	city = models.CharField(max_length=255, null=False, default="", blank=True, )
	state = models.CharField(max_length=255, null=False, default="", blank=True, )
	country = models.CharField(max_length=32, null=False, default="", blank=True, )
	cardtype = models.IntegerField(null=True, blank=True, help_text=ur'''CardType should represent whether its a billing address, contact etc.''', )

	class Meta:
		verbose_name = 'ContactCard'
		verbose_name_plural = 'ContactCards'
		

	table_group = ''


#
class Language(models.Model):
	languagename = models.CharField(max_length=32, null=False, default="", blank=True, )
	unicodepage = models.CharField(max_length=32, null=False, default="", blank=True, )

	class Meta:
		verbose_name = 'Language'
		verbose_name_plural = 'Languages'
		

	table_group = ''


#
class Biography(models.Model):
	content = models.TextField(null=False, default="", blank=True, )
	account = models.ForeignKey('Account', blank=False, null=False, default=1, )
 	language = models.ForeignKey('Language', blank=False, null=False, default=1, )
 
	class Meta:
		verbose_name = 'Biography'
		verbose_name_plural = 'Biographies'
		

	table_group = ''


#
class KeyWords(models.Model):
	content = models.CharField(max_length=32, null=False, default="", blank=True, )
	language = models.ForeignKey('Language', blank=False, null=False, default=1, )
 	account = models.ForeignKey('Account', blank=False, null=False, default=1, )
 
	class Meta:
		verbose_name = 'KeyWords'
		verbose_name_plural = 'KeyWordses'
		

	table_group = ''


#
class AccountLanguage(models.Model):
	primary = models.BooleanField(default=False, null=False, blank=False, )
	account = models.ForeignKey('Account', blank=False, null=False, default=1, )
 	language = models.ForeignKey('Language', blank=False, null=False, default=1, )
 
	class Meta:
		verbose_name = 'AccountLanguage'
		verbose_name_plural = 'AccountLanguages'
		

	table_group = ''


#
class IndustryAssociation(models.Model):
	name = models.CharField(max_length=255, null=False, default="", blank=True, )
	logourl = models.URLField()
	websiteurl = models.URLField()
	account = models.ForeignKey('Account', blank=False, null=False, default=1, )
 
	class Meta:
		verbose_name = 'IndustryAssociation'
		verbose_name_plural = 'IndustryAssociations'
		

	table_group = ''


#
class IndustryAssociationMembership(models.Model):
	title = models.CharField(max_length=255, null=False, default="", blank=True, )
	account = models.ManyToManyField('Account', blank=False, null=False, default=1, through='Account_IndustryAssociationMembership', )
 	industryassociation = models.ForeignKey('IndustryAssociation', blank=False, null=False, default=1, )
 
	class Meta:
		verbose_name = 'IndustryAssociationMembership'
		verbose_name_plural = 'IndustryAssociationMemberships'
		

	table_group = ''


#
class SocialNetwork(models.Model):
	type = models.IntegerField(null=True, blank=True, )
	url = models.URLField()
	username = models.CharField(max_length=255, null=False, default="", blank=True, )
	secret = models.CharField(max_length=1024, null=False, default="", blank=True, )
	writepermission = models.BooleanField(default=False, null=False, blank=False, )
	account = models.ForeignKey('Account', blank=False, null=False, default=1, )
 
	class Meta:
		verbose_name = 'SocialNetwork'
		verbose_name_plural = 'SocialNetworks'
		

	table_group = ''


#
class MarinaData(models.Model):
	name = models.CharField(max_length=255, null=False, default="", blank=True, )
	ismarina = models.BooleanField(default=False, null=False, blank=False, )
	maxdraught = models.FloatField(null=True, blank=True, )
	maxlength = models.FloatField(null=True, blank=True, )
	vhfchannels = models.CharField(max_length=255, null=False, default="", blank=True, )
	date = models.DateTimeField(null=True, blank=True, )
	lattitude = models.FloatField(null=True, blank=True, )
	longtitude = models.FloatField(null=True, blank=True, )
	marinefacilities = models.TextField(null=False, default="", blank=True, )
	nearbyfacilities = models.TextField(null=False, default="", blank=True, )
	berthstableu12 = models.CharField(max_length=255, null=False, default="", blank=True, )
	berthstable13t24 = models.CharField(max_length=255, null=False, default="", blank=True, )
	berthstable25t34 = models.CharField(max_length=255, null=False, default="", blank=True, )
	berthstable50t60 = models.CharField(max_length=255, null=False, default="", blank=True, )
	berthstableo60 = models.IntegerField(null=True, blank=True, )
	account = models.ForeignKey('Account', blank=False, null=False, default=1, )
 
	class Meta:
		verbose_name = 'MarinaData'
		verbose_name_plural = 'MarinaDatas'
		

	table_group = ''


#
class Publicity(models.Model):
	type = models.IntegerField(null=True, blank=True, )
	refersto = models.IntegerField(null=True, blank=True, )
	title = models.CharField(max_length=255, null=False, default="", blank=True, )
	content = models.TextField(null=False, default="", blank=True, )
	account = models.ForeignKey('Account', blank=False, null=False, default=1, )
 	language = models.ForeignKey('Language', blank=False, null=False, default=1, )
 
	class Meta:
		verbose_name = 'Publicity'
		verbose_name_plural = 'Publicities'
		

	table_group = ''


#
class Media(models.Model):
	mediatype = models.CharField(max_length=32, null=False, default="", blank=True, )
	path = models.CharField(max_length=255, null=False, default="", blank=True, )
	title = models.CharField(max_length=255, null=False, default="", blank=True, )
	keywords = models.CharField(max_length=255, null=False, default="", blank=True, )
	description = models.TextField(null=False, default="", blank=True, )
	parentrec = models.IntegerField(null=True, blank=True, )
	ispublic = models.BooleanField(default=False, null=False, blank=False, )
	account = models.ForeignKey('Account', blank=False, null=False, default=1, )
 
	class Meta:
		verbose_name = 'Media'
		verbose_name_plural = 'Medias'
		

	table_group = ''


#
class Exhibition(models.Model):
	name = models.CharField(max_length=255, null=False, default="", blank=True, )
	location = models.TextField(null=False, default="", blank=True, )
	datefrom = models.DateTimeField(null=True, blank=True, )
	dateto = models.DateTimeField(null=True, blank=True, )
	account = models.ForeignKey('Account', blank=False, null=False, default=1, )
 
	class Meta:
		verbose_name = 'Exhibition'
		verbose_name_plural = 'Exhibitions'
		

	table_group = ''


#
class Exhibitor(models.Model):
	issponsor = models.BooleanField(default=False, null=False, blank=False, )
	isexhibitor = models.BooleanField(default=False, null=False, blank=False, )
	name = models.CharField(max_length=255, null=False, default="", blank=True, )
	description = models.TextField(null=False, default="", blank=True, )
	exhibition = models.ForeignKey('Exhibition', blank=False, null=False, default=1, )
 	account = models.ForeignKey('Account', blank=False, null=False, default=1, )
 	logo = models.ForeignKey('Media', blank=False, null=False, default=1, related_name='%(class)s_logo', )
 
	class Meta:
		verbose_name = 'Exhibitor'
		verbose_name_plural = 'Exhibitors'
		

	table_group = ''


# Many To Many Tables 

#
class Account_IndustryAssociationMembership(models.Model):
	account = models.ForeignKey('Account')
	industryassociationmembership = models.ForeignKey('IndustryAssociationMembership')
I cant see anything wrong there. Its autogenerated from a UML diagram, and has a few hand tweaks, but yeah. :confused:

Captain Capacitor
Jan 21, 2008

The code you say?

duck monster posted:

Anyone ever encountred this. Happens the same in MySQL or Postgres (or more or less. Some sort of bitch-out about character lengths)


Run "./manage.py sql" to create the SQL commands for all of the tables involved and you can see which one has a limit of 50.

duck monster
Dec 15, 2004

Captain Capacitor posted:

Run "./manage.py sql" to create the SQL commands for all of the tables involved and you can see which one has a limit of 50.

None of them :(

code:
bash-3.2# ./manage.py sqlall directory | grep 50
ALTER TABLE "directory_account" ADD CONSTRAINT "parent_id_refs_id_5030256d" FOREIGN KEY ("parent_id") REFERENCES "directory_account" ("id") DEFERRABLE INITIALLY DEFERRED;
ALTER TABLE "directory_account" ADD CONSTRAINT "contact_id_refs_id_8d33500a" FOREIGN KEY ("contact_id") REFERENCES "directory_contactcard" ("id") DEFERRABLE INITIALLY DEFERRED;
ALTER TABLE "directory_account" ADD CONSTRAINT "billing_id_refs_id_8d33500a" FOREIGN KEY ("billing_id") REFERENCES "directory_contactcard" ("id") DEFERRABLE INITIALLY DEFERRED;
    "berthstable50t60" varchar(255) NOT NULL,
bash-3.2# 
bash-3.2# 

Profane Obituary!
May 19, 2009

This Motherfucker is Dead
I don't see anything wrong, but have you tried commenting out everything, and uncommenting and syncdbing them a couple at a time?

Yay
Aug 4, 2007
I would guess the problem is the table
code:
directory_account_industryassociationmembership
which is 47 characters long. The exception appears to be coming from creating the permissions for things
code:
File "/Library/Python/2.6/site-packages/django/contrib/auth/management/__init__.py", line 28, in create_permissions
    defaults={'name': name, 'content_type': ctype})
and I'm wagering it has a limit of some kind thats being hit describing the permissions for such tables.

According to django snippets, from a long time ago, you can try and run create_permissions from the shell with the following:
code:
from django.contrib.auth.management import create_permissions
from django.db.models import get_apps
for app in get_apps():
   create_permissions(app, None, 2)
If that runs fine (assuming its up to date), I rightly don't know, but if it fails, you could always explicitly set db_table on the model meta options to be shorter.

(The reason this is occuring, if it is the problem, is because as I recall, syncdb emits a signal for updating content types and permissions for new models)

(Edit: confirmed for myself that auth's Permission model has a CharField which is 50 characters maximum)

Yay fucked around with this message at 13:13 on Jan 16, 2011

duck monster
Dec 15, 2004

Bingo! By shortening the name of that table to the super descriptive
'DAIM' the migrations all run sanely without making GBS threads themselves.

What a *stupid* bug. Its been reported to hell and back on the django bug tracker, but I see no evidence at all of it being either fixed or that there is any desire to fix it. :(

Apparently it might break older code SOMEHOW. v:shobon:v

All I could really find was a cobwebbed bug tracker, and some douchebag developers pouring piss and venom on some poor newbie that tripped over it.

duck monster fucked around with this message at 05:07 on Jan 17, 2011

Mulozon Empuri
Jan 23, 2006

duck monster posted:

Bingo! By shortening the name of that table to the super descriptive
'DAIM' the migrations all run sanely without making GBS threads themselves.

What a *stupid* bug. Its been reported to hell and back on the django bug tracker, but I see no evidence at all of it being either fixed or that there is any desire to fix it. :(

Apparently it might break older code SOMEHOW. v:shobon:v

All I could really find was a cobwebbed bug tracker, and some douchebag developers pouring piss and venom on some poor newbie that tripped over it.

Was there nothing to be found in your database log?

chutwig
May 28, 2001

BURLAP SATCHEL OF CRACKERJACKS

sink posted:

Last page there was some discussion about automated tasks. I've been using django-chronograph for some fairly simple things and I like it. You set up a cronjob to hit chronograph admin command once a minute. Then it acts as a controller for other commands that you schedule via the admin web interface.

I could easily just have a cron job that touches the WSGI script file, but I'd like to avoid that because of the long delay in page response when the interpreter is restarting and loading the Django app again. My problem is that once the object is initialized and it obtains this list of hosts and services from the external DB, that sticks around until the interpreter's destroyed. I can't find a hook to run something every time the admin form is loaded; __init__() only runs the first time the admin form is created. I really wish there were an equivalent to validate() that ran on form load so that I could stash the retrieval in there.

I'll look into django-chronograph and see if I can schedule some way of doing it, but I'm not feeling real hopeful.

Yay
Aug 4, 2007

chutwig posted:

[...] I can't find a hook to run something every time the admin form is loaded; __init__() only runs the first time the admin form is created.

Assuming the calls to the python nagios module you're using aren't cached, but are instead generated anew each time, could you not add the functionality to one of the ModelAdmin methods? I can't remember the method names, but I know you can override the change_form (or whatever) methods etc and add your required code, before calling super to render the original modeladmin stuff.

That suff should get called each time, so might work. Could be kind of hacky, though. YMMV.

chutwig
May 28, 2001

BURLAP SATCHEL OF CRACKERJACKS

Yay posted:

Assuming the calls to the python nagios module you're using aren't cached, but are instead generated anew each time, could you not add the functionality to one of the ModelAdmin methods? I can't remember the method names, but I know you can override the change_form (or whatever) methods etc and add your required code, before calling super to render the original modeladmin stuff.

That suff should get called each time, so might work. Could be kind of hacky, though. YMMV.

I came across http://docs.djangoproject.com/en/1.2/ref/forms/api/#django.forms.Form.initial so I'm going to try implementing it that way. I may have also hosed up before when I was trying to insert the list into self.fields['name'].choices, so that's another option. I just need to steel myself enough to go back into the code and look at it.

duck monster
Dec 15, 2004

Mulozon Empuri posted:

Was there nothing to be found in your database log?

Nope!

Hanpan
Dec 5, 2004

I am trying to create a simple blog application and I want to list all my blog posts along with all the categories that entry is associated with. My "Entry" model has a ManyToMany field called "categories" to make the connection.

When I list my Entries using Entries.objects.all(), it will hit the database once PER ENTRY.. even if I have already obtained that category elsewhere. I understand why this is happening, but surely I can cache the results somehow? If I am showing 100 entries on a page, hitting the database 100 times to get each posts categories seems rather excessive.

My actual query looks like this: "Entry.objects.all().select_related('author')" since I am also showing the authors information, and adding Entry.objects.all().select_related('author', 'categories') doesn't seem to help... it'd also be one hell of a query!

Anyone have an ideas as to how I could improve on this?

Mulozon Empuri
Jan 23, 2006

duck monster posted:

Nope!

Crazy. And you would think they would be able to change the exception msg without breaking anything.

Surface
May 5, 2007
<3 boomstick

Hanpan posted:

I am trying to create a simple blog application and I want to list all my blog posts along with all the categories that entry is associated with. My "Entry" model has a ManyToMany field called "categories" to make the connection.

When I list my Entries using Entries.objects.all(), it will hit the database once PER ENTRY.. even if I have already obtained that category elsewhere. I understand why this is happening, but surely I can cache the results somehow? If I am showing 100 entries on a page, hitting the database 100 times to get each posts categories seems rather excessive.

My actual query looks like this: "Entry.objects.all().select_related('author')" since I am also showing the authors information, and adding Entry.objects.all().select_related('author', 'categories') doesn't seem to help... it'd also be one hell of a query!

Anyone have an ideas as to how I could improve on this?

Querysets are supposed to be lazily evaluated, enabling you to stack various filters/etc before the db actually gets queried but I wonder if the order in which you are applying select_related could be causing it to not function as expected...

So, just for grins: have you tried
code:
Entry.objects.select_related().all()
opposed to
code:
Entry.objects.all().select_related()

king_kilr
May 25, 2007
Those 2 are equivilant in every way. You can't select_related a many to many (or any multivalued relationship).

Hanpan
Dec 5, 2004

So my only real option is to create a dict of all the categories first and then obtain the data from that. Saves on a fair few queries so must be worth it.

duck monster
Dec 15, 2004

Is there any obvious way to get the GeoDjango map widget to display in a template.

Everything I can find on Google at the moment seems to be about showing the wiget in an Admin panel. As the client put it; "Requiring customers to get full time employment to view the map is not exactly what we are aiming to do here!"

Surely with this wiget being in there, theres an easy way to convince django to do this.

Surface
May 5, 2007
<3 boomstick
I just learned that you can use custom queries to filter the list presented on a Model's Admin Change List view.

Such as,

code:
http://www.mysite.com/admin/my_app/my_model/?foo__bar__endswith=baz
Which returns a queryset equivalent to the one returned by

code:
MyModel.objects.filter(foo__bar__endswith="baz")
But, unless I am mistaken, it is not using ModelManager I provided (named 'objects') to MyModel.


So I have a two questions:
1) Is it possible for http requests like the one above to run through a custom ModelManager?
2) Regardless of the answer to #1, what section of the Django source is involved building QuerySets for responses to http requests like the one above?


Fake edit: If '2) tell me what line teh codez is on' is too LMGTFY, any suggestions on how I should start looking for that section of code?

epswing
Nov 4, 2003

Soiled Meat
Any comments on django-invitation versus django-privatebeta?

Mulozon Empuri
Jan 23, 2006

This just in: tastypie kicks so much rear end compared to django-piston, I think I've found my weapon of choice when it comes to building apis.

Ferg
May 6, 2007

Lipstick Apathy

Mulozon Empuri posted:

This just in: tastypie kicks so much rear end compared to django-piston, I think I've found my weapon of choice when it comes to building apis.

Hell yes! I spent all morning wrestling with trying to fix a Piston bug. So sick of it.

Adbot
ADBOT LOVES YOU

Xenos
Jun 17, 2005

Mulozon Empuri posted:

This just in: tastypie kicks so much rear end compared to django-piston, I think I've found my weapon of choice when it comes to building apis.

This actually looks a lot nicer than Piston, I'll most likely use it the next time I need to build an API.

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply