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
raymond
Mar 20, 2004

LuckySevens posted:

Yeah, I just wrote the view myself, everything works smoothly now except:

code:
    @models.permalink
    def get_absolute_url(self):
        return ('flowplayer.views.videos_detail', (), { 'series': VidSeries.slug,
                    'slug': self.slug })
I can't work out how to get my get_absolute_url working correctly, series is a manytomany with a model called VidSeries, I'm using the slug from that model as part of the url dispatcher, I dpasted the other info here. I can't seem to find any info apart from the official django docs on get_absolute, I've also tried self.series.slug to no avail. Something fundamental I must not be getting here.

Did my suggestion not work?

If your series field was a ForeignKey, then you could use self.series.slug.

But your series field is a ManyToMany field, and your video is linked to possibly more than one VidSeries. It needs to pick just 1 of them so it can make up a URL.

Read this if you haven't already: http://docs.djangoproject.com/en/dev/ref/models/instances/#django.db.models.permalink

Adbot
ADBOT LOVES YOU

LuckySevens
Feb 16, 2004

fear not failure, fear only the limitations of our dreams

Oh sorry, totally missed your last post for some reason. That suggestion works, thanks for that, I'm understanding now the philosophy behind it now.

Sock on a Fish
Jul 17, 2004

What if that thing I said?
Is anyone familiar with initial_data? I've reviewed the docs on it and it seems straightforward enough, but I can't get it to work.

I've got a file called initial_data.yaml, it looks like this:
code:
- model: django.contrib.auth.models.Group
  pk: 1
  fields:
    name: app_admin
    
- model: django.contrib.auth.models.Group
  pk: 2
  fields:
    name: services
I've tried placing it by itself in the root of the project, the root of the app, in a 'fixtures' folder in the root of the project and the root of the app, but so far nothing has gotten recognized by a syncdb command. The only thing I can think of is that the django.contrib.auth.models.Group model isn't supported as a fixture, but I just can't believe that could be real, there are so many testing scenarios where you'd want to verify that someone has some quality before proceeding to perform some action.

Where am I going wrong?

Sock on a Fish
Jul 17, 2004

What if that thing I said?

Sock on a Fish posted:


Figured it out, Django doesn't even try to deserialize YAML if PyYAML isn't installed. Installed PyYAML, got another error about invalid model name, used dumpdata to find that the actual name is 'auth.group', and now everything works proper.

inveratulo
May 14, 2002
wat

inveratulo posted:

This is really a better way of thinking about things than how I was going about it. But it still doesn't address the edge cases of say when I want a job to run daily, except on Sundays.

Any other suggestions? If I can create a model to select a single value from a list, I should be able to create a model that select multiple values from a list without having to hack the form route, right?

LuckySevens
Feb 16, 2004

fear not failure, fear only the limitations of our dreams

Not sure if I'm being to clever here or not clever enough, trying to design a menu templatetag based on tree of my manytomany linked models, by returning the titles into a tree-like dictionary queryset:

code:
v = VidCategory.objects.all()
s = VidSeries.objects.all()
f = Videos.objects.all()

options = {'category': [], 'series': []}

for obj in v:
    options['category'].append(dict({obj.title: [(dict({ser.title: [vid.name for vid in f.filter(series__title=ser.title)]}))
                                                    for ser in s.filter(categories__title=obj.title)]})) 
                                            
    
for ser in s:
    options['series'].append(dict({ser.title: [vid.name for vid in f.filter(series__title=ser.title)]}))
Any foreseeable problems doing it this way? Just using generates and iterating over everything, only going to have maybe 6 categories, with 3 series each, with 4 videos.

edit: code revised and tested, now delivers the tree dict structure i want

LuckySevens fucked around with this message at 20:32 on May 18, 2010

Yay
Aug 4, 2007

LuckySevens posted:

Any foreseeable problems doing it this way?
Forseeable problem: its not re-usable. Its neat, in a 'hey-this-is-perfect-for-this-project' way, but not beyond that.

An entirely opposite approach: use generic relations to tie an object (of any type) to a 'MenuItem' model; provide a context processor or templatetag to fetch. Can be taken from project to project, extending as you need it.

An even more opposite approach: find a re-usable app that does what I just said.

inveratulo posted:

Any other suggestions? If I can create a model to select a single value from a list, I should be able to create a model that select multiple values from a list without having to hack the form route, right?
Its certainly a bit more tricky; I'm pondering it. I suppose the problem is, that doing it every X but not Y isn't massively useful; it mostly only applies to days. For example, performing a ScheduledJob every month, but not March, isn't likely. Its mostly days its appropriate to.

inveratulo
May 14, 2002
wat

Yay posted:

Its certainly a bit more tricky; I'm pondering it. I suppose the problem is, that doing it every X but not Y isn't massively useful; it mostly only applies to days. For example, performing a ScheduledJob every month, but not March, isn't likely. Its mostly days its appropriate to.

Well, I am trying to create something that can hold its own with crontab, hopefully replacing it entirely in the future. What I ended up doing was creating a day and month object, and generating 7 and 12 instances of each, respectively. Then my job objects have a many-to-many relationship with these days or months. 9am and 3:30pm every second and third Tuesday of months not ending in a "-ember"? Not a problem!

e: i may put in a schedule object layer and have my jobs subscribe to them. So I can have like, multiple jobs subscribed to a daily midnight job or something like that.

Sock on a Fish
Jul 17, 2004

What if that thing I said?
Does anyone use fabric?

I'm trying to get fabric, in one operation, to selectively apply certain sub-operations only to a subset of hosts. e.g., when deploying I want to copy new files to all application servers, but I only want to syncdb, do a south migration, and install some cron jobs on one host.

I tried to accomplish this by defining two roles, one 'primary_host' that updates the db and has cron jobs, and another 'whole_cluster' that consists of every app server. I've got one function that's decorated with an @roles('primary_host') that contains calls to a bunch of other functions, some which are decorated the same and some which are decorated @roles('whole_cluster').

The problem is, when I run that one big function, the actions are only performed on the primary_host. Am I doing this wrong, or is this a limitation of fabric? Right now it seems like I'm going to have to write a shell script that calls fabric with different host arguments.

Sock on a Fish
Jul 17, 2004

What if that thing I said?
Eh, wasn't that bad, I'd still like to keep it all in Fabric if that's what I'm using anyway:

code:
#!/bin/bash

fab enable_maintenance_mode --roles=whole_cluster

# turn on maintenance mode in settings.py in current working directory
sed -r -e 's/MAINTENANCE_MODE = False/MAINTENANCE_MODE = True/g' settings.py

fab update_application_files --roles=whole_cluster

fab update_primary_host --roles=primary_host

fab disable_maintenance_mode --roles=whole_cluster

bitprophet
Jul 22, 2004
Taco Defender

Sock on a Fish posted:

The problem is, when I run that one big function, the actions are only performed on the primary_host. Am I doing this wrong, or is this a limitation of fabric?

Limitation of Fabric: http://code.fabfile.org/issues/show/21 (a generic ticket, but covers this overall issue to some degree.) There will be some way to do it in the future (e.g. execute('function_name', ['host', 'list'])) but right now it's not easily possible.

You can fake it on your own for the time being by routing around the main execution loop: when run() and sudo() execute, they actually just check env.host_string. Multi-host execution (either manual or in Fabric's own main loop) is thus just effected by looping over a host list and setting that variable, then calling the task function.

So you could do e.g.
code:
from fabric.api import *

def go():
    # single host crap
    with settings(host_string='primary_host'):
        primary_host_only1() 
        primary_host_only2() 

    # multiple host crap
    for host in ['host1', 'host2', 'primary_host']:
        with settings(host_string=host):
            whole_cluster1()
            whole_cluster2()
            whole_cluster3()

def primary_host_only1():
    # crap that should only run on the single host

def primary_host_only2():
    # crap that should only run on the single host, part 2

def whole_cluster1():
    # crap that applies to everyone

def whole_cluster2():
    # crap that applies to everyone, part 2

def whole_cluster3():
    # crap that applies to everyone, part 3
Then invoke as:
code:
$ fab go
Note lack of any decorators or roles -- you're driving the "host list" mechanisms yourself here so they're not necessary.

Hope that makes some sense.

nbv4
Aug 21, 2002

by Duchess Gummybuns
So they announced djangocon. I was thinking of going until Is saw how much it costs. Five hundred freaking dollars per person. Why does it cost so much? I haven't been to a "con" like this before, but that seems like a lot of money. I've been to job fairs before that costs $100 which I thought was a lot, even though the price included a fancy catered lunch. Does Djangocon at least include kick rear end food? If one hundred people show up, thats $50,000 of gross income. Does it really costs that much money put put on a "con" of this nature?

MonkeyMaker
May 22, 2006

What's your poison, sir?
Does anyone have any suggestions for how I can catch the non-hashed password when a user updates their password? I need to sync it with Convio and I've been using signals for catching profile changes. The changed password is the only real stumbling block I have left on this point.

Jonnty
Aug 2, 2007

The enemy has become a flaming star!

MonkeyMaker posted:

Does anyone have any suggestions for how I can catch the non-hashed password when a user updates their password? I need to sync it with Convio and I've been using signals for catching profile changes. The changed password is the only real stumbling block I have left on this point.

Firstly, you shouldn't be storing unhashed passwords - I'm assuming you want to put the password into an API which hashes it internally. First, look for a way of passing in the hashed password. Failing that, you could just extend the registration form and add a hook in for what you want to do - I don't know what the best practices for that would be though I'm sure someone else will.

MonkeyMaker
May 22, 2006

What's your poison, sir?

Jonnty posted:

Firstly, you shouldn't be storing unhashed passwords - I'm assuming you want to put the password into an API which hashes it internally. First, look for a way of passing in the hashed password. Failing that, you could just extend the registration form and add a hook in for what you want to do - I don't know what the best practices for that would be though I'm sure someone else will.

I'm not storing an unhashed password anywhere. I'm sending it, securely, to Convio who will hash it in their own way and store it.

The registration form won't help me either since I only care, at this point, about password changes. I'm sure I could write my own view for it, or edit Django's existing view, but I'd really rather not since that fucks with forward-compatability.

nbv4
Aug 21, 2002

by Duchess Gummybuns

MonkeyMaker posted:

Does anyone have any suggestions for how I can catch the non-hashed password when a user updates their password? I need to sync it with Convio and I've been using signals for catching profile changes. The changed password is the only real stumbling block I have left on this point.

I'd look into modifying the form field to send the value off somewhere in the clean() function. Sounds really dirty though (sending off plain text passwords that is)

Or maybe have an ajax request send the password off by scraping it off the text field in the HTML.

m0nk3yz
Mar 13, 2002

Behold the power of cheese!

nbv4 posted:

So they announced djangocon. I was thinking of going until Is saw how much it costs. Five hundred freaking dollars per person. Why does it cost so much? I haven't been to a "con" like this before, but that seems like a lot of money. I've been to job fairs before that costs $100 which I thought was a lot, even though the price included a fancy catered lunch. Does Djangocon at least include kick rear end food? If one hundred people show up, thats $50,000 of gross income. Does it really costs that much money put put on a "con" of this nature?

I don't know why you're putting "con" in quotes.

But to your question; I've found most python conferences well worth the price of admission - but I would note that prices of the DjangoCon tickets is surprising to me. Tickets to a lot of conferences have been going up though - and typically, the tickets are not profitable to the organizers - the money goes to pay for the hotel rooms and costs, and the most expensive item - food and snack catering.

Really, seeing behind the scene at Pycon as I have, it doesn't surprise me to see expensive tickets (even if the cost is more than I'd expect) for DjangoCon - the hotels (and especially, the catering people) love to stick it in your throat whenever they can.

So, essentially I can see justification for the price from a pure contract-with-the-hotel-and-catering-people standpoint, I imagine the organizers found the best hotel deal they could (or were locked into a multi year contract) and are paying for it now. Unless you're in a good negotiating position, hotels and the other groups will totally molest you.

As for "will the content be worth it" - I don't even miss a beat when I say yes. It will be. Like PyCon, the content will be high quality, there will be a lot of it, and you will get the best thing ever out of it - exposure to other people working with it. The networking, sprinting and hallway track is almost worth it alone.

king_kilr
May 25, 2007
My boss is running the conference, so I'll say what I can. Basically there are a LOT of holdover contracts this year that they couldn't renegotiate.

raymond
Mar 20, 2004

MonkeyMaker posted:

Does anyone have any suggestions for how I can catch the non-hashed password when a user updates their password? I need to sync it with Convio and I've been using signals for catching profile changes. The changed password is the only real stumbling block I have left on this point.

This is totally untested but you could try putting this, or something like it, into an __init__.py file of an installed app. It could be extended to work with more than just the set password form. I suppose it could break in future versions of django, but it's less likely to break than replacing code.

code:
from django.contrib.auth.forms import SetPasswordForm

def hijack_password(func):
    def wrapper(self, *args, **kwargs):
        print 'I can do something with this password: %s' % self.cleaned_data['new_password1']
        return func(self, *args, **kwargs)
    return wrapper

SetPasswordForm.save = hijack_password(SetPasswordForm.save)
This doesn't seem very safe (what if the save fails?) but whatever, it's an idea!

raymond fucked around with this message at 11:19 on May 21, 2010

inveratulo
May 14, 2002
wat
Hey guys, I am having problems with the admin model that I am overriding. Basically, in my models.py I have something this:
code:
...
JOB_PERIOD	=	(
	('0','Yearly'),
	('1','Monthly'),
	('2','Weekly'),
	('3','Daily'),
	('4','Hourly'),
)
...

class Job(models.Model):
... (some other stuff here) ...
	period	=	models.IntegerField(default=JOB_PERIOD[2][0],choices=JOB_PERIOD,max_length=1,)	
and then in my admin.py, I have a:
code:
class JobAdmin(admin.ModelAdmin):
	list_display		=	('name','descr','period','time')
	search_fields		=	('name','descr',)
	list_filter		=	('time','period','category',)
	filter_horizontal	=	('month','day',)
So, when the admin interface loads up, the list_filter portion properly lists the contents of the 'period' tuple, but the list_display does not. It just has a column of "(none)". Any ideas on how to fix this?

Sock on a Fish
Jul 17, 2004

What if that thing I said?

bitprophet posted:

Hope that makes some sense.

Perfect sense, thanks. That reminds me of figuring out that the cd() context manager doesn't process absolute paths correctly, so before every cd('/some/abs/path') I'd have to set env.cwd to ''.

bitprophet
Jul 22, 2004
Taco Defender

Sock on a Fish posted:

Perfect sense, thanks. That reminds me of figuring out that the cd() context manager doesn't process absolute paths correctly, so before every cd('/some/abs/path') I'd have to set env.cwd to ''.

Hmm. That should only be the case if env.cwd is set to a non-empty value beforehand, such as if you were to call cd within another cd block. Can you verify whether that's what's going on?

Edit: If we have to do more than another back-and-forth on this, given it's not that Django related, maybe I should make a Fabric thread. Then again I can't imagine that many goons use it, so maybe we should just take it to email or PM.

raymond
Mar 20, 2004

inveratulo posted:

Hey guys, I am having problems with the admin model that I am overriding. Basically, in my models.py I have something this:
code:
...
JOB_PERIOD	=	(
	('0','Yearly'),
	('1','Monthly'),
	('2','Weekly'),
	('3','Daily'),
	('4','Hourly'),
)
...

class Job(models.Model):
... (some other stuff here) ...
	period	=	models.IntegerField(default=JOB_PERIOD[2][0],choices=JOB_PERIOD,max_length=1,)	
and then in my admin.py, I have a:
code:
class JobAdmin(admin.ModelAdmin):
	list_display		=	('name','descr','period','time')
	search_fields		=	('name','descr',)
	list_filter		=	('time','period','category',)
	filter_horizontal	=	('month','day',)
So, when the admin interface loads up, the list_filter portion properly lists the contents of the 'period' tuple, but the list_display does not. It just has a column of "(none)". Any ideas on how to fix this?

Just a stab in the dark, but maybe try changing your JOB_PERIOD tuple to use numbers instead of strings (change '0' to 0, '1' to 1, etc). I think Django converts your string numbers fine when saving the model, but when loading the model from the database it gets back integers.

Sock on a Fish
Jul 17, 2004

What if that thing I said?

bitprophet posted:

Hmm. That should only be the case if env.cwd is set to a non-empty value beforehand, such as if you were to call cd within another cd block. Can you verify whether that's what's going on?

Edit: If we have to do more than another back-and-forth on this, given it's not that Django related, maybe I should make a Fabric thread. Then again I can't imagine that many goons use it, so maybe we should just take it to email or PM.

Oh yeah, it was a cd within a cd. I had some functions that were executing other functions within a cd context, and within those functions themselves there was a cd context specified as well. That really threw me, I assumed that any path starting with '/' would be interpreted as absolute.

bitprophet
Jul 22, 2004
Taco Defender

Sock on a Fish posted:

Oh yeah, it was a cd within a cd. I had some functions that were executing other functions within a cd context, and within those functions themselves there was a cd context specified as well. That really threw me, I assumed that any path starting with '/' would be interpreted as absolute.

Thanks, that makes sense now, and I agree that your assumption should have been correct. Ticket :)

inveratulo
May 14, 2002
wat

raymond posted:

Just a stab in the dark, but maybe try changing your JOB_PERIOD tuple to use numbers instead of strings (change '0' to 0, '1' to 1, etc). I think Django converts your string numbers fine when saving the model, but when loading the model from the database it gets back integers.

Thanks Raymond this worked like a charm.

Mulozon Empuri
Jan 23, 2006

So.. Shopping apps in Django?

I've found LFS and Satchmo so far. Any of you guys have any experience with those two? Any other shop apps I should be checking out?

king_kilr
May 25, 2007
One of the guys I work with use{d,s} a forked, very early Satchmo, successfully. In general the satchmo guys seem pretty smart, but that's as much as I can intelligibly say.

Mulozon Empuri
Jan 23, 2006

Cool, thanks for the feedback.

I need to get away from the horror that is a site build on Joomla. Now I've just got to convince people that Python/Django is a valid choice.

Avenging Dentist
Oct 1, 2005

oh my god is that a circular saw that does not go in my mouth aaaaagh
Is it worth using one of the Django blogging packages out there or would it be just as simple to write one myself? I know Django well enough, but I'm not sure what malarkey people put in their Django-based blogs, so maybe it'd be a lot of work to write a decent one!

Corollary: if I should use one of the already-existing ones, which one is least bad? (I have had less than stellar experiences with stuff built on top of Django.)

NoDamage
Dec 2, 2000

Avenging Dentist posted:

Is it worth using one of the Django blogging packages out there or would it be just as simple to write one myself? I know Django well enough, but I'm not sure what malarkey people put in their Django-based blogs, so maybe it'd be a lot of work to write a decent one!

Corollary: if I should use one of the already-existing ones, which one is least bad? (I have had less than stellar experiences with stuff built on top of Django.)
I'd love to see an answer to this too. All of the Django blogging plugins I've seen are either horrendously overcomplicated (django-mingus, the first installation step in a loving blog shouldn't consist of installing 30 other plugins) or too simplified. I haven't found any I'm happy with.

A lot of people recommend rolling your own. But come on, it's 2010, and a blog has a bunch of features (pingbacks, feeds) that we shouldn't have to waste our rewriting.

bitprophet
Jul 22, 2004
Taco Defender

NoDamage posted:

(django-mingus, the first installation step in a loving blog shouldn't consist of installing 30 other plugins)

In its author's defense, the point of Mingus is to embrace the Django "reusable apps" philosophy. It's not that they're plugins to some core app, it's that the core app is simply a tiny bit of glue to hold all of the individual components together.

So where e.g. Wordpress core implements comments, static pages, permalinks, RSS feeds, and so forth, and then has plugins, Mingus is just a collection of what its author perceives to be the best available Django comments app, permalink app, RSS feed app, etc. So to knock it for "requiring a bunch of plugins" is to miss the point of the app.

At least, that's my understanding; I haven't used it myself, only read up on it a bit. I think king_kilr has though?

king_kilr
May 25, 2007
I've never used it, but mingus is very much designed for developers, not being an end-user solution like wordpress.

m0nk3yz
Mar 13, 2002

Behold the power of cheese!

bitprophet posted:

In its author's defense, the point of Mingus is to embrace the Django "reusable apps" philosophy. It's not that they're plugins to some core app, it's that the core app is simply a tiny bit of glue to hold all of the individual components together.

So where e.g. Wordpress core implements comments, static pages, permalinks, RSS feeds, and so forth, and then has plugins, Mingus is just a collection of what its author perceives to be the best available Django comments app, permalink app, RSS feed app, etc. So to knock it for "requiring a bunch of plugins" is to miss the point of the app.

At least, that's my understanding; I haven't used it myself, only read up on it a bit. I think king_kilr has though?

You're pretty much correct - mingus is a pile of reusable apps under one banner, it doesn't implement a lot on it's own. I tend to use it piecemeal as I need for other applications. If I didn't have a ton of wordpress history, I'd be over on mingus right now personally.

Sock on a Fish
Jul 17, 2004

What if that thing I said?
Does anyone have insight on keeping their Django code readable and testable? I read through Clean Code a couple of months back and have been trying to keep from letting my code get bloated and too multi-purposed, but it's not readily apparent what the best way to do that is in Django.

I've started to define functions within my view functions to better separate layers of abstraction while keeping everything logically grouped together as a single unit, but I can't figure out how to use those from outside of the function, which means I can't write tests for them.

Is the only way to just have a whole bunch of functions in the same namespace as your view function? Maybe define each view and associated functions within a discrete Python file?

It seems like it'd be easier if every view was a class instead of a function.

MonkeyMaker
May 22, 2006

What's your poison, sir?

Sock on a Fish posted:

It seems like it'd be easier if every view was a class instead of a function.

So write class-based views? http://lmgtfy.com/?q=class-based+views+django

Sock on a Fish
Jul 17, 2004

What if that thing I said?

MonkeyMaker posted:

So write class-based views? http://lmgtfy.com/?q=class-based+views+django

Is that what most people do? It doesn't have to be class-based, and honestly reading through those results class-based views look like a kludgy hack that could possibly be broken in later Django releases.

edit: I'm thinking it might make more sense to make a views folder, and then for each view or set of closely related views a separate file.

Sock on a Fish fucked around with this message at 21:08 on Jun 3, 2010

nbv4
Aug 21, 2002

by Duchess Gummybuns
the way i usually do it is like this:

code:
def some_view(request, other_vars):
    controller = MyController(request)
    some, vars = blah(other_vars, None)

    if request.POST:
        return controller.handle_post()
    else:
        return controller.show_page_as_response(some,vars)

Basically I do all the dispatching stuff in the view function, and any actual programming logic goes into it's own class so it can be subclassed and stuff. But I don't have the whole view as a class because that introduces all sorts of complexity.

LuckySevens
Feb 16, 2004

fear not failure, fear only the limitations of our dreams

fixed, didnt use the correct decorator

LuckySevens fucked around with this message at 06:47 on Jun 4, 2010

Adbot
ADBOT LOVES YOU

Stabby McDamage
Dec 11, 2005

Doctor Rope
I have an asinine template question that I can't figure out.

I have a list of objects and I want to put the 'name' field of each, quoted, into a comma-delimited list. For example, if I have 3 stooges objects, I'd want the output:

'larry','moe','curly'

Well, if I just had a list of strings instead of objects, I'd do:

'{{string_list|join:"','"}}'

But they're objects, so I use a for loop, as in:

{% for obj in obj_list %}'{{obj.name}}',{%endfor%}

That's good, except it leaves a trailing comma. I can crudely fix that, though:

{% for obj in obj_list %}'{{obj.name}}'{%if not forloop.last%},{%endif%}{%endfor%}

That seems excessively verbose for such a simple operation. Isn't there a better way?

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