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
Zenobia
Nov 11, 2007

i can't see the captcha image
where is it
Thanks, I thought it might be possible to subclass the generic views or that the snippet Bonus provided would redefine the save function in the forms file. I wrote my own view to handle the form and everything works perfectly now.

Zenobia fucked around with this message at 12:26 on Jul 29, 2008

Adbot
ADBOT LOVES YOU

MonkeyMaker
May 22, 2006

What's your poison, sir?
I'm using ModelForms for most of my...forms. Anyway, I'd like to wrap required fields in one fieldset and non-required fields in another. Anyone know of any simple way to do this?

bitprophet
Jul 22, 2004
Taco Defender

MonkeyMaker posted:

I'm using ModelForms for most of my...forms. Anyway, I'd like to wrap required fields in one fieldset and non-required fields in another. Anyone know of any simple way to do this?

You mean aside from manually specifying them with fields? (or is it fieldsets now? can't remember which way it changed)

It might be possible to programmatically do it, i.e. define an __init__() to introspect the model's field attributes and (over)write the instance's fields attribute, but that sort of thing doesn't always work well given the metaprogramming surrounding Django classes. Then again, I don't think ModelForm is used anywhere but in your own custom code, which lessens the chance of there being some behind-the-scenes admin related magic or some such. Hard to tell without trying it :)

Wulfeh
Dec 1, 2005

The mmo worth playing: DAoC
So is anyone going to Djangocon? I grabbed a pair of tickets this morning for my boss and I.

jarito
Aug 26, 2003

Biscuit Hider
Saw this on reddit:

http://groups.google.com/group/django-developers/browse_thread/thread/815f76ad7e823cbf?hl=en

Benchmark Performance:

quote:

Summary results:
Signal sends with no listeners in process: 67% faster
Signal sends with no listeners, but 10 other listeners on different signals: 91% faster
Signal sends with 30 weakref receivers: 60% faster
Signal sends with 30 strongref receivers: 67% faster

Semi-Real World (Test Suite):

quote:

I'm seeing about a 40% improvement in
the running of the test suite (from 500s down to 300s). That's just
loving awesome. On top of that the net -500 LOC is very, very nice :)

Seems like 1.0 is going to be quite a bit faster.

Sgt. Raisins
Oct 21, 2007
Damnit
The awesome Geodjango branch got merged in to trunk, hell yeah.

ATLbeer
Sep 26, 2004
Über nerd
God.. Anyone want to rewrite my OP to update it to 1.0? I probably won't be able to get to it for another month or so...

You get good karma and probably instant gold status. :v:

king_kilr
May 25, 2007
And ticket 5361 just hit, this allows for using alternate file system backends, yay!

MonkeyMaker
May 22, 2006

What's your poison, sir?
I'm having a problem with one-to-many relationships. I'm doing an app for writers, so you have Stories and Characters models. I want to use character.story_set.add(story) to add (!) to a list of stories that a character belongs to. This seems to be the right way to do it, according to the docs. It doesn't work, though. I keep getting an error about character not having an attribute 'story_set', even though story is a ForeignKey field in the Character model.

Any suggestions?

I have a feeling I may be going about this entirely backward, too, and need to either do Story.character_set, or do a Many-to-Many relationship.

bitprophet
Jul 22, 2004
Taco Defender
Yes, it sounds like you have it backwards. Here's code based on what I think you just said your setup was:
code:
class Story(models.Model):
    title = models.CharField(max_length=100)

class Character(models.Model):
    name = models.CharField(max_length=100)
    story = models.ForeignKey(Story)
In that scenario -- which is the wrong way to model it, and I'll get to that in a sec -- Character objects would have a .story attribute resulting in a single Story object, and Stories would have a .character_set attribute which is a Manger allowing you to do e.g. .all(), or .add(), to work with the related Character objects. That's how ForeignKey works.

Now, my example code there is a setup where a character can only belong to one story (and, since it's many-to-one, a story can thus have >1 character). I'm guessing you do want ManyToManyField, because a character can often belong to >1 story in addition to stories being made up of >1 character.

Thus, you'd do something like this:

code:
class Character(models.Model):
    name = models.CharField(max_length=100)

class Story(models.Model):
    title = models.CharField(max_length=100)
    characters = models.ManyToManyField(Character)
and then Story.characters is an (explicit) Manager, as is Character.story_set (an implicit Manager created by the ManyToManyField). You can also have a more "readable" or "obvious" setup by specifying the name of the implicit manager, like so:

code:
    characters = models.ManyToManyField(Character, related_name='stories')
and then you'd have Character.stories instead of .story_set.

Note also that M2M is totally arbitrary as to which side of the relationship you define it on -- you could just as easily put a 'stories' ManyToManyField on Character instead, and have the exact same result (assuming you used related_name='characters').

wither
Jun 23, 2004

I have a turn both for observation and for deduction.
I'm so sodding angry. I setup a new server and installed django from the trunk. Everything on my old servers were 0.97-pre and this happened to be 1.0-ALPHA or something. They entirely changed the way files.REQUEST and uploads in general are handled. Broke every god drat thing. I just tarred up my old django-trunk and symlinked it.
If anyone has any idea how to fix this, I'd appreciate it
code:
if 'file' in request.FILES:
                        file = request.FILES['file']
                try:
                        img = Image.open(StringIO(request.FILES['photo']['content']))
                        request.FILES['file']['dimensions'] = img.size
                except:
                        request.FILES['file']['error'] = True
                content_type = file.get('content-type')
                if len(file['content']) > 1024 * 750:
                        raise forms.ValidationError('nein kiddo')
                if content_type:
                        main, sub = content_type.split('/')
                        if not (main == 'image' and sub in ['jpeg','gif','png']):
                                raise forms.ValidationError('wrong file type')
                filename = file['filename']

bitprophet
Jul 22, 2004
Taco Defender
Running Django from trunk is generally very stable bug-wise, but they've never claimed that it would be stable feature-wise, especially now that they're ramping up to 1.0 and thus need to break as much backwards compatibility as is necessary so they don't have to do it after 1.0.

http://code.djangoproject.com/wiki/BackwardsIncompatibleChanges

I think the one you're specifically looking for is here:

http://code.djangoproject.com/wiki/BackwardsIncompatibleChanges#Filestoragerefactoring

Typh
Apr 18, 2003

LAY EGG IS TRUE!!!
So, did anyone get tickets to Djangocon after? If so, let's meet up.

Typh fucked around with this message at 13:02 on Aug 11, 2008

proddo
Mar 13, 2006

A++ would club again
Right, so got a bleeding edge version django running on my bluehost.com shared server, with svn and latest python.

Am running it out of a site subfolder in an addon domain (e.g. "mydomain.com/blah" not "mydomain.com/") with a .htaccess and fastcgi.

Installation works, creating projects and stuff works fine.. just the URLs that are confusing me. The default url for the admin in urls.py is like so:
code:
(r'^admin/(.*)', admin.site.root),
I read up on the docs, and apparently the common middleware automatically attempts to add trailing slashes. Visiting /blah/admin will give a 404, but /blah/admin/ maps fine into that pattern. This confuses me. A lot. Shouldn't it just add a '/' and resolve correctly?

I'm guessing it's because at some stage, django thinks it's running relative to '/'. I can't set django.root in my apache config (it's a shared host) so I'm limited to tinkering with Settings.py and .htaccess.

My .htaccess:
code:
AddHandler fcgid-script .fcgi
Options +FollowSymLinks
RewriteEngine On
RewriteBase /
RewriteRule ^(adminmedia/.*)$ - [L]
RewriteRule ^(django\.fcgi/.*)$ - [L]
RewriteRule ^(.*)$ /blah/django.fcgi/$1 [L]
my django.fcgi:
code:
#!/home/myusername/bin/python
import sys, os
sys.path.insert(0,"/home/myusername/django_src")
sys.path.insert(0,"/home/myusername/django_projects")
from fcgi import WSGIServer
os.environ['DJANGO_SETTINGS_MODULE'] = 'myapp.settings'
from django.core.handlers.wsgi import WSGIHandler
WSGIServer(WSGIHandler()).run()
Now I don't know if I've set it up incorrectly; maybe I've missed something. It just seems that the URLs will not resolve correctly when appending slashes whilst the django folder is not running at "/". I've got round this with a filthy hack - suggested by one of the guys in #django:

urls.py:
code:
from django.conf.urls.defaults import *
from django.http import HttpResponseRedirect

# hack to force trailing slashes on and prepend '/blah/' 
def redirect (request,url):
	return HttpResponseRedirect('/blah/'+url+'/')

# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
	# append trailing slash if needed
	(r'(?P<url>.*[^/]$)', redirect),
	
	# Uncomment the next line for to enable the admin:
	(r'^admin/(.*)', admin.site.root),
)
And this works just fine - chucks slashes onto the end of things and resolves relative to /blah/. Feels like a dirty hack though, and I'm ashamed of it.

Any ideas? tldr: running django from inside a sub folder, url resolution is buggy. help!

proddo fucked around with this message at 13:34 on Aug 11, 2008

deimos
Nov 30, 2006

Forget it man this bat is whack, it's got poobrain!
Does anyone have any good resources for running django on CentOS under WSGI? I am having trouble getting it to work.

king_kilr
May 25, 2007
If anyone is interested I have a django application(open source, BSD license) for doing ajax validation for your forms(ie, you have a form and want to be able to validate in over ajax using the form classes you already created in python). You can check it out at http://github.com/alex/django-ajax-validation/tree/master if you use git or http://code.google.com/p/django-ajax-validation/ if you use SVN.

No Safe Word
Feb 26, 2005

If there are any Houston-area Django lovers in the area, the Houston Python Meetup group is having an Introduction to Django meetup Tuesday, August 26th. Come on out!

Space Kimchi
Jan 7, 2007

by Peatpot

deimos posted:

Does anyone have any good resources for running django on CentOS under WSGI? I am having trouble getting it to work.

I managed to get apache/modpython working on CentOS but I'm starting to regret it a little as it likes to do things like cache error messages and never ever let them go (although restarting apache seems to clear things up). I can't find any information on where the cache is or how it works or how to tweak or disable it, it's kind of frustrating :(

deimos
Nov 30, 2006

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

Space Kimchi posted:

I managed to get apache/modpython working on CentOS but I'm starting to regret it a little as it likes to do things like cache error messages and never ever let them go (although restarting apache seems to clear things up). I can't find any information on where the cache is or how it works or how to tweak or disable it, it's kind of frustrating :(

It's not "not letting them go" each apache child has it's mod_python which has it's corresponding copy of the source running, you have to apache2ctl force-reload (pretty sure force-reload works, but might actually need a restart).

This is why if you make a site-breaking mistake it can take several refreshes to reflect it on Apache.

Git
Aug 21, 2004

Sounds like you guys need to play with Apache's MaxRequestsPerChild option. I'm pretty sure the Django docs recommend giving it a value of 1 for development so code changes are reflected instantly.

deimos
Nov 30, 2006

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

Git posted:

Sounds like you guys need to play with Apache's MaxRequestsPerChild option. I'm pretty sure the Django docs recommend giving it a value of 1 for development so code changes are reflected instantly.

I don't even use apache for development. I use ./manage.py runserver <ip>:8000 when testing the mod_python config I just /etc/init.d/apache2 restart on the test install if I made a mistake then pushed live.

Space Kimchi
Jan 7, 2007

by Peatpot

Git posted:

Sounds like you guys need to play with Apache's MaxRequestsPerChild option. I'm pretty sure the Django docs recommend giving it a value of 1 for development so code changes are reflected instantly.

The problem is this was on deployment, and the wrong config file got slipped in, causing all hell to break loose.

Thanks for the explanation deimos, this makes sense. Also I'll make a note that if I ever need to hotfix the live server it'd be a good idea to restart apache before walking away from it, ha.

No Safe Word
Feb 26, 2005

Django 1.0 beta1

:woop:

wither
Jun 23, 2004

I have a turn both for observation and for deduction.
Does that mean the trunk is frozen?

Edit: Ahh thank god.

wither fucked around with this message at 11:16 on Aug 17, 2008

mwarkentin
Oct 26, 2004
I believe they're in feature freeze now.. bug fixes from now until release.

beerinator
Feb 21, 2003
I've inherited a django project that I am trying to figure out. I've never done any django or python for that matter, so forgive me if I am not totally understanding some things. The old django developer is long gone and it is just me trying to bootstrap myself into figuring things out.

I'm not sure why things are set up the way they are on this server, but I really feel like something might be strange. Here is what I see.

When I log into plesk I see the domain.com and I see two subdomains (mail and media). When I go into file manager (or ftp in) I see nothing at all in the main domain except for plesk template stuff.

When I look at the source code for the pages in html for the main domain.com pages I see that all js and css files are hardcoded to media.domain.com. Why would these css and javascript files be in a subdirectory of the main site?

When I ssh into the media subdirectory folder I see all the folders are owned by root and they are looking like this:
css -> /home/django-apps/domain/media/css
js -> /home/django-apps/domain/media/js

Is any of this typical django behavior? Or was the last guy doing things a bit odd?

bitprophet
Jul 22, 2004
Taco Defender
I'm not sure it's that strong a Django convention; I certainly never do it that way, instead preferring to use http://mydomain.com/media/css/ or similar. However, the core Django team does do it this way -- have a separate subdomain for media files -- and the way Django is set up makes it pretty easy to do this.

Keeping your media files within your Django project, by the way, is definitely a convention, as it lets you keep everything in the same place. One usually then symlinks the media directory/ies to the actual Web server's docroot so they are statically served. I think that's what you're seeing, but can't tell for sure without seeing what else is in the directory structure you mentioned.

EDIT: OK, yea, I think you posted the literal output of `ls` there? Those are symlinks as I mentioned. So, yes, that particular thing -- just having a couple symlinks in your docroot and nothing else -- is definitely a convention and a good way of doing things.

Honestly I'd be more worried that Plesk is involved :v:

bitprophet fucked around with this message at 16:48 on Aug 16, 2008

Space Kimchi
Jan 7, 2007

by Peatpot

bitprophet posted:

Honestly I'd be more worried that Plesk is involved :v:

Yeah this. But the idea behind Django's media server stuff is that apache/(*snicker*)IIS/whatever are much faster at serving up files than the Django framework is. Why load up the entire goddamned python engine just to serve a static file? As such, the css, etc. is supposed to be given its own subdomain or otherwise served up straight from the web server, which is better and faster at serving static files.

Jo
Jan 24, 2005

:allears:
Soiled Meat
I'm missing something really stupid, but I just can't figure it out.
In my views.py I have the line `results = DatabaseImage.objects.filer(blahblahblah)`, but I'm getting the error, "global name 'DatabaseImage' is not defined", despite having the entry DatabaseImage in my models.py. What could be causing this?

EDIT:
Relevant lines from views.py:
code:
searchHashObject = sha(file['content']);
searchHash = searchHashObject.hexdigest();
print searchHash;
results = DatabaseImage.objects.filter( hashValue=searchHash ); ...
if results.size > 0:
result = results[0];
Relevant lines from models.py:
code:
class DatabaseImage( models.Model ):
  # hashValue is sha256sum
  hashValue = models.CharField(maxlength = 64, primary_key = True);
  specialHash = models.CharField(maxlength = 128);
  image = models.ImageField(upload_to = '/home/jo/images');

Jo fucked around with this message at 05:10 on Aug 18, 2008

No Safe Word
Feb 26, 2005

Jo posted:

I'm missing something really stupid, but I just can't figure it out.
In my views.py I have the line `results = DatabaseImage.objects.filer(blahblahblah)`, but I'm getting the error, "global name 'DatabaseImage' is not defined", despite having the entry DatabaseImage in my models.py. What could be causing this?

EDIT:
Relevant lines from views.py:
code:
searchHashObject = sha(file['content']);
searchHash = searchHashObject.hexdigest();
print searchHash;
results = DatabaseImage.objects.filter( hashValue=searchHash ); ...
if results.size > 0:
result = results[0];
Relevant lines from models.py:
code:
class DatabaseImage( models.Model ):
  # hashValue is sha256sum
  hashValue = models.CharField(maxlength = 64, primary_key = True);
  specialHash = models.CharField(maxlength = 128);
  image = models.ImageField(upload_to = '/home/jo/images');

You're missing the import to let it know what DatabaseImage is
code:
from appname.models import DatabaseImage

bitprophet
Jul 22, 2004
Taco Defender
What he said. Python is generally very explicit: it only knows about the names you've told it about. So in any random .py file, such as your views.py, you can only refer to classes or functions or modules that you've explicitly imported.

Do you come from a Rails background? Ruby/Rails is much less explicit and has a lot more magic, which could definitely cause a bit of confusion if you're then new to Python.

The Real Ambassador
Apr 9, 2005

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

Space Kimchi posted:

Yeah this. But the idea behind Django's media server stuff is that apache/(*snicker*)IIS/whatever are much faster at serving up files than the Django framework is. Why load up the entire goddamned python engine just to serve a static file? As such, the css, etc. is supposed to be given its own subdomain or otherwise served up straight from the web server, which is better and faster at serving static files.
Also there are companies out there that will host your static files.

Space Kimchi
Jan 7, 2007

by Peatpot

The Real Ambassador posted:

Also there are companies out there that will host your static files.

You mean like the one you're paying to run your Django application on? :confused:

ATLbeer
Sep 26, 2004
Über nerd

Space Kimchi posted:

You mean like the one you're paying to run your Django application on? :confused:

Offload your statics files to S3 or any other CDN. It's usually cheaper and faster* than either double tasking an app server or by getting another hosting account just for static media.

*cheaper and faster is not universal. As always depends on scale and your costs. In general though it is comparable and efficient.

The Real Ambassador
Apr 9, 2005

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

Space Kimchi posted:

You mean like the one you're paying to run your Django application on? :confused:
Lots of people like to host their static content on different servers. For example you could use a content distribution network like Akamai. These are networks that can host your files in geographically disperse areas so the number of hops between your visitor and static content (which is like 80% of the bandwidth) is much lower. It also helps take load off your server.

You might also want to just setup another dedicated server for static content running like nginx instead of apache.

In these situations it's helpful to be able to configure MEDIA_URL.

Edit: beaten :(

mwarkentin
Oct 26, 2004
I just set web faction up to host static files.. super easy.

Jo
Jan 24, 2005

:allears:
Soiled Meat

No Safe Word posted:

You're missing the import to let it know what DatabaseImage is
code:
from appname.models import DatabaseImage

EDIT:
From Hotsauce.MAIN.models
:downs:

Jo fucked around with this message at 18:55 on Aug 18, 2008

Space Kimchi
Jan 7, 2007

by Peatpot

The Real Ambassador posted:

Lots of people like to host their static content on different servers. For example you could use a content distribution network like Akamai. These are networks that can host your files in geographically disperse areas so the number of hops between your visitor and static content (which is like 80% of the bandwidth) is much lower. It also helps take load off your server.

You might also want to just setup another dedicated server for static content running like nginx instead of apache.

In these situations it's helpful to be able to configure MEDIA_URL.

Edit: beaten :(

The confusion was that Akami and friends aren't necessarily Django-specific and anything can link to anything, so I don't see where it's a particularly big deal, although good point (and another point to Django) that setting up something like Akami for a properly-configured Django site application would take less than 5 minutes. :)

king_kilr
May 25, 2007
new docs stuff just hit django, you can check out the hotness at http://docs.djangoproject.com/

Adbot
ADBOT LOVES YOU

jupo
Jun 12, 2007

Time flies like an arrow, fruit flies like a banana.
Anyone have any feedback on hosting django with http://webfaction.com ?

Looking to put my first app up and I've only heard good things about these guys so far.

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