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
bitprophet
Jul 22, 2004
Taco Defender
Yes, render_to_response() will be used in the majority of situations, especially since you can give it a RequestContext in order to use context processors (although I do this often enough that I tend to write my own render() which is just a 2-line shortcut to doing so). The rest of the time I tend to be returning a Response subclass generated in some non-template-related fashion such as a simple CSV output, or an HttpResponseRedirect; or aforementioned 404/403 via 'raise Http404' or 'raise Http403' (if there is no 403 then I must've made my own at some point, heh).

Adbot
ADBOT LOVES YOU

bitprophet
Jul 22, 2004
Taco Defender

rotor posted:

Then why didn't they just name it "Jango"?? :argh:

Ask this guy

bitprophet
Jul 22, 2004
Taco Defender

genericadmin posted:

I'm going to laugh if it has to do with the jazz guitarist Django. I forget his full name.

Already posted the Wiki link, but, yup. It's because Adrian Holovaty, one of the core dev group members and arguably the founder, really has a thing for gypsy jazz and thought it'd be a neat name v:shobon:v

bitprophet
Jul 22, 2004
Taco Defender
The deal with the per-app template loader is that it throws all the templates into one big namespace (no other way around this given that every request for a template is a single string, e.g. 'index.html' or 'appname/index.html') so if you have two different apps, both with an 'index.html', it'll only pick up the first one it sees. So this basically forces you to 'namespace' your templates no matter which template loader you use.

Also, as you saw, the generic views assume this setup by default (i.e. 'appname/templatename.html') so if you're using the per-app loader, you either need to make the extra folder, or override every generic view call with the correct template location (you can do this, by the way - you can just pass 'template_name=blah' to any generic view to override the template it uses).

Hope that makes sense, typing this in a hurry :)

bitprophet
Jul 22, 2004
Taco Defender

Nolgthorn posted:

Would the DB get hit twice, or only once? Is what I'm saying too complex for a framework to be able to do... If you derived 'result' from 'all_results[0]' instead of 'my_results[0]', then it wouldn't have to hit the DB twice.

Absolutely not - how could it? That's asking the Python interpreter to start making guesses about what you're doing with your code...doesn't make any sense. Put another way, the 'my_results[0]' call comes before the other one - having that line change its behavior when you remove a line farther down the file would just be :psyduck:

bitprophet
Jul 22, 2004
Taco Defender

Addict posted:

I just wish the template language was a little looser and allowed recursion.

It does support recursion, just not straight out of the box. I'm doing it on one of my personal apps and I am reasonably sure I or someone with a similar approach has an item up on djangosnippets.org (which is down right now or I'd try to find it for you).

My approach is not well abstracted nor will it gracefully fail if you get it into an infinite recursion scenarion, but is still pretty simple - it simply renders the template given to it, re-binds a single object in the sub-template's context dict, and returns the output.

It's the first templatetag in this file and is used on todo item objects (hence the re-setting of 'item' in the new template's context).

Needs a 'kickoff' template which calls it the first time, then a 'sub' template which calls it the 2nd through the Nth times, at least in my usage, although I can't think of any obvious reason why they couldn't be the same one (but it has been a while since I whipped that up so I could be wrong).

Also, a big :fuckoff: to you lucky bastards going to PyCon, I'd love to go (and should go, since we have a Django book coming out soonish which I should be trying to hype) but don't have enough vacation days due to using some of this year's, last year (for my honeymoon though, so it was worth it).

bitprophet
Jul 22, 2004
Taco Defender

Nolgthorn posted:

Is there a good way of creating "HTML helpers", in the way that Rails does it, so that I could type {% paginnnnnnnnnnnator %} and have that just read from another template? Do I just need to include it on the page then and what does the code look like to do that?

What if I'm calling it multiple times in the same page, is there a way to do it properly with a minimal of code and duplication?

Can I pass arguments?

First off, for actual custom template tags, see Bonus' link.

However, if what you want is for {% paginnnnnnnnator %} to "read from another template" then you want the built-in template tags {% include %} (for literal including) or {% block %}/{% extends %} (for a fill-in-the-holes approach).

I mean I guess you could make your own template tag that's simply a shortcut for {% include "specific/template.html" %} but I'd say that's just silly :)

bitprophet
Jul 22, 2004
Taco Defender

ashgromnies posted:

Why not? I want the question mark to be optional. In most regular expression engines(including Python's), the question mark means to match the preceding character zero or one times.

Make sure the slash-appending behavior of CommonMiddleware isn't screwing you up. Typically, you should have APPEND_SLASH enabled in settings.py and just forget about trying to catch 'missing' slashes in your URLconf - there's no need for doing so and it'll give rise to issues like this.

I'm guessing something unexpected is going on when interpreting your URL (again possibly caused by APPEND_SLASH behavior) and it's 'falling through' to your blogs URLconf. For example, if the admin and articles lines in your mail URLconf don't match (which seems to be what's happening) the URL dispatcher will end up in your blog URLconf (because it's catching the 'empty' regex).

At any rate, I'm 99.9% sure that if you make sure APPEND_SLASH is on (and that CommonMiddleware is enabled, natch) and remove the question mark in your admin include regex, everything will work fine, for either https://www.mysite.com/admin or https://www.mysite.com/admin/.

bitprophet
Jul 22, 2004
Taco Defender

politicorific posted:

I'm trying to determine if Django is the right tool for my website:

http://politicorific.gotdns.com:8090/
try "work" "sweep"

It conjugates Hebrew verbs. There are 4800 entries, the example and many of the other sites in the examples are geared toward user created content.

Can it be done, should it be done?

I don't see why not...but we'd need more specific/technical info to determine if there's some aspect of it that Django would be poorly (or well) suited for. Certainly Django's fine for user created content driven sites, and I can't imagine why it would have any problems outputting Hebrew characters.

Especially given that current trunk is pretty much 100% Unicode based now; although for that concern, the question is more "how easy is it to work with Hebrew in Python" given that Django is just a handful of Python libs.

bitprophet fucked around with this message at 16:01 on Mar 16, 2008

bitprophet
Jul 22, 2004
Taco Defender

Digital Spaghetti posted:

Funnily enough I'm working on that now in our app, but I've hit an issue.

The problem is when making a Ajax request, when I load a view because it extends the template above it and it loads in the whole page and not just the fragment.

I tried to pass a view variable from request.is_ajax() and put a {% if %} tag around the extend, it doesn't work - so what I'm having to do is create two versions of the same template, one without the extend.

It seems very anti-DRY, but I can find any other solution to it.

Yea, I don't think {% extends %} can work that way, as its use has large implications for how the rest of the template is interpreted and rendered. In fact I don't think you're even allowed to have {% extends %} anywhere but on the first line of a template file.

Would it be feasible to use {% include %} to work around it? I'm thinking the following:

base.html:
code:
<html lol>
<nav goes here maybe>
<div class="left-col">{% block one %}{% endblock %}</div>
<div class="content-col">{% block two %}{% endblock %}</div>
<footers yay>
</html lol>
An average template in the rest of your site:
code:
{% extends "base.html" %}
{% block one %}Left col content!{% endblock %}
{% block two %}Main col content!{% endblock %}
The template in question, which needs to be used normally and via AJAX: it will be included for the former and rendered directly for the latter. The trick is that the contents of {% block %} will always print out normally unless overridden by a child template, so if you use {% block %} in a template that's not extending anything, no harm no foul. Let's call it 'include.html':
code:
{% comment %}No extends here!{% endcomment %}
{% block one %}blah blah left col{% endblock %}
{% block two %}blah blah content col{% endblock %}
This, then, is the template you would ask to render for your normal HTML view, let's call it 'normal.html':
code:
{% extends "base.html" %}
{% include "include.html" %}
Hope that makes sense: for the base case, when you just want your "fragment", you render include.html directly, the block tags (but not their contents!) are basically ignored, and you get your output sans any wrapper HTML or whatever's in your base template. And when you want the normal HTML view, you render normal.html, which does the extends, then includes include.html, and the block tags are then used to fill in base.html as normal.

An additional useful tidbit, if you have output in include.html that is not within the {% block %} tags it should be ignored when included in normal.html (because the extends/block setup only cares about what's inside {% block %} tags in child templates) but will print out in when rendered directly. Thus you can further customize the template to behave differently in AJAX than normally, although there's no easy way to do the reverse.

bitprophet
Jul 22, 2004
Taco Defender

ashgromnies posted:

you can't modify a model after it's been installed is a major sticking point for me.

I'm guessing you're not that great at SQL? I don't mean that in a mean sense - just that anyone who's intermediate with SQL would think absolutely nothing of 1) add or modify Django model field, 2) Execute a couple of ALTER TABLE statements or drop/create db and syncdb, 3) reload Apache, 4) test out new feature.

Having automagic schema evolution would be great, obviously, but doing it by hand is not difficult.

So I guess I just take issue with you claiming Django has "no way to implement features incrementally" - that's hogwash, I and thousands of others do it daily. It just doesn't go the extra mile to insulate people from having to know their database, and if that's something that you value, that's cool (again, I think Django should have the option to generate SQL updates) - just please don't frame it as the framework lacking something integral to Web development, which it does not.

bitprophet fucked around with this message at 01:25 on Mar 25, 2008

bitprophet
Jul 22, 2004
Taco Defender

ashgromnies posted:

Not sure, I haven't looked at Middleware yet.

Yea, Django middleware is designed to run before/after every request/response as well as offering a couple of other spots to plug into. I haven't looked at that third-party RESTful stuff, but from what you're saying you should definitely look into the process_view (pre-view) and process_response (post-view) middlewares here (top of the page will give you an intro to middleware in general).

bitprophet
Jul 22, 2004
Taco Defender

Typh posted:

How/where do I turn off the conversion of linebreaks to paragraphs in the admin interface (TextField)? I just want a nice clean HTML-capable textarea.

What exactly do you mean? AFAIK TextField should not be doing anything special when it displays in a template unless you pipe it through the 'linebreaksbr' or similar template filters. Where exactly is it changing line breaks to paragraphs - where is your inputted text displaying?

bitprophet
Jul 22, 2004
Taco Defender

Typh posted:

The admin interface automatically converts line breaks to paragraphs when it saves to the database, as far as I can tell. When I put in my own paragraphs, there are extra p tags strewn around that aren't from me.

That can't be right - a literal, normal TextField should save plain text to the database 100% literally, with zero HTML whatsoever unless you've entered it yourself.

Where are you viewing "the database" exactly? I'm guessing that the P tags are getting inserted by some post-database process, or by whatever tool you use to view the source (e.g. Firebug's HTML viewer seems to 'tidy' the HTML and might end up appearing to insert extra tags like that).

But, again, a normal, unaltered (meaning no save() override in the model or anything) TextField should never be performing any sort of transform on your data, period. So something else should be going on here.


StabbinHobo, you don't work in the journalism field, do you? Not at a paper in JC perhaps?

bitprophet fucked around with this message at 23:00 on Mar 28, 2008

bitprophet
Jul 22, 2004
Taco Defender

Typh posted:

Today, I am that programmer.

Nah, everyone does this, and more often than they admit. It's part of the job, we have so many different scenarios and environments and variables (in the non code sense) floating around that it's stupidly easy to make silly mistakes like that.

The trick is not spending too long chasing any one "bug"...we tend to get like bulldogs and latch onto a single issue and beat our heads on it for extended periods. If the entire bug hunt is predicated on a mistake, we've just wasted hours of our time (experience talking here :() so it's good to develop a habit of "ok I just passed the two-hour mark without making much real progress - time to take a step back and try a different approach".

bitprophet
Jul 22, 2004
Taco Defender

Typh posted:

I was digging through the admin code, running from file to file, function to function, trying to track down where it was coming from. Why didn't I check the database to see if it was really there.

Anyways, back to loving Django.

That's another semi mantra of mine (and no doubt lots of people with way more experience), "always double check your assumptions". Assumptions, especially in programming, are killers.

bitprophet
Jul 22, 2004
Taco Defender

Addict posted:

So is everyone using the .96 release of django or the latest on subversion. When looking to extending the admin panel they keep saying they want to overhaul it with newforms and such. It seems like a few things are in limbo at the moment. I have been sticking to .96.

0.96 versus trunk is an odd case; obviously 0.96 is very stable and trunk does change fairly often-ish (although rarely breaking backwards compat, and always well documented when it does). However, 0.96 is over a year old at this point and there are a lot (as in A WHOLE LOT) of new features and concepts and so forth, in trunk, which aren't in 0.96 at all.

If you stick with 0.96 and wait for e.g. 1.0 to come out (whenever that is; nobody knows; I'm guessing within 3-6 months or so) there will be a significant amount of work you'll need to do to upgrade your codebase, and in the meantime you will miss out on some vastly improved functionality (newforms, the upcoming queryset-refactor, HTML auto-escaping, url()/@permalink for DRY get_absolute_url()s, the list goes on).

So I'd only stick with 0.96 if you're developing mission-critical production software, in all honesty; plus there's no reason you have to track "the latest" if you upgrade to a trunk checkout. I tend to check out or upgrade SVN when I start a new project, when a bug is fixed or when I want to try something new - but only then. So it'll still be extremely stable but you'll reap the benefits of over a year's worth of work.

bitprophet
Jul 22, 2004
Taco Defender

StabbinHobo posted:

indeed. you interview?

I did, last summer actually, but ended up going with the place I'm at now (sorry!). Good luck with the hiring, if I run into anyone looking for Django work I'll send them your way :)


Tap posted:

Here's to a long future with Python!

:neckbeard:

bitprophet
Jul 22, 2004
Taco Defender
Senso, if you have a minute, you should definitely do a quick search on the Django bug tracker to see if there's a ticket for this already, and if not, make a quick one with the info you just posted - it sounds like this might be a genuine minor bug in the Postgres support, and if so, it'd be great to have it officially reported so it can be fixed in trunk :)

vvv Thanks!

bitprophet fucked around with this message at 22:06 on Apr 8, 2008

bitprophet
Jul 22, 2004
Taco Defender

jarito posted:

I've decided to take a look into Django and I had some quick questions. From Java / ASP development, I've gotten spoiled in having really good IDE's. Is there a good ide for Python? By good I mean at least has syntax highlighting, intellisense and debugger integration. Project management would be a bonus but I guess it is not required.

Gotta specify your platform...:)

Any programmer's editor will do syntax highlighting for Python, and most of the extensible ones (Vim, Emacs, TextMate, etc) will probably have third party Django template language bundles available. Debugger integration varies; debuggers aren't typically (in my experience) terrifically useful/applicable to Web development, but for stuff that can be tested outside of the Web context, there are Python debuggers such as pdb, and again many editors have hooks for them.

From what I've seen, though, most Django devs don't find themselves needing the big beefy IDE setup that Java, etc practically require. Autocomplete, syntax highlighting and a terminal = good to go.

bitprophet
Jul 22, 2004
Taco Defender

jarito posted:

I generally develop on Windows these days due to a lot of ASP.NET projects, but I still run Linux so either of those would be fine. So the only options are Vim / Emacs (TextMate is OSX only, yes?). That's disappointing. There aren't any plugins for Eclipse or something of that nature that do intellisense? I've never been that fond of vim / emacs, but I guess I can use them if I really have too.

I disagree about the debugger comment, but that's a whole different conversation. :)

Oh, no, I wasn't giving an exhaustive list. Pretty sure the default Python distribution comes with something called IDLE, that might be Windows only, not sure. No idea how good it is - I use TextMate which is OS X only.

Eclipse should definitely have Python support, not sure if it has Django specific support. Google around for "(python OR django) IDE" and I'm sure you'll find blog posts / discussions.

vvv I actually use vim more than TM nowadays since I spend a lot of time remotely editing...it is pretty awesome :)

bitprophet fucked around with this message at 02:58 on Apr 9, 2008

bitprophet
Jul 22, 2004
Taco Defender

tehk posted:

I have a quick question regarding the subclassing of models.

Model subclassing is still not officially in, but the queryset-refactor branch (which will hopefully hit trunk in the next, I dunno, month or two maybe?) has implemented it: http://code.djangoproject.com/changeset/7126#file8

So if you're willing to use an unstable branch, you could check out that version of Django and give it a whirl. I haven't used it at all.

Withnail posted:

I've been finding it a little difficult to work in java all day and then switch gears to php at night. Generally speaking, is python/django going to be an easier transition for web apps than php?

Depends partly on what you mean by "easier"; PHP's syntax is a little closer to Java than Python's is (what with the semicolons and curly braces and all). In terms of overall web development paradigms, I've never used Struts so I can't really say there.

bitprophet
Jul 22, 2004
Taco Defender

The Real Ambassador posted:

It really irritates me when people think languages are similar because they both have curly brackets.

Heh, well I was only throwing that out because it's been years since I used Java heavily (university; been using Python exclusively since I graduated) and didn't feel qualified to speak on the more meaningful similarities/differences. That's why I italicized syntax, an attempt to highlight the fact that it wasn't really something to seriously compare with.

The real point of my reply was the request for clarification of what he was asking for, should have left it at that.

bitprophet fucked around with this message at 15:38 on Apr 15, 2008

bitprophet
Jul 22, 2004
Taco Defender

ImJasonH posted:

I'm having a problem making my first Django Model class save(). I keep getting an AttributeError with the message: 'Foo' object has no attribute 'id'

The docs make it pretty clear that you don't have to specify an id field, that it'll add one for you if you don't, so what could be keeping it from working?

I'm using a Manager, I have a Meta class that sets a different db_table and an __init__ that sets all the fields, but nothing else that's all that complicated. Any ideas?

Also, I just started using Python last week to play around with the Google App Engine and got hooked on Django this week, it's pretty sweet. Seems to make things just about as easy as possible, I think. Except, of course, when none of your objects will save :(

Please paste (or pastebin, e.g. dpaste.com) your model code? Hard to troubleshoot without.

Been a while since I tinkered with save() but I am reasonably sure objects do not get an id until after their first save, so depending on what you're doing that might be the issue. Also, "an __init__ that sets all the fields" could be dangerous depending on what that means exactly, which is another reason I'd like to see your code :shobon:

bitprophet
Jul 22, 2004
Taco Defender

Nolgthorn posted:

[...]
I see other benefits to the way Django is doing it, I'm just surprised. That amount of control and manual 'work' is unheard of in the Rails community.

The way I've seen it, without having used Rails much but working at a shop where it's used by 50% of the dev team, is that Rails goes the extra mile in terms of leveraging cleverness and magic and making decisions on your behalf. The benefit of this is that it's less work in those cases where Rails' decision-making lines up with your needs, and/or where you don't run into bugs that are made difficult to fix due to having to track down said magic.

However, if you want/need to differ from Rails' opinions on things, then you have to struggle with the framework to get things done, and/or omit large gobs of functionality.

Django, on the other hand, tends to not offer as much extra stuff, but that's because it wants to avoid that above situation where the user then has to fight the framework to get things done their way (with the exception of Django's ORM, which is used for the admin and generic views; but that's more of a technical constraint rather than an explicit choice made by the core team).

For example, Rails tends to tie you to Prototype for Ajax stuff, insofar as its JS helper code uses Prototype only (or so I'm told); Django doesn't offer such helpers, so you can use whatever Ajax library you want.


So, yea, neither approach is inherently wrong, it's just two different philosophies at work.

bitprophet
Jul 22, 2004
Taco Defender

politicorific posted:

Next question regarding views/models.
__str__ in model constructs the output of the database search into a single string. I need to manipulate this data separately - each piece goes to a different place. I suppose I could use .split() and create another list, but that just doesn't seem elegant enough.

code:
def __str__(self):
                return ("""%s,%s,%s,%s,%s,%s,%s,%s,...

really this goes on forever, there are 49 instances of %s and 49 different variables it's combining. There must be a better way!

code:
def __str__(self):
    return ",".join([str(x) for x in list_of_vars])
Not sure why you were returning what looks like a tuple for your __str__, but my snippet there will give you a string of the form you're trying to generate, and assumes your variables are in a list of some kind.

It's not 100% clear what exactly you're trying to accomplish, though, so maybe you should step back a bit and give us a better idea :)

bitprophet
Jul 22, 2004
Taco Defender
I...I don't think you quite get this :(

__str__ is solely a convenience method for printing out a string representation of your model object, like when you're debugging or displaying a list. "output from models.py" doesn't mean jack poo poo: you're supposed to query the database using the ORM, not parse the string representation of your model, or whatever you're trying to do.

It looks like you're trying to basically build an arbitrary query front end or something (like phpMyAdmin)? It's not clear. Can you give some example use cases in plain English? I.e. "I want to find all Entry items in my database which have the word 'Foo' in their 'english' field" or etc.

What is the real world problem your application is trying to model and solve here?

bitprophet
Jul 22, 2004
Taco Defender
Yea, it's a decision made by the Django devs (for the time being, anyway) that having a script automagically update the DB based on changes you make to your models, isn't a good idea. There's a lot of places where such a script could gently caress things up or cause you to lose data, and they didn't want people to be tempted to run that kind of tool on live data.

Or, put another way, you really ought to know at least enough about SQL to be capable of making minor changes to your DB schema, if you're going to be making sites; that's my opinion, anyway. It's really not hard to run a couple of ALTER TABLE statements during development :)

That said, yea, it's a commonly asked-for feature and there are a few projects out there trying to address it, but nothing that's hit prime-time yet. Your best bet is to try checking out the schema-evolution branch and play with that, but it's not for the faint-hearted.

Actually, I take that back - your best bet is to read a few SQL tutorials so you understand how to make the changes yourself, it really is. You'll be a much better developer for it.

bitprophet fucked around with this message at 15:47 on May 6, 2008

bitprophet
Jul 22, 2004
Taco Defender

Larry Horse posted:

edit: I just blanked the strings in the enum structure. I don't know if this is the "right" way to do this, but it works.

By which I assume you mean your "enum"s look like this:

code:
CHOICES_FOR_SOME_FIELD = (
    ('option1',''),
    ('option2',''),
    ...
    ('optionN','')
)
?

If so, that's one way to do it, since you don't actually intend for each individual radio button to have a label. It's also probably the quickest way, given that the other alternative is to manually spit out the HTML yourself (and checking e.g. {{ form.some_field.data }} to determine which radio buttons are selected, if you ever display the form in a previously-filled-out state, like if you redisplay on user error). I say this assuming you currently do something like {{ form.some_field }} for the display...which is what is automatically spitting out labels.

If you're on trunk instead of 0.96, I think there may be a way to print the formfield sans label, with newforms (the form/manipulator stuff in 0.96 is now 'oldforms'; newforms is a lot better and gives you more granular control) but I don't know for sure off the top of my head.

bitprophet
Jul 22, 2004
Taco Defender
Yea, Django's awesome like that :D

One minor note, the approach you're taking is potentially a little "off" accessibility-wise and/or markup-wise, in that it is probably littering your code with lots of <label for="field_name"></label> tags, i.e. tags which are generally intended to have text in them but which are now empty.

Chances are this isn't a huge problem, or that it's not an issue in your case (tho it could potentially cause style problems in e.g. IE6 even if you don't care about people with screen-readers), but I wanted to make sure you knew the diff between this approach and one where the <label> tags aren't even displayed :)

bitprophet
Jul 22, 2004
Taco Defender
Not sure if you've been using generic views for your existing template(s), but for this you will need a normal, non-generic view. For input it'll probably just take the request, and you'll want to use a form with checkboxes or radio buttons to make this happen (you can use JavaScript so that clicking the name of the game/referee selects the appropriate form control, if you want to make it even easier for users).

Then your view will do what's a pretty normal form-processing flow control: check to see if request.POST is non-empty (and request.POST is a dict, so you can just do if request.POST: since an empty dict is equal to False). If it is non-empty (i.e. the user has submitted the form) you see what game/referee were selected and make the association in the database (how exactly this is done depends on how you've related the two models, but I'm assuming a many-to-many given your description).

After that if statement (but not in an else!) you will then want to render the template; users hitting the page for the first time will just get the normal display, while users who have submitted the form will get it back again, as you've said you want them to.

Here's an example...please don't copy-paste this, as I'm going from memory, but instead make sure you understand what it's doing and look up the correct methods and such to use :) Copy-paste is a terrible way to learn! Also, I am very lazy when whipping up HTML for the first time, so this isn't awesome front-end work either (but CSS-styled divs and spans are generally better than tables, regardless).

Template
code:
<form action="" method="POST">
<div class="page-wrapper">
    <div id="left-col">
        {% for game in games %}
        <input type="radio" name="game" value="{{ game.id }}" />
        <span class="game">{{ game.title }}</span><br />
        {% endfor %}
    </div>

    <div id="right-col">
        {% for referee in referees %}
        <input type="radio" name="referee" value="{{ referee.id }}" />
        <span class="referee">{{ referee.name }}</span><br />
        {% endfor %}
    </div>

    <input type="submit" value="Associate the selected game and ref!" />
</div>
</form>
Model (just to fit with the rest of the example)
code:
from django.db import models

class Referee(models.Model):
    name = models.CharField(maxlength=100)

class Game(models.Model):
    title = models.CharField(maxlength=100)
    referees = models.ManyToManyField(Referee)
View
code:
from django.shortcuts import render_to_response
from myproject.myapp.models import Referee, Game

def refs_and_games(request):
    if request.POST:
        # Omitting checks to make sure a game & ref were actually selected!
        game = Game.objects.get(pk=request.POST['game']) # since we used game.id
        ref = Referee.objects.get(pk=request.POST['referee'] # ditto
        game.referees.add(ref) # no need to call game.save() since it's a m2m op
    return render_to_response('refs_and_games.html')

bitprophet
Jul 22, 2004
Taco Defender
Wulfeh's approach is quite valid and leverages the forms framework more than mine does. Main difference template-wise is that his uses the default representation of a field with choices (forget what that is these days but it used to be a dropdown list or a multi-select box depending on field type), whereas mine has a more explicit/manual HTML setup. The former is quicker while the latter gives you more control.

I guess I went with the latter myself because the way the problem was phrased made me think "ok, he's got a fairly specific page layout in mind, so that means custom form HTML", but that's not always necessary. Mine actually ended up involving less work than Wulfeh's, but is also less realistic as it omits all the error checking and such :) In the long run, the more you can leverage the forms stuff, the better off you'll be.

bitprophet
Jul 22, 2004
Taco Defender

Wulfeh posted:

I also love how python is so easy to work with, compared to literally "fighting" with C++.

IMHO that's Python's greatest strength: most of the time, your biggest problem is...the problem at hand...not the language or the libraries. When you get down to it, programming is just problem solving and domain modeling, and Python makes it very easy to focus almost entirely on what you're doing, not how you're doing it.

Jacko posted:

I have been backtracking to make sure I understand the fundamentals

Good! It'll take a bit of time, but I'm glad you're doing this - too many people care only about the end result and "getting it working" instead of understanding the tool and/or the right way to solve the problem at hand. If you can manage to juggle both the desire to learn the "Right Way" of doing stuff, and the desire to get things done on time, you'll be a much better developer than most of 'em :)

bitprophet
Jul 22, 2004
Taco Defender
http://www.djangosnippets.org/snippets/160/

Found by googling for django templatetags "every template" :)

I knew this existed but couldn't remember the specific method to use, and it's not documented for some reason (pretty unusual for Django, but could imply that it's not considered 'stable' yet).

bitprophet fucked around with this message at 15:22 on May 17, 2008

bitprophet
Jul 22, 2004
Taco Defender

Nolgthorn posted:

This raises the question about how liberally imports should or should not be used. How much extra processing is required when you use urls.py and views.py to import a lot of stuff, instead of just directing everything in your urls.py file to you view, to only import there.

I would be concerned, that if importing does use up resources, then more resources are being used than necessary. Thoughts?

I'm reasonably sure that it doesn't matter; everything except for templates is loaded once, and only once, per Apache child process (or whatever Web server process you're using which has loaded up a Python interpreter) so whether something is imported to your URLconf or your view, it's going to take up memory for that particular process either way. (Also pretty sure that Python interpreters are smart enough that only one copy of each module gets loaded, so importing your Foo model class everywhere won't be a problem...)

This is a good thing, though, because re-loading and re-interpreting all your Django/Python code on each request would be pretty god-awful performance-wise.

bitprophet
Jul 22, 2004
Taco Defender
James' book is, in my understanding, exactly what the title implies - a look at developing some practical sample applications. I don't think he's going for the "learn Django just by reading my book", which is what the official book, the Sams (lol) book, or my book (http://www.amazon.com/dp/0132356139/) would be good for.

Looking forward to James' book, though, he's a very smart cookie and he and I pretty much tag-teamed the IRC channel back in the day in terms of fielding questions. He's also been the official Django release manager for, what, a year now? :) so he's practically part of the core team.

bitprophet
Jul 22, 2004
Taco Defender

Nolgthorn posted:

Neato, is a developers library more or less what you find on the Django web site? I'm curious.

If you mean the "Developer's Library" on the cover image of my book, naw, it's just the "line" or series of Addison-Wesley books it's being published in (sorta like how O'Reilly has the In A Nutshell series).

The book I'm writing (with two other guys, so it's really "our" book, not "my" book :)) is sort of a generalist book...it's got wide coverage of the framework's features, both basics and contrib apps (so it functions as a general howto like the official Django docs/book); it's got four example application chapters (probably similar, but smaller, than James'); it's also got an intro chapter on Python for Python newbies, and overall tries to keep a focus on practical development practices, something none of the other books really have (except James' by virtue of the example-app focus).

/self-promotion

bitprophet
Jul 22, 2004
Taco Defender
Are you asking whether select_related() will pull things down across reverse foreign keys? As far as I know, not having checked the source, it wouldn't (but I'm not an expert in this area) - it would probably only follow 'forward' relationships. So in the setup given in that documentation, City.objects.all().select_related() wouldn't pull in all the Persons and Books.

Should be pretty easy to figure out if this is the case, though, by doing from django import db and then printing out db.queries (I think that's the right name) at different points, before/during/after running some queries.

Just did some Googling and found at least one Django-users post implying that it does not follow reverse relations at this point in time; the post was from mid April, though, so it's possible the queryset-refactor merge has changed things.

bitprophet
Jul 22, 2004
Taco Defender
Yes :(

Also, I started learning Rails in earnest today. Not really blown away...has some neat ideas, and some pretty silly ones too (plus the usual warts that everything including Django has, i.e. occasional inconsistencies). Still, looking forward to being able to really contrast the two as I learn more, and at any rate it HAS to be better than the PHP crap I've been doing lately.

Adbot
ADBOT LOVES YOU

bitprophet
Jul 22, 2004
Taco Defender

Milde posted:

mod_python is a huge piece of poo poo.

I'd be honestly interested to hear more on this -- not saying I don't believe you (it's semi well known that, maturity aside, mod_wsgi is a superior approach) but the only material I've seen repeatedly is that mod_python is simply not as efficient and/or layered as the WSGI approach.

It's worked fine for the Django core team and it's worked fine for me and other Django folks, so I'm curious about stories from people who have had negative experiences with it, assuming you can go into the whys and hows and not just say "I had random problems X and Y" (i.e. be informed and not just anecdotal).

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