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
No Safe Word
Feb 26, 2005

For those who were lost as I was: http://www.djangopony.com/

My Little Pwny

Adbot
ADBOT LOVES YOU

king_kilr
May 25, 2007
DjangoCon videos are starting to come out: http://www.youtube.com/results?search_query=djangocon&search=tag

greenskeleton
Apr 5, 2003
http://www.youtube.com/view_play_list?p=D415FAF806EC47A1

A more comprehensive list.

Typh
Apr 18, 2003

LAY EGG IS TRUE!!!
Woo! As fascinating as Malcolm's talk on the ORM was, I couldn't wait to get to watch James Bennett's reusable apps presentation (and the schema panel!). I didn't realize until I got there that presentations were happening at the same time.

Wulfeh
Dec 1, 2005

The mmo worth playing: DAoC
Alright, got another problem that I am not quite sure how to approach.

We are trying to split up a section of the site in to a multi-step process so it is easier for user's to complete the information, obviously this looks like a job for FormWizard.

The problem I am having trouble with is that, not only do we take information for a model via form fields, but there is one part that requires the user to enter a search query and pick a person based on that query.

What I don't know how to do is maintain the form-wizards state when the user goes for a search, and picks a user. If I leave the current url, they lose all the data entered, so you can't re-enter the wizard from where they left off.

As an added bonus, they should be able to search and pick people several times.

One idea I had was to add a form to the wizard where they entered their search queries and it would return back another form with a MultipleChoiceField with all the queries and they can choose who they wanted, but that could be a little difficult for the end user to see who they are choosing.

bitprophet
Jul 22, 2004
Taco Defender

Wulfeh posted:

Alright, got another problem that I am not quite sure how to approach.

This basically screams for Ajax; I actually did something very similar with my first major Django app, where the list of potential objects one could select on a form was HUGE and would not work as a dropdown, thus I had to make one of those find-as-you-type deals, which of course uses JS callbacks to the server.

If I read you correctly, that's what you want; you could work around the use of Ajax by saving temporary data about the form, but that can get super messy super fast, so Ajax is (IMO) absolutely a better approach.

Wulfeh
Dec 1, 2005

The mmo worth playing: DAoC

bitprophet posted:

AJAX

Another clincher is that we try to stay as far away as possible from AJAX / JS calls to the DB. Reason is because we are diligent in being handicap friendly. This means screen readers have to be able to go through this and be A-Ok at reading what's going on.

I think we may end up just using the form wizard for the model, saving it, then redirecting with the id in the url to the next step, and just have that step be repeatable.

We had discussed this idea in length, but put it down at first because we felt it wouldn't be coherent enough programatically, but seems to be one of the few options.

bitprophet
Jul 22, 2004
Taco Defender

Wulfeh posted:

Another clincher is that we try to stay as far away as possible from AJAX / JS calls to the DB. Reason is because we are diligent in being handicap friendly. This means screen readers have to be able to go through this and be A-Ok at reading what's going on.

In that case, then yea, you're going to have to do what I think you're describing, w/r/t using the DB to preserve some state during form fillout. Kind of a pain, but that's the breaks with HTTP, isn't it :(

dimebag dinkman
Feb 20, 2003

The Django docs make a big deal out of the fact that you shouldn't serve static files through Django. That makes sense, but what if I want to only allow the download of a large static file for people authenticated and in a certain group etc.? Is there actually any satisfactory way of having Django handle a request initially, and then have it pass control over the fastest method available to send a static file? (I'm using lighttpd + FastCGI, currently.)

I'd also like to hear any advice about custom form fields / widgets that are more complex than the framework seems to expect. For example, if I have a custom field with a "clean" method that relies on knowing who the current user is - how would that work? All I get are the "data" and "files" parameters, ideally I'd need the HTTPRequest. Is there any way to get at it?

deimos
Nov 30, 2006

Forget it man this bat is whack, it's got poobrain!

dimebag dinkman posted:

The Django docs make a big deal out of the fact that you shouldn't serve static files through Django. That makes sense, but what if I want to only allow the download of a large static file for people authenticated and in a certain group etc.? Is there actually any satisfactory way of having Django handle a request initially, and then have it pass control over the fastest method available to send a static file? (I'm using lighttpd + FastCGI, currently.)

http://trac.lighttpd.net/trac/wiki/Docs:ModSecDownload

http://wiki.codemongers.com/NginxXSendfile


Basically you change the headers and shazzam proxied download. (actually lighty's is a bit more complicated but who cares, use nginx)

duck monster
Dec 15, 2004

Mod python also lets you write custom authentication drivers for apache using python

So you can write a handler that covers a particular directory authing off your models, but passing the request back into apache.

Not sure how it works with lighthttpd.

deimos
Nov 30, 2006

Forget it man this bat is whack, it's got poobrain!

duck monster posted:

Mod python

gently caress mod_python TBH. Seriously, don't use it.

Allie
Jan 17, 2004

dimebag dinkman posted:

The Django docs make a big deal out of the fact that you shouldn't serve static files through Django. That makes sense, but what if I want to only allow the download of a large static file for people authenticated and in a certain group etc.? Is there actually any satisfactory way of having Django handle a request initially, and then have it pass control over the fastest method available to send a static file? (I'm using lighttpd + FastCGI, currently.)

deimos obnoxiously alluded to it: X-Sendfile. Enable that in your mod_fastcgi settings and when your application sends an X-Sendfile header, lighttpd will discard your application's response and serve up the file the header specifies. I believe it just needs to be an absolute path.

Be sure to set the Content-Type on the response though, as I don't think lighttpd does it for you in this case. It does set the Content-Length itself, however.

There's also an Apache module for X-Sendfile support called mod_xsendfile.

duck monster
Dec 15, 2004

deimos posted:

gently caress mod_python TBH. Seriously, don't use it.

The alternative is mod_perl, or writing a C handler. gently caress that. mod_python is goofy, but it works. This isnt a content handler, its an authentication handler.

The only other way I can see it being done is to write a custom PAM handler using, I dunno, something.

bitprophet
Jul 22, 2004
Taco Defender

duck monster posted:

The alternative is mod_perl, or writing a C handler. gently caress that. mod_python is goofy, but it works. This isnt a content handler, its an authentication handler.

The only other way I can see it being done is to write a custom PAM handler using, I dunno, something.

To be fair, use of WSGI, with any server (i.e. mod_wsgi with Apache, or whatever the nginx equiv is) is becoming more popular lately, and a decent number of people also use FCGI.

But, deimos' personal bad experiences with it aside (assuming I remember the source of his complaints correctly :)), mod_python is still the "gold standard" for now, with mod_wsgi being the next closest, I believe. Many people claim WSGI can get them better memory usage, and it (along with FCGI) can get you better security as well, so it's definitely worth a look.

deimos
Nov 30, 2006

Forget it man this bat is whack, it's got poobrain!

Milde posted:

deimos obnoxiously alluded to it

Eh? how was I obnoxious? I gave him relevant links and gave a very concise explanation of how the technique works (for nginx), neither link lacked explanations as to how they worked so there was no need to write :words:.


bitprophet posted:

To be fair, use of WSGI, with any server (i.e. mod_wsgi with Apache, or whatever the nginx equiv is) is becoming more popular lately, and a decent number of people also use FCGI.

WSGI is the best thing for hosting django apps. The only problem is that the django devs say it's the best way to host django apps (just go to #django or the django-users mailing list), but it seems they don't want to put it on the docs because not all web servers have WSGI available to them.

There are very few reasons to use mod_python, and none of them really make sense to me, because most of them involve using parts of Apache that are normally not exposed to web apps. I would personally forego apache/django and switch to twisted/nevow for that degree of control, or, I would separate the things that require you to control apache into their own applications. But I can see a very small subset of projects needing it.

dimebag dinkman
Feb 20, 2003

Excellent, thanks for the help, I've got X-LIGHTTPD-Send-File working well.

dimebag dinkman
Feb 20, 2003

Is there an elegant approach - either in the standard system that I've missed, or with a recommendable extension - to handling submit buttons that post back to the same page, and are intended to cause some minor action while otherwise just redrawing the page?

For example: say I want to accept a list of strings on a form. (Ignoring the Javascript-based progressive enhancement for now, focusing just on the basic Javascriptless model.) When you first load the page you see an empty text field and an "Add" button, like this:
code:
[         ] [Add]
You type "one" into the field and click Add. The page's form posts back to itself and it reloads, but there is a new row added:
code:
[one      ] [X]
[         ] [Add]
Clicking the X button next to an existing row removes it, also by doing a postback and reloading the page. I'd like to make this a reusable component I can easily drop in different places, sticking to the DRY principle and keeping the code clean and logical, etc.

I had a look at the Forms system, but as I understand it:
-A Widget is intended to render a data-capturing piece of HTML, given a name-ID and optionally a value;
-A (form) Field is responsible for validating the value of a Widget.

Neither of these things feel like an appropriate place to handle a "mutating" action triggered by a postback submission. And that's fine, I'm probably looking in the wrong place. But where is the right place?

bitprophet
Jul 22, 2004
Taco Defender

dimebag dinkman posted:

Is there an elegant approach - either in the standard system that I've missed, or with a recommendable extension - to handling submit buttons that post back to the same page, and are intended to cause some minor action while otherwise just redrawing the page?
<snip>

I think you want to look into FormSets, they're designed to basically be collections of identical Forms, so in this case you'd make a ItemForm with a single text field, and a FormSet of ItemForms, and then maybe a form containing that FormSet plus the "entry" text field (although I am not too up on exactly how you use/compose FormSets with Forms -- I just know that a FormSet == 0..N identical Forms).

If it's not possible to "compose" FormSets within Forms, then you'd just want the FormSet plus manual stuff for the entry field (which would not be much at all, the tiny HTML snippet plus controller logic to look for request.POST['new_entry_field_lol'] and then make a new object or Form out of it.

dimebag dinkman
Feb 20, 2003

drat, sorry, I think I overspecified the problem - the adding and removing rows stuff was kind of a red herring. (Thank you, though - FormSets do look pretty useful, it's just not exactly what I was getting at.) I was trying to think of a reasonable real-world example. So I'll go with a ridiculous fake one instead:
code:
[         ] [Reverse!]
When the Reverse! button posts back, the value of the text field is changed so its characters are reversed.

Now, yeah, in a one-off case I would do something like this in the request handler:
code:
if request.POST.get('reverse_button'):
    # modify the reverse_me field's value, and render
    # the form with this modified data instead of request.POST directly
...but this is the bit that bothers me, because if I want my ludicrous reverse-button field in *loads* of forms across the site, not just on one page - and possibly even in several places on the same page (but you will have to sign up for that) - it means a lot of duplicated code. Instead I would like some way of defining it once and dropping it into places as easily as a Field.

dimebag dinkman fucked around with this message at 22:57 on Oct 1, 2008

bitprophet
Jul 22, 2004
Taco Defender
I spent a loooong time writing up some general theory about this (hinging on how Django is "just Python" and you can therefore just write a function to call when you want this logic applied -- it would take in the request and return a dictionary to be merged into your context dict for the template render) but then realized the answer is even simpler:

Just write a Form class :downs: (that :downs: is me, not you)

The trick is that a Form will happily gobble up any dictionary whatsoever, and will only be interested in the form fields and/or validation methods you've defined on it -- it ignores everything else. Thus, for any arbitrary form submission (including none at all, of course, which is an empty dict) you can make e.g. a ReverseForm expecting your text_to_reverse field, and have its `clean()` method modify the contents of `self.cleaned_data` (see here if you don't already know about it).

In other words, Forms can act as "filters" of a sort on the data they represent. Here's an example for your reversal situation. First, the Form:

code:
from django import forms

class ReverseForm(forms.Form):
    text_to_reverse = forms.CharField(max_length=100, required=False)
    
    def clean(self):
        ttr = self.cleaned_data['text_to_reverse']
        if ttr:
            self.cleaned_data['text_to_reverse'] = ttr[::-1] # No string.reverse :(
        return self.cleaned_data
A potential view:
code:
from myproj.myapp.forms import ReverseForm
from django.shortcuts import render_to_response

def some_random_view(request):
    context = {}
    do_some_shit_with_the_request()
    maybe_update_the_context_who_knows()
    context['reverse_form'] = ReverseForm(request.POST.copy())
    render_to_response('some_template.html', context)
And a potential template:
code:
<html>
<!-- poo poo goes here -->
<form action="" method="post">
{{ reverse_form.text_to_reverse }} <input type="submit" value="press me lol" />
</form>
<!-- other poo poo here -->
</html>
The resulting render will spit out the <input type="text" value="whatevs" /> where the "whatevs" would either be empty (in case of first hit to page) or empty again (if user submitted some other form on the page) or contain the reversed string (if the user filled out and submitted that particular form).

Finally, you can plop that one line in the view -- the context['reverse_form'] = ReverseForm(request.POST.copy()) -- into any view anywhere and it will Just Work. You can obviously make multiple Forms to use in this manner if you've got multiple types of logic to run; the main thing differentiating them from one another is the field or fields to expect, and the logic performed in the "validation" step (though you are, of course, not really validating per se, just modifying the data if it's there).

bitprophet fucked around with this message at 02:36 on Oct 2, 2008

geera
May 20, 2003
How is the state of Python and Django on Windows? I'd like to use them here at work and I have a free Windows 2003 server to host them on. However, it looks like Windows users have a lot of hoops to jump through and I don't see any information on getting this setup to work with IIS. I've started tinkering with them today and I'm already having issues with the MySQL-python drivers not wanting to install.

Should I just give up now and try to find somewhere to get Linux running?

ATLbeer
Sep 26, 2004
Über nerd

geera posted:

How is the state of Python and Django on Windows? I'd like to use them here at work and I have a free Windows 2003 server to host them on. However, it looks like Windows users have a lot of hoops to jump through and I don't see any information on getting this setup to work with IIS. I've started tinkering with them today and I'm already having issues with the MySQL-python drivers not wanting to install.

Should I just give up now and try to find somewhere to get Linux running?

http://www.vmware.com/products/server/

Your real problems are going to be in the DB bindings (which you've already discovered). I believe Postgres has cleaner bindings in Windows than MySQL but, it's been years since I've played with Python on Windows. (cleaner meaning easier to install)

And IIS.... Wow... I would try Apache2 for Windows. I've used it before and it's not as "friendly" as IIS on Windows but, it still works. I would be hesitant to have it in production though. I know there was PyISAPI bindings and you could probably force Django to work in WSGI mode with it but, I have no idea if it's been done (probably has, there are crazy people everywhere)

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



geera posted:

How is the state of Python and Django on Windows? I'd like to use them here at work and I have a free Windows 2003 server to host them on. However, it looks like Windows users have a lot of hoops to jump through and I don't see any information on getting this setup to work with IIS. I've started tinkering with them today and I'm already having issues with the MySQL-python drivers not wanting to install.

Should I just give up now and try to find somewhere to get Linux running?

Apologies in advance if this sounds stupid, but have you tried running the installer under the Administrator account? When I installed the MySQL bindings on Vista, the installer wasn't smart enough to request elevation and so it couldn't write what it needed to write until I explicitly ran it as Admin. Those installer packages are/were pretty much :effort: and I can't understand how nobody has noticed and corrected it.

geera
May 20, 2003

ATLbeer posted:

And IIS.... Wow... I would try Apache2 for Windows. I've used it before and it's not as "friendly" as IIS on Windows but, it still works. I would be hesitant to have it in production though. I know there was PyISAPI bindings and you could probably force Django to work in WSGI mode with it but, I have no idea if it's been done (probably has, there are crazy people everywhere)
This server is actually a Win2k3 instance on VMWare. I was just trying to avoid installing another instance of Linux just for a web server, since this Windows box already runs our web-based helpdesk ticketing system, MySQL, and some other random services on IIS. I guess I could try and switch all that stuff over to Apache2 on Windows, but that's a lot of work and still doesn't fix my database bindings issue.

Munkeymon posted:

Apologies in advance if this sounds stupid, but have you tried running the installer under the Administrator account?
Yeah, I'm logged in as Administrator.

It first complained about a missing DLL, so I fixed that, but now it's saying Python 2.5 is required (I installed 2.6 today) and won't go any further. I guess I could try downgrading to 2.5. :effort:

dimebag dinkman
Feb 20, 2003

EDIT: Found the solution myself - I'd missed the "exclude" instead of "filter" QuerySet method.


This seems to work:
code:
MyModel.objects.filter(myfield__in = ['val1','val2','val3'])
...but myfield__not_in/myfield__notin don't work for the negation. Is there a reason for this? I'd understand if it was because "NOT IN" isn't supported by some of the SQL backends that Django uses (or there's some clever other syntax to get the same result), but if not it seems like an oversight.

dimebag dinkman fucked around with this message at 12:45 on Oct 4, 2008

king_kilr
May 25, 2007
Django doesn't have "negative filters" so there is no not equal filter, or not in, you just use excluse instead of filter.

the talent deficit
Dec 20, 2003

self-deprecation is a very british trait, and problems can arise when the british attempt to do so with a foreign culture





I just spent three hours hacking django to remove autoescaping only to learn there's a 'safe' filter tag that prevents autoescaping. :(

The Real Ambassador
Apr 9, 2005

I'll explain and make it plain, I represent the human race.

the talent deficit posted:

I just spent three hours hacking django to remove autoescaping only to learn there's a 'safe' filter tag that prevents autoescaping. :(

Aww I'm sorry. One time I searched for three hours to figure out how to escape template tags like this: {% hello %} Sometimes you come across features that are just so hard to search for.

I personally couldn't live without auto-escaping. I think it's one of the best features they could have possibly implemented into Django.

Also what is up with the new documentation layout? It's harder to navigate and they couldn't even create 301 redirects from the old URLs. Tsk tsk...

bitprophet
Jul 22, 2004
Taco Defender

The Real Ambassador posted:

Also what is up with the new documentation layout? It's harder to navigate and they couldn't even create 301 redirects from the old URLs. Tsk tsk...

Yea, I understand that Sphinx makes for generally easier to manage documentation, but man I do not really like the new docs layout at all; and my favorite habit of using my browser to search the top level page for the topic of interest, no longer works half the time :( I keep meaning to bring this up with the community since I don't remember seeing anything about it on the mailing lists; I fear everyone who finds it confusing is assuming they're alone and that's why it's not been brought up. Or I'm just missing something :v:

vvv I need to get better at doing that, myself, or add it to Quicksilver's list of Web searches.

bitprophet fucked around with this message at 22:21 on Oct 8, 2008

Typh
Apr 18, 2003

LAY EGG IS TRUE!!!
I just have a search keyword assigned to the documentation search box. So when I need to find something, I just type "dj [search term]" in my address bar.

Typh fucked around with this message at 21:50 on Oct 8, 2008

hitze
Aug 28, 2007
Give me a dollar. No, the twenty. This is gonna blow your mind...

I've been trying to figure out how to do this for a few weeks now. I've got an ImageField in an admin form, and what I want to do is move that file and rename it with the slug generated in the form. I've searched high and low trying to find a solution to this, but I've only found stuff relating to user uploads, not uploads in the admin area. Does anyone know how to go about doing this? :downs:

Wulfeh
Dec 1, 2005

The mmo worth playing: DAoC
Fourthing the "hard to find poo poo you need in the new docs," and it isn't just because I memorized the the layout of the old one. It isn't clear where the links are going to lead sometimes and you have to dig from one page to the next to find what you need, unless you know the search term you want.

bitprophet
Jul 22, 2004
Taco Defender

hitze posted:

I've been trying to figure out how to do this for a few weeks now. I've got an ImageField in an admin form, and what I want to do is move that file and rename it with the slug generated in the form. I've searched high and low trying to find a solution to this, but I've only found stuff relating to user uploads, not uploads in the admin area. Does anyone know how to go about doing this? :downs:

What do you mean by "slug generated in the form"? Is it a SlugField or something? Is the ImageField in the same form (i.e. load up empty form => specify both slug and image file => save form => expect renamed/moved image file to be on server now)?

This sounds like a job for overriding your model's save() method, assuming that this slug you speak of ends up back in the model at some point :)

Something like this (going from memory with the os, shutil commands, so double check those for sure; and you'll need to do a bit of tweaking about the image file extension because I am too lazy to look up how that works right now):
code:
import os, shutil
from django import models

def MyModel(models.Model):
    slug = models.SlugField()
    image = models.ImageField()

    def save(self):
        super(MyModel, self).save() # To do the normal saving stuff
        dst = '/path/to/destination/directory/'
        desired = '%s%s.jpg' % (dst, self.slug)
        if not os.path.exists():
            shutil.move(self.image.path, desired)

the talent deficit
Dec 20, 2003

self-deprecation is a very british trait, and problems can arise when the british attempt to do so with a foreign culture





Is there a generally accepted method of subclassing/extracting the admin app so that you can provide selective access to certain tasks without exposing admin directly? I know about permissions, but frankly they are not nearly flexible enough for what I want to do.

bitprophet
Jul 22, 2004
Taco Defender

the talent deficit posted:

Is there a generally accepted method of subclassing/extracting the admin app so that you can provide selective access to certain tasks without exposing admin directly? I know about permissions, but frankly they are not nearly flexible enough for what I want to do.

Depends on what exactly you want to do; with the newer admin (the one in 1.0, previously known as newforms-admin) you can create multiple different admin sites with different functionality. Can you give a specific example of what you want to accomplish?

hitze
Aug 28, 2007
Give me a dollar. No, the twenty. This is gonna blow your mind...

bitprophet posted:

What do you mean by "slug generated in the form"? Is it a SlugField or something? Is the ImageField in the same form (i.e. load up empty form => specify both slug and image file => save form => expect renamed/moved image file to be on server now)?

This sounds like a job for overriding your model's save() method, assuming that this slug you speak of ends up back in the model at some point :)

Something like this (going from memory with the os, shutil commands, so double check those for sure; and you'll need to do a bit of tweaking about the image file extension because I am too lazy to look up how that works right now):
You sir are a scholar and a gentleman. That was exactly what I was going for. I ended up using this
code:
    def save(self):
        super(Post, self).save()
        os.mkdir('/path/to/file/%s/' % (self.Slug))
        destination = '/path/to/file/%s/' % (self.Slug)
        renamed     = '%s%s-p.jpg' % (destination, self.Slug)
        shutil.move(self.Preview.path, renamed)
Now all I need to do is figure out how to dump a zip files contents and thumbnail them :)

bitprophet
Jul 22, 2004
Taco Defender
Zip file contents, there's a zip library in the Python stdlib, IIRC; thumbnailing, you can use PIL, which you should already have installed since you're using ImageFields (these require PIL). PIL.Image has a thumbnail or resize method, check their docs :)

Also, you should probably make use of os.path.exists() (which I had in my example but apparently forgot to put in the actual argument, oops) because otherwise someone re-saving the object will get a nasty error when your mkdir call fails :) which I believe it will do if the directory already exists.

nbv4
Aug 21, 2002

by Duchess Gummybuns
hi I'm a Django nub. I got everything installed and I ran "sudo django-admin startproject myproject" but I ran it in my /var/www folder, which apparently is not a good idea. If I just manually move the folder to my home directory or something, will everything be OK, or will I mess poo poo up? In other words, does that command just simply create those files, or is anything else being done?

Adbot
ADBOT LOVES YOU

bitprophet
Jul 22, 2004
Taco Defender

nbv4 posted:

hi I'm a Django nub. I got everything installed and I ran "sudo django-admin startproject myproject" but I ran it in my /var/www folder, which apparently is not a good idea. If I just manually move the folder to my home directory or something, will everything be OK, or will I mess poo poo up? In other words, does that command just simply create those files, or is anything else being done?

It just creates the files, so no worries. There is one aspect of setting up a Django project that cares about where your files are -- namely making sure your project is on Python's include path -- but 'startproject' doesn't do that, so at this point it doesn't really matter.

So, yes, move away! And yes, having it in /var/www/ is a bad idea -- stuff like Django and Rails are "hooked into" the Web server in a different way than CGI scripts or PHP are, and do not need to be in the Apache document root. Having your source files there is thus a bad thing because they might be served up as plaintext -- allowing anyone to read your source code :(

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