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
Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe
I was going to post a reply, but then I remembered this.

That Turkey Story posted:

I work as a programmer coding software for an automatic sewing machine that runs entirely on cow manure to be used primarily by wives of cattle farmers (not even kidding). Despite how it sounds, we somehow have a steady stream of consumers and the software itself is surprisingly complicated -- the machine manages all different kinds of needles and threads, switching between them via a simple interface and it alerts the user when spools are running low, etc. It's not exactly the most fun work I've done, but it's unique and it pays well.

Anyway, the code-base is absolutely garbage and it makes heavy use of factories for creating any and all objects. What's even worse is that the coding standard here for factories is to use all single letter identifiers that consist of the first letter of the word that they represent. The exception to this rule is that if you want to represent something that is two or more words long, you use the first letter of each of those words (I.E. the generic factory for creating objects that represent "Needles" is a global object simply called "n" and the factory that produces objects that represent "Tatting Needles" is called "tn" :doh:). Furthermore, we have a strict versioning convention where you append "v#" to any new factory name that is a revised version of another factory where # is the version number). For instance, at some point early on in development before I got here, the type for representing upholstery needle's was totally revamped and a new type was created -- rather than reuse the same factory name, the old one still exists, but if you want the new type, you have to use the "unv2" factory, where "unv2" stands for upholstery needle version 2. Couple this with the fact that there are pretty much no comments and you get impossible to read code that you have to analyze to figure out what it's supposed to be doing.

Case in point, we have different factories for threading needles that work with different internal types based on whether the machine is running on cow manure or bull manure or a combination, so there is a factory "nc" for "no cow" if it is trying to thread a needle when running strictly on bull manure, "cb" if it is trying to thread a needle while running on cow and/or bull manure, and "nb" if it is trying to thread a needle while running on just cow manure. What's worse is, these factories are constantly being revised so seeing an expression like "cbv3()" for "cow and bull version 3" is way too common.

To make a long story short, one afternoon back in 2002 I was making updates to the threading functionality and when I tested my changes on the actual machine, everything seemed to work fine except that whenever I went to work with strictly bull manure, all the spools were getting covered in feces! I looked back at my code but because it was a long day I couldn't figure out what the problem was so I just started a new version of the "no bull" code and increased the version count to 5.

Everything works fine now if you use the latest factory, but to this day, nbv4 produces nothing but lovely threads.

In the off chance that you aren't trolling, that's the worst way to make apps. Your apps should depend as little as possible on the rest of your program. If it's done right you should be able to copy an app over to another project and have it work with as little modifications as possible.

To elaborate on your PDF example, if it depends entirely on the user account then it should be in the user account app.

Adbot
ADBOT LOVES YOU

nbv4
Aug 21, 2002

by Duchess Gummybuns
If that were the case, then my whole project would be one giant app, because everything depends on everything to some extent. The project I'm referring to is 30,000 lines of code, and it's split up into 17 apps. None of the apps are "reuseable" except for maybe one or two, but they don't need to be.

Stabby McDamage
Dec 11, 2005

Doctor Rope
I'm just starting out and I have a pretty basic question. I'm making a simple restaurant voter with this model.

I want a view that shows all the places and what the logged-in user rated them.

My stupid instinct is something like {{place.user_rating(user)}}, but templates don't work like that, and it would be mixing code and template anyway.

But I'm not sure what the "right" thing to put in the view function to make this happen. I could do a parallel array, but that seems ugly as hell. What is the canonical Django way to do something like this?

king_kilr
May 25, 2007
a) tabs :(
b) self.vote_set.get(user=user) will raise a Vote.DoesNotExist exception, not return None, so you'll want to catch the exception and return None in that case, not test for whether vote is True.
c) To answer your actual question, write a template tag or filter. Something like {% get_vote for place user as vote %}: http://docs.djangoproject.com/en/dev/howto/custom-template-tags/#howto-custom-template-tags

Stabby McDamage
Dec 11, 2005

Doctor Rope

king_kilr posted:

a) tabs :(
b) self.vote_set.get(user=user) will raise a Vote.DoesNotExist exception, not return None, so you'll want to catch the exception and return None in that case, not test for whether vote is True.
c) To answer your actual question, write a template tag or filter. Something like {% get_vote for place user as vote %}: http://docs.djangoproject.com/en/dev/howto/custom-template-tags/#howto-custom-template-tags

a) Yes, tabs. A HAHAHAHAHAHA
b) Dang, I should have known that
c) I knew I was missing a big part of the puzzle. Thanks.

While I'm here, I have a general question. How are apps supposed to be reusable when so many references have to be made to the project name? Maybe I'm missing something here, but following the tutorial, I have lots of projectname.appname.thing in my code, like the first arg to patterns(), from/import statements to get the models imported, reverse() calls in my views, etc.

How are you supposed to plug-and-play apps if the apps have the project name sprinkled everywhere? Or am I missing another big concept?

king_kilr
May 25, 2007
Apps should go directly on your python path, and you should never need to reference your project name except for your root urlconf pretty much. I highly reccomend: http://www.youtube.com/watch?v=A-S0tqpPga4 by james bennett and http://djangodose.com/podcasts/callcast/episode/10/ from DjangoDose.

jupo
Jun 12, 2007

Time flies like an arrow, fruit flies like a banana.

king_kilr posted:

you should never need to reference your project name except for your root urlconf pretty much.

Here's a little snippet from my default settings that ensures even your urlconf doesn't reference the project.

code:
import os
ROOT_URLCONF = "%s.urls" % os.path.dirname(os.path.abspath(__file__)).split(os.sep)[-1]

Stabby McDamage
Dec 11, 2005

Doctor Rope

king_kilr posted:

Apps should go directly on your python path, and you should never need to reference your project name except for your root urlconf pretty much. I highly reccomend: http://www.youtube.com/watch?v=A-S0tqpPga4 by james bennett and http://djangodose.com/podcasts/callcast/episode/10/ from DjangoDose.

I will definitely watch those, but is there a good Django resource that is a hard-core reference and best practices guide? So much of the official docs are conversational, and many assume you'll roll your own best practices. Is there a good, concise Django reference that will tell me the right way from the start (besides the Django book)?

Also, is there a Django app repository or index? I didn't see one in the OP, and this site basically says "search google code, some random forum, or use something these guys wrote". Perl has CPAN and Python as PyPI, but is there a central repository for Django apps? Maybe PyPI is the answer?

No Safe Word
Feb 26, 2005

Stabby McDamage posted:

Also, is there a Django app repository or index? I didn't see one in the OP, and this site basically says "search google code, some random forum, or use something these guys wrote". Perl has CPAN and Python as PyPI, but is there a central repository for Django apps? Maybe PyPI is the answer?

Normally I would recommend Django Pluggables but it seems to be down at the moment!

king_kilr
May 25, 2007

No Safe Word posted:

Normally I would recommend Django Pluggables but it seems to be down at the moment!

http://www.djangozen.com/ does something similar.

agscala
Jul 12, 2008

How do you all serve your images and css and other files? I suppose I could use another server but I feel like there is a better way

king_kilr
May 25, 2007

agscala posted:

How do you all serve your images and css and other files? I suppose I could use another server but I feel like there is a better way

Another server. All of our static media is served by nginx which also acts as a reverse proxy to apache/mod_wsgi.

bitprophet
Jul 22, 2004
Taco Defender

agscala posted:

How do you all serve your images and css and other files? I suppose I could use another server but I feel like there is a better way

Any serious production server that sees heavy traffic will use another server, which is why that's the "default" in the settings.py commentary.

For something not quite so heavily trafficked, what I usually do is keep them in source control with everything else in a media or similar directory at the top level, then symlink that into my static Apache docroot.

Then just tell Apache to toss the entire URL space to e.g. mod-wsgi, with a Location block saying "...well, except for /media/, just serve that normally".

I posted another example of this earlier in the thread :) a page or 2 back iirc.

jupo
Jun 12, 2007

Time flies like an arrow, fruit flies like a banana.

king_kilr & bitprophet posted:

approaches

We use a combination of these. We can get away with using the same server for Django and static files but through our testing found nginx to beat the pants off Apache for static content. So we have nginx serve static content and proxy out to Apache for Django running on the same server on a different port.

Lamacq
Jun 15, 2001

Breezeblock RIP
I use the nginx/apache/mod_wsgi combination too, except on separate servers. That is, I have one host running nginx for static content (which in my case includes actual static HTML pages, as the CMS we use publishes fully baked HTML files to a web server instead of serving content itself), and then in the nginx configuration I use regexes to specifically reverse proxy django-powered resources to another host that is running apache + mod_wsgi (and the django stuff is actually running side-by-side on that host with a legacy PHP CMS).

Then on the nginx host, I'm exporting some directories via NFS to the apache application server for it to use as its media directories.

The hardest part about getting this setup working was trying to explain to the network & firewall administrators what I was trying to do. Once the firewall rules were in place the rest was pretty straightforward.

agscala
Jul 12, 2008

Oh, so if I was going to deploy a django-powered webpage I made, I'd have to pay for two companies to do my hosting?

e: Sorry if this is a stupid/obvious question. I've never done this before so it's all new territory.

king_kilr
May 25, 2007
Nope, there's no reason you can't run both servers (as in Apache/Nginx) on the same physical server (or virtual server or whatever).

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe
Check these guys out, they will allow you to setup your own server per application. I have an nginx app serving static content and another django app with apache and mod_wsgi doing all the django stuff.

http://www.webfaction.com/

agscala
Jul 12, 2008

Also this is a really simple issue I'm having. I have an apache server set up running on localhost and I've been using django's built-in production server on localhost:8000. Is there a proper way to get MEDIA_URL to work in my templates? When I use it in my template and look at the source in my webpage, the MEDIA_URL defined in my settings.py never shows up in the source. Take a look at the screenshot for reference:

I also tried just having {{ MEDIA_URL }} instead of {{ settings.MEDIA_URL }} but that doesn't work either.

Click here for the full 1400x1010 image.

king_kilr
May 25, 2007
You should be doing {{ MEDIA_URL }} in your templates, but that assumes that you are using RequestContext when you render the template in the view.

agscala
Jul 12, 2008

king_kilr posted:

...RequestContext...

Thanks, I had a feeling I was leaving something out.

taqueso
Mar 8, 2004


:911:
:wookie: :thermidor: :wookie:
:dehumanize:

:pirate::hf::tinfoil:

I'm looking to hire someone to code up a site for my company using Django (w/ Satchmo). SA-Mart thread: http://forums.somethingawful.com/showthread.php?threadid=3223779

SlightlyMadman
Jan 14, 2005

Is there a simple way to add links to other models in an admin model? I know I could do it by overriding admin templates, but it seems like there should be a better way. Basically, I want to provide a link to any foreign key relationships, or to the change pages of any inline elements displayed.

MonkeyMaker
May 22, 2006

What's your poison, sir?

SlightlyMadman posted:

Is there a simple way to add links to other models in an admin model? I know I could do it by overriding admin templates, but it seems like there should be a better way. Basically, I want to provide a link to any foreign key relationships, or to the change pages of any inline elements displayed.

Admin inlines?
http://docs.djangoproject.com/en/dev/ref/contrib/admin/#inlinemodeladmin-objects

SlightlyMadman
Jan 14, 2005


That's fine for editing them, but I want to be able to link to the actual change page (where the object's own inlines are lister, for instance). I also want to be able to link to the change page of any foreign key references, which inlines aren't really right for.

As an example, say I've got three classes: Person, House, and Furniture. They have a straight hierarchical relationship.

From the inline list of Houses on the Person admin page, I want to be able to link to the House admin pages, so that I can get see an inline list of Furniture. I also want the House admin page to have a link back to the Person admin page.

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe
I haven't found a simple way to do this. I had to do this recently for a M2M field which is a bitch to print out by itself. It was a relation for a bunch of printers and their cartridges.

What I did was create a function in the model that creates a bunch of links using the cartridge id and a link to the admin_prefix/modelname/id. Then in the admin I just add the function name to the list_display. Just remember to tell django not to escape that string with function_name.allow_tags = True right under it in the model.

nbv4
Aug 21, 2002

by Duchess Gummybuns

SlightlyMadman posted:

That's fine for editing them, but I want to be able to link to the actual change page (where the object's own inlines are lister, for instance). I also want to be able to link to the change page of any foreign key references, which inlines aren't really right for.

As an example, say I've got three classes: Person, House, and Furniture. They have a straight hierarchical relationship.

From the inline list of Houses on the Person admin page, I want to be able to link to the House admin pages, so that I can get see an inline list of Furniture. I also want the House admin page to have a link back to the Person admin page.

http://pythonblog300246943.blogspot.com/2009/10/view-on-site-links-in-list-view-with.html

You can do something like this, but to the actual admin page instead of the live page.

Mulozon Empuri
Jan 23, 2006

'ello django people

I need to do this: users = User.objects.all().order_by("profile__name"), but I need it to be ordered case insensitive. ['A', 'C', 'd', 'F'] instead of ['A', 'C', 'F', 'd']

Any easy way to do this?

Edit: oh, it works the right way in postgre but not in sqlite..

Mulozon Empuri fucked around with this message at 17:32 on Nov 5, 2009

ATLbeer
Sep 26, 2004
Über nerd

Mulozon Empuri posted:

'ello django people

I need to do this: users = User.objects.all().order_by("profile__name"), but I need it to be ordered case insensitive. ['A', 'C', 'd', 'F'] instead of ['A', 'C', 'F', 'd']

Any easy way to do this?

Edit: oh, it works the right way in postgre but not in sqlite..

Best way I've seen to do is using the .extra() method in a QuerySet

http://docs.djangoproject.com/en/de...ect-params-none

User.objects.all().extra(select={'lower_name': 'lower(profile__name)'}).order_by('lower_name')

Stabby McDamage
Dec 11, 2005

Doctor Rope
Is there an easy way to do user authentication against users on the server itself? ...within a certain group?

I could go with an LDAP setup for something I'm working on, but it would be much easier to auto-create and authenticate with the normal Linux user mechanism for users of a certain group. (The users are NIS authenticated, but there's a locally defined group for our team, which is not encoded in NIS or LDAP.)

king_kilr
May 25, 2007

Stabby McDamage posted:

Is there an easy way to do user authentication against users on the server itself? ...within a certain group?

I could go with an LDAP setup for something I'm working on, but it would be much easier to auto-create and authenticate with the normal Linux user mechanism for users of a certain group. (The users are NIS authenticated, but there's a locally defined group for our team, which is not encoded in NIS or LDAP.)

Well you could write a custom auth backend to do it, I don't know that I'd want to. If you want to do LDAP: http://pypi.python.org/pypi/django-auth-ldap/1.0b7 looks prety good

ATLbeer
Sep 26, 2004
Über nerd

Stabby McDamage posted:

Is there an easy way to do user authentication against users on the server itself? ...within a certain group?

I could go with an LDAP setup for something I'm working on, but it would be much easier to auto-create and authenticate with the normal Linux user mechanism for users of a certain group. (The users are NIS authenticated, but there's a locally defined group for our team, which is not encoded in NIS or LDAP.)

This is what I use in production.

I pass authentication UP the chain to Apache and rely on Apache LDAP to do HTTP Digest authentication against whatever LDAP group you want to go against. Apache will simply just pass back an "authorized user" to Django and the app will just log that user in automatically. Here's a sample from my Django settings.py

code:
MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.RemoteUserMiddleware',
)

AUTHENTICATION_BACKENDS = (
    'django.contrib.auth.backends.RemoteUserBackend',
)
and then relevant portions from httpd.conf from Apache
code:
LoadModule ldap_module         /opt/apache/modules/mod_ldap.so
LoadModule auth_basic_module         /opt/apache/modules/mod_auth_basic.so
LoadModule authnz_ldap_module         /opt/apache/modules/mod_authnz_ldap.so

<Location "/">         
        AuthType Basic
        AuthBasicProvider ldap
        AuthzLDAPAuthoritative on
        AuthName "[Use your NT login/password]"
        AuthLDAPURL ldap://ldap.yourdomain.com/DC=youroa,DC=com?sAMAccountName?sub?(objectClass=*)
        AuthLDAPBindDN "CN=auth_user,CN=users,DC=youroa,DC=com"
        AuthLDAPBindPassword auth_user_password
        Require valid-user
        Satisfy any
        Order allow,deny
</Location>

LuckySevens
Feb 16, 2004

fear not failure, fear only the limitations of our dreams

I'm trying to create a testproject on Windows Vista, everything went smooth until it came to activating the admin panel:

code:

Using the URLconf defined in testproject.urls, Django tried these URL patterns, in this order:

   1. ^admin/doc/
   2. ^admin/

The current URL, , didn't match any of these.
Is my error. I've added django to my PATH in environment variables and even created a new one PYTHONPATH but still no dice. I can create my own apps and everything else seems to work, its just this part I've hit a wall. What should I do next?

LuckySevens
Feb 16, 2004

fear not failure, fear only the limitations of our dreams

Well, after trying to solve this problem I played with some permissions to no avail. When I try and do a from import djangocontrib import admin, I get an error:

code:
File "C:\Python26\Tools\django-1.1.1\django\conf\__init__.py", line 38, in _setup
    raise ImportError("Settings cannot be imported, because environment variable %s is undefined." % ENVIRONMENT_VARIABLE)
ImportError: Settings cannot be imported, because environment variable DJANGO_SETTINGS_MODULE is undefined.
My environmental variables look like this:

code:
C:\Program Files\Subversion\bin;C:\Python26;C:\Python26\Scripts;C:\Python26\Tools;
Django is in Tools, I tried setting a path directly to the django-1.1.1 folder no avail. I enabled PYTHONPATH and tried each combo and nothing as well. I feel like its something obvious I'm missing but I'm backtracking through everything and the settings are all what they should be.

Mulozon Empuri
Jan 23, 2006

ATLbeer posted:

Best way I've seen to do is using the .extra() method in a QuerySet

http://docs.djangoproject.com/en/de...ect-params-none

User.objects.all().extra(select={'lower_name': 'lower(profile__name)'}).order_by('lower_name')

It might just be sqlite loving with the ordering, but I couldnt' quite get it to work. Extra is nice to know about though, thanks.

king_kilr
May 25, 2007

Mulozon Empuri posted:

It might just be sqlite loving with the ordering, but I couldnt' quite get it to work. Extra is nice to know about though, thanks.

That's because that code won't work lower('profile__name') tries to use Django's ORM syntax in pure SQL.

ATLbeer
Sep 26, 2004
Über nerd

king_kilr posted:

That's because that code won't work lower('profile__name') tries to use Django's ORM syntax in pure SQL.

Hmm.... Might be a good suggestion for Django to throw a exception Warning for using an ORM Syntax that isn't 100% compliant against all backends.

king_kilr
May 25, 2007

ATLbeer posted:

Hmm.... Might be a good suggestion for Django to throw a exception Warning for using an ORM Syntaxt that isn't 100% compliant against all backends.

Yeah, Django has better poo poo to do than build a SQL parser, and then build a way to tell which SQL is standard. This is actually one of the most terrible ideas I've ever herad frankly.

bitprophet
Jul 22, 2004
Taco Defender

ATLbeer posted:

Hmm.... Might be a good suggestion for Django to throw a exception Warning for using an ORM Syntax that isn't 100% compliant against all backends.

No, I think what king_kilr was trying to say is that the string values in an extra() clause like that, are all being inserted into the raw SQL, and you were trying to treat them like they were still ORM syntax or something.

Put another way, it's doing SELECT blah, blah,blah, <dict key here> AS <dict value here> FROM tablename WHERE ...". So, extra(select={'lower_name': 'lower(profile__name)'}) is translated into something like SELECT blah, blah,blah, lower_name AS lower(profile__name) FROM tablename WHERE ...".

Which doesn't make any sense, as you can see, because at that point we're talking SQL, not Django ORM keyword-argument stuff. There's no profile__name column.

However, if I'm right, you could do something like extra(select={'lower_name': 'lower(profiles.name)'}), provided you're also using the right stuff to get the profiles table joined into the query so that it forms legal SQL.

Adbot
ADBOT LOVES YOU

nbv4
Aug 21, 2002

by Duchess Gummybuns
since we're talking about extra, does anyone know why this doesn't work?

code:
Flight.objects.all().extra(select={"day": "total - night"}, where=['"day" > 0'])
it just spits out this:

code:
ProgrammingError: column "day" does not exist
LINE 1: ...flight" WHERE "logbook_flight"."user_id" = 3  AND "day" > 0 ...
                                                             ^
but if I leave off the custom 'where' clause, it works fine...

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