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
Mulozon Empuri
Jan 23, 2006

MonkeyMaker posted:

Anyone here going to DjangoCon?

I'm going to try to make it to the next djangocon europe.

Adbot
ADBOT LOVES YOU

Profane Obituary!
May 19, 2009

This Motherfucker is Dead
http://djangocon.us/livestream/

There goes my productivity for the week.

Xenos
Jun 17, 2005

MonkeyMaker posted:

Anyone here going to DjangoCon?

I'm there right now :woop:

MonkeyMaker
May 22, 2006

What's your poison, sir?

Xenos posted:

I'm there right now :woop:

Hey, me too! Look for the dude giving out djangopeople.me stickers (I know, how descriptive!)

duck monster
Dec 15, 2004

Does anyone know what a django thing called "Zamboni" is? For the loving life of me I cant work it out, but for some reason my curiosity is killing me.

e: Oh never mind its some mozilla internal stuff that uses django which has created a bit of google polution for runserver_plus in a few queries

duck monster fucked around with this message at 08:34 on Sep 7, 2011

Profane Obituary!
May 19, 2009

This Motherfucker is Dead

Xenos posted:

I'm there right now :woop:

MonkeyMaker posted:

Hey, me too! Look for the dude giving out djangopeople.me stickers (I know, how descriptive!

My jealousy knows no bounds... next year !

bitprophet
Jul 22, 2004
Taco Defender

MonkeyMaker posted:

Hey, me too! Look for the dude giving out djangopeople.me stickers (I know, how descriptive!)

I'm here too :)

MonkeyMaker
May 22, 2006

What's your poison, sir?
If anyone wants a DjangoCon 2011 t-shirt, they're on sale for $20. I'm willing to pick them up for you, just Paypal me cost + shipping. hit me on twitter at @kennethlove for fastest responses.

bitprophet
Jul 22, 2004
Taco Defender

MonkeyMaker posted:

If anyone wants a DjangoCon 2011 t-shirt, they're on sale for $20. I'm willing to pick them up for you, just Paypal me cost + shipping. hit me on twitter at @kennethlove for fastest responses.

Say, didn't Steve Ivy say yesterday that you wanted to meet up with me? EDIT: No, wait, that was some other guy. I think you still said you wanted to say hi though :v: I'm in the middle rear of the lightning talks room at the moment...

Profane Obituary!
May 19, 2009

This Motherfucker is Dead

MonkeyMaker posted:

If anyone wants a DjangoCon 2011 t-shirt, they're on sale for $20. I'm willing to pick them up for you, just Paypal me cost + shipping. hit me on twitter at @kennethlove for fastest responses.

You gave that CBV talk?

MonkeyMaker
May 22, 2006

What's your poison, sir?

Profane Obituary! posted:

You gave that CBV talk?

Yeah. And the one about Banana-py.

Profane Obituary!
May 19, 2009

This Motherfucker is Dead

MonkeyMaker posted:

Yeah. And the one about Banana-py.

Well assuming no one does it during a sprint, your talk started the ball rolling on me fixing the docs for CBV's. I use the poo poo out of them and they are awesome

(Also FormView is not hard!)

Hed
Mar 31, 2004

Fun Shoe
I was never able to get the live streams working from the office. Any idea on how soon until the sessions are posted on Blip? It seems like it has taken a few weeks in the past.

Comrade Gritty
Sep 19, 2011

This Machine Kills Fascists
And they are up: http://blip.tv/djangocon

Puddy Dumplins
Apr 10, 2011
I'm trying to figure out how to automatically load data into my app, sort of like a fixture but with a lot helper-functions to simplify the construction of the data set by hand. I decided on a YAML format, but now I'm having difficulty resolving the data into an actual instance of a model.

Say I have a model like this:

code:
class Unit(models.Model):
    name = models.CharField(_('Name'), max_length=80)    
    type = models.ForeignKey(UnitType, related_name='unit_type', verbose_name=_('Unit Type'))
    location = models.ForeignKey(Territory, related_name='location', verbose_name=_('Location'))
and I also have some data:

code:
class_name = 'Unit'
fields = {'name' : 'Franky',
          'type' : 'Soldier',
          'location' : 'France'
         }
what I want to do is to is, after doing a bunch of error and integrity checking, resolve this data into an object:

code:
class_def = Unit
real_fields = {'name' : 'Franky',
               'type' : UnitType.objects.get(name='Soldier'),
               'location' : Territory.objects.get(name='France')
              }
object = class_def(**real_fields)
I know how to get class_def, but I'm not exactly sure how to loop over the fields of that class, much less knowing how to check what type of class they are.

Does anyone have an idea of how to do this?

xpander
Sep 2, 2004
I've been tasked with making some improvements to an internal web tool, as a way of getting up to speed on Python and Django. I have a FilteredSelectMultiple widget in place, and it's pulling in data properly, however I haven't been able to nail saving yet. Through a bunch of googling, I've figured out that I need to handle saving the intermediary model's data.

Here are the requisite models:

code:
class Server(AuditBase):
    name = models.CharField(max_length=50, unique=True)
    fqdn = models.CharField(max_length=100)
    provider = models.CharField(max_length=50)
    disabled = models.BooleanField(default=False)
    connection = models.CharField(max_length=50)
    comment = models.CharField(max_length=50, null=True, blank=True)
    
    def __unicode__(self):
        return self.name
    
class Profile(AuditBase):
    name = models.CharField(max_length=50, unique=True)
    servers = models.ManyToManyField(Server, through='ServerGroup')
    limitcount = models.PositiveIntegerField(null=True, blank=True)

    def __unicode__(self):
        return self.name

class ServerGroup(models.Model):
    profile = models.ForeignKey(Profile)
    server = models.ForeignKey(Server)

    def __unicode__(self):
        return "Profile=%s, Server=%s" % (self.profile.name, self.server.name)
And here's the form from admin.py:

code:
class ServerAdminForm(forms.ModelForm):
    servers = forms.ModelMultipleChoiceField(queryset=Server.objects.all(), widget=FilteredSelectMultiple("Servers", is_stacked=False))
   
    class Meta:
        model = Server
        
    def __init__(self, *args, **kwargs):
        super(ServerAdminForm, self).__init__(*args, **kwargs)

    def save(self, commit=True):
        server = super(ServerAdminForm, self).save(commit=commit)
I'm trying to override the save method so that it saves the servers selected on the form. I feel like I'm almost there, but anything I've tried hasn't worked. Any suggestions?

raymond
Mar 20, 2004
Why does ServerAdminForm have a "servers" field? There's no such field on the model. The only model there with a "servers" field is Profile. Should you be looking at ProfileAdmin instead?

Anyway, do you know about this? https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.filter_horizontal

code:
class ProfileAdmin(admin.ModelAdmin):
    filter_horizontal = ('servers',)
I am confused by your code so I might be way off.

raymond
Mar 20, 2004

Puddy Dumplins posted:

I know how to get class_def, but I'm not exactly sure how to loop over the fields of that class, much less knowing how to check what type of class they are.

Does anyone have an idea of how to do this?

How about something like this:
code:
def create_instance(model, data):
    real_data = {}
    for field_name, value in data.iteritems():
        field = model._meta.get_field(field_name)
        if field.rel:
            value = field.rel.to.objects.get(**value)
        real_data[field_name] = value
    return model(**real_data)

fields = {
    'name': 'Franky',
    'type': {'name': 'Soldier'},
    'location': {'name': 'France'},
}
create_instance(Unit, fields)

xpander
Sep 2, 2004

raymond posted:

Why does ServerAdminForm have a "servers" field? There's no such field on the model. The only model there with a "servers" field is Profile. Should you be looking at ProfileAdmin instead?

Anyway, do you know about this? https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.filter_horizontal

code:
class ProfileAdmin(admin.ModelAdmin):
    filter_horizontal = ('servers',)
I am confused by your code so I might be way off.

You're right about the form, I should have named it ProfileAdminForm. However, I don't think that changes anything functionally. I took a look at filter_horizontal, and it sounds exactly like a FilteredSelectMultiple widget, so I'm already using that. My issue is essentially that I am using a "through" table, ServerGroup, to store the servers tracked in a profile. Because of that, from what I've read, a typical save_m2m() doesn't work, as it doesn't handle saving the through table's data. I just don't know how to get the servers selected from the widget, then save them along with the profile into the ServerGroup table.

Edit: to be more specific, when I try to save the form, the error I get is: Cannot set values on a ManyToManyField which specifies an intermediary model. Use monitor.ServerGroup's Manager instead. What I'm having trouble with is using the manager to save that data - I don't know how to get the selected servers from the form.

xpander fucked around with this message at 21:37 on Sep 27, 2011

Puddy Dumplins
Apr 10, 2011

raymond posted:

How about something like this:
code:
def create_instance(model, data):
    real_data = {}
    for field_name, value in data.iteritems():
        field = model._meta.get_field(field_name)
        if field.rel:
            value = field.rel.to.objects.get(**value)
        real_data[field_name] = value
    return model(**real_data)

fields = {
    'name': 'Franky',
    'type': {'name': 'Soldier'},
    'location': {'name': 'France'},
}
create_instance(Unit, fields)

Cool! I didn't know about ._meta... thanks buddy!

raymond
Mar 20, 2004
^^^ You're welcome.

xpander posted:

You're right about the form, I should have named it ProfileAdminForm. However, I don't think that changes anything functionally.
You've also got "model = Server" in the form, which changes (perhaps breaks) things. ProfileAdmin should use ProfileForm (IF you must define a custom form) which should use the Profile model.

Do you need to use the "through" table? They are pretty troublesome in the admin.

This works for me:

code:
class Profile(models.Model):
    name = models.CharField(max_length=50, unique=True)
    # Specifying db_table because it already exists.
    # If you can, don't set it at all, and let Django create it.
    servers = models.ManyToManyField(Server, db_table='servers_servergroup')
    limitcount = models.PositiveIntegerField(null=True, blank=True)

    def __unicode__(self):
        return self.name

# Delete the ServerGroup model
code:
class ProfileAdmin(admin.ModelAdmin):
    filter_horizontal = ('servers',)

admin.site.register(Profile, ProfileAdmin)
admin.site.register(Server)

xpander
Sep 2, 2004

raymond posted:

You've also got "model = Server" in the form, which changes (perhaps breaks) things. ProfileAdmin should use ProfileForm (IF you must define a custom form) which should use the Profile model.

Yeah I'd changed that too, though with no luck.

raymond posted:

Do you need to use the "through" table? They are pretty troublesome in the admin.

This works for me:

code:
class Profile(models.Model):
    name = models.CharField(max_length=50, unique=True)
    # Specifying db_table because it already exists.
    # If you can, don't set it at all, and let Django create it.
    servers = models.ManyToManyField(Server, db_table='servers_servergroup')
    limitcount = models.PositiveIntegerField(null=True, blank=True)

    def __unicode__(self):
        return self.name

# Delete the ServerGroup model
code:
class ProfileAdmin(admin.ModelAdmin):
    filter_horizontal = ('servers',)

admin.site.register(Profile, ProfileAdmin)
admin.site.register(Server)

I just picked up this project, to modify what is currently in use. I can pretty much change whatever I want, it's just a matter of what's simplest for me to do.

I made your suggested changes, though I had to specify the table - syncdb wasn't creating the new table, and the app was complaining that what it wanted was missing. However, reusing the old table works! Thanks a bunch. :)

xpander
Sep 2, 2004
Looking at the next thing to do, I realized I need to add another field to the above. Each server selected will also have a related database table that needs to be stored. Altering the servergroup table itself is no problem, but I'm not sure how to best represent that in the form. Off the top of my head, having a label for each entry in the servergroup table with a textbox beside it to input the table name would work. Does anyone have a more elegant suggestion?

IsotopeOrange
Jan 28, 2003

The new Heroku for Django is Heroku: http://devcenter.heroku.com/articles/django

bitprophet
Jul 22, 2004
Taco Defender

IsotopeOrange posted:

The new Heroku for Django is Heroku: http://devcenter.heroku.com/articles/django

Why would you link that and not the actually pretty great blog post introducing it? :D

As a Pythonista I think this is one of the best descriptions of the language, community and ecosystem ever.

Pardot
Jul 25, 2001




bitprophet posted:

As a Pythonista I think this is one of the best descriptions of the language, community and ecosystem ever.

I'm at heroku, so if anyone here has platform questions, I'm happy to help. I have to admit though that my python-specific skills aren't that great.

I'm really excited that it's official now. We've had python as a (not very secret) beta for a while and that's been going great.

Comrade Gritty
Sep 19, 2011

This Machine Kills Fascists

IsotopeOrange posted:

The new Heroku for Django is Heroku: http://devcenter.heroku.com/articles/django

And a Django Core Dev Response: http://news.ycombinator.com/item?id=3050760

Hanpan
Dec 5, 2004

Any Django devs in the UK recommend any hosting? I've been using Kutoken but I'm not all that impressed.

A A 2 3 5 8 K
Nov 24, 2003
Illiteracy... what does that word even mean?

Hanpan posted:

Any Django devs in the UK recommend any hosting? I've been using Kutoken but I'm not all that impressed.

Isn't WebFaction in the UK? It's pretty good for Django traditional shared hosting.

bitprophet
Jul 22, 2004
Taco Defender

Hanpan posted:

Any Django devs in the UK recommend any hosting? I've been using Kutoken but I'm not all that impressed.

Hopefully you're already aware of it, but ep.io (a PaaS) is UK-based. EDIT: Oh right, they're still invite-only. Still :)

Yay
Aug 4, 2007

A A 2 3 5 8 K posted:

Isn't WebFaction in the UK? It's pretty good for Django traditional shared hosting.

Based in, but not hosted in. Their servers are at The Planet in Texas, or something. 100msec ping in an SSH session can be a proper chore.

Also once you get over a certain number of sites/applications, their panel feels like wading through molasses.

They're very good at support, and the hosting itself is pretty good.

xpander
Sep 2, 2004
I found a bug in my filter_horizontal usage: it won't delete the last item selected. I can move items from left to right without issue, and can delete all but the last selected item and save successfully. However, when I go to remove that last item, I get "Please correct the error below", with the required field being the entire widget, from what I can tell. Is it forcing a 1-item minimum somewhere that I don't know about?

Edit - nevermind, had to add "blank=True" to the appropriate field in that model, problem solved!

xpander fucked around with this message at 23:37 on Sep 29, 2011

a cyberpunk goose
May 21, 2007

Heyo, sanity check!

So I'm using Django to ease database interactions with python (bypassing the "website" aspect entirely in a few areas). I'm using it to do some game programming, serverside stuff.

I'm writing a turn based combat system that keeps track of a healthy amount of data that will be changing a lot. This means that I'm going to be storing snapshots of all the relevant data (equipped items, base stats, player details) in each instance of the fight, in a database object.

One of the things I realized that would be really helpful for me to do, but that I'm here to sanity check, is for some data I could just pickle a python object and throw it into a blob field. Like for example I want to keep track of modifiers applied to people (poison, armor buffs etc), and naturally I want to use a list or something. I could just pickle that list and throw it into a blob field that's called "Modifiers", then unpickle it and have that easy object and it's children later.

Crazy?

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe
Serializing objects into your database is a quick and dirty hack that is only useful when you don't need to query any of that information from the database. You inevitably will want to as your game grows more complicated and then you'll punch yourself in the dick for being so short sighted. This isn't specific to python or Django though.

Usually the only data that you want to store as a blob is stuff that's already compressed like images or zip files. Everything else should really be a part of your data model.

Yay
Aug 4, 2007
Crazy, and not crazy.

Personally, I'd avoid the pickling into a column, in favour of additional models, for the simplistic reason that pickling the list means it's valid at that point in time. You can't easily adapt the data structure or change values in it without writing interim methods to translate it.

This may not be a big issue because you're describing snapshots of player data, I suppose, but it'd make it hard to add in new modifiers, or tweak values, I think.

Django has got pluggable cache backends anyway, many of which, I suspect, pickle whatever is passed in.

Comrade Gritty
Sep 19, 2011

This Machine Kills Fascists
Note: Don't use Pickle for any data that might even remotely come from a User. Unless you like giving your users the ability to execute arbitrary python that is.

a cyberpunk goose
May 21, 2007

HMMMMMMM

Thanks guys, good input, I'll do everything I can to avoid pickling.

What I'm looking at is taking a snapshot of all the relevant skills/items/commonly changed information in this persistent multiplayer world for reference with that particular combat instance. This is because over time the skill/item definitions will change and I want people to be able to take a historical look at their old fights, (and also incase a staffer updates the item definition mid-fight) so I figure if I pickle a snapshot of some basic values it'll be a pretty sure fire way of achieving that goal instead of making tons of database objects of redundant data for every single fight.

Another way around this could be to keep track of changes automatically, just keep a hash of the definition values as a primary key or something so if some day a fight is initiated where values have changed, the hashes wont line up and it will just make a new one.

Lots of thinking to do, so many ways to do this, and unless I write like 30 paragraphs on this whole system I'm not sure I can give enough information for all you smarties to give perfect input, I'll work with what I get. If anyone's interested though I'll definitely do a huge brain dump and see what I get back. I don't have a lot of experience doing database planning for games.

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe
Definitely don't pickle it then! The object that represents your items or whatever will change in the future as you add more features and your old pickled items in the database won't work anymore!

I made a browswer based game for D&D using Django once, but I never finished it because :effort:.

a cyberpunk goose
May 21, 2007

MEAT TREAT posted:

Definitely don't pickle it then! The object that represents your items or whatever will change in the future as you add more features and your old pickled items in the database won't work anymore!

The item definitions will change but they are simple key:value pairs. The functionality of the storage class doesn't change really.

Lemme give some examples of item definitions and how much they can vary and maybe someone can explain to me a good way to store this information in a database.

code:
; file 1: fireball.ini
name=Fireball
desc=An explosive and superheated ball of generic boring magic hits a dude and he takes damage!
source_animation=cast_spell.ani
source_animation_params=blah,blah

; damage information
damage_type=magic,fire
damage_amount=33
action_type=targeted_projectile
action_effects=apply:modifier:mod_burning,remove:modifier:mod_wet,remove:modifier:mod_frozen
target_type=unit,single
target_range=300
I can keep going but basically every item is going to have relatively different uses of fields and many of them are optional or fringe.

Perhaps I should do this:
  • Store the definition exactly as is as a text field
  • Have a field that is the action's name
  • Have a field that is the hash of the definition (PK)
  • Have a field that is the date this definition was created

That way I can refer to specific points in time of an action's definition if necessary (retrospective) but pull up the latest version of an action definition for new fights.

I can write some setter/getter functions for the model that stores all this so when you say ActionModelInstance["target_range"] it just finds target_range in the definition and returns the value to the right of =

Runtime performance isn't a biggy because none of this is per-frame, nor does it need to scale very high.

Adbot
ADBOT LOVES YOU

Puddy Dumplins
Apr 10, 2011
Mido, you may be interested in this JSONField. I first saw it as part of djangobb, but I think it's actually more common than that. I think its exactly what you are asking for.

code:
class JSONField(models.TextField):
    from django.core.serializers.json import DjangoJSONEncoder
    from django.utils import simplejson as json

    """
    JSONField is a generic textfield that neatly serializes/unserializes
    JSON objects seamlessly.
    Django snippet #1478
    """

    __metaclass__ = models.SubfieldBase

    def to_python(self, value):
        if value == "":
            return None

        try:
            if isinstance(value, basestring):
                return json.loads(value)
        except ValueError:
            pass
        return value

    def get_db_prep_save(self, value):
        if value == "":
            return None
        if isinstance(value, dict):
            value = json.dumps(value, cls=DjangoJSONEncoder)
        return super(JSONField, self).get_db_prep_save(value)
And here's how you can add it to South:
code:
if 'south' in settings.INSTALLED_APPS:
    from south.modelsinspector import add_introspection_rules
    add_introspection_rules([], ['^djangobb_forum\.fields\.JSONField'])
Oh, and to the guy asking about Webfaction: I use it to run my website, and I've found it to be pretty good! Just my 2 cents.

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