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
hey mom its 420
May 12, 2007

Use the template inheritance functionality along with the auth context manager. First off, in your settings.py, check that django.core.context_processors.auth is in the variable TEMPLATE_CONTEXT_PROCESSORS. Then in every view, give it a request context like this.
code:
from django.template import RequestContext

....

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
See that variable you give to the template, that's the request context.

Once you've done that, you can do stuff like
code:
{%if user.is_authenticated%}
  //Login form goes here
{%else%}
  //Link to logout or something
{%endif%}

hey mom its 420 fucked around with this message at 18:17 on Jul 8, 2008

Adbot
ADBOT LOVES YOU

duck monster
Dec 15, 2004

For Django hosting, checkout Slicehost. Its just a dirtcheap vHost, and they are pretty cool guys. Select debian (naturally), apt-get up to python 2.5, follow the apache->django setup and serve django like a motherfucker. too easy.

And by cheap I mean 'absurdly cheap'.

ATLbeer
Sep 26, 2004
Über nerd

duck monster posted:

For Django hosting, checkout Slicehost. Its just a dirtcheap vHost, and they are pretty cool guys. Select debian (naturally), apt-get up to python 2.5, follow the apache->django setup and serve django like a motherfucker. too easy.

And by cheap I mean 'absurdly cheap'.

Thats exactly the deployment set-up I plan on using +memcache

I'm tagging that with AMZN S3 for static file hosting via a CNAME forward media.mydomain.com so I don't have to run lighttp or a second Apache instance. I'm hoping it flys for a time during my ramp up phase.

Has anyone looked at deploying Django with mod_wsgi instead of mod_python. I've heard there are some performance benefits over mod_python but, it looks like you might have to hack your code base a bit to make it compatible. I've googled but, it's a bit sparse.

WickedMetalHead
Mar 9, 2007
/dev/null
webfaction seems to be decent for cheap hosting too.

Allie
Jan 17, 2004

ATLbeer posted:

Has anyone looked at deploying Django with mod_wsgi instead of mod_python. I've heard there are some performance benefits over mod_python but, it looks like you might have to hack your code base a bit to make it compatible. I've googled but, it's a bit sparse.

I've set up Django with mod_wsgi in production environments, I haven't had any problems with it. There is one longstanding issue with Django's WSGI support involving PATH_INFO, but that can be worked around, and the mod_wsgi site has great documentation, including how to deal with Django specifically.

mod_python is a huge piece of poo poo. It's a poorly designed framework around Apache, and you can only use it within Apache. Django abstracts it all away, but personally having dealt with it directly on many occasions, I could never see myself going back to it. I think mod_wsgi is the way to go.

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).

Space Kimchi
Jan 7, 2007

by Peatpot
Oh hey, late to the party :)

I'm developing an in-house django application to administer and keep track of a ton of stuff, and just hit a major milestone of being to where it is feature-complete enough to start using it for real. Aside from deployment being a bit of a bitch (we have and need to use cPanel servers, joy!) I must say I absolutely love Django so far, and Python as well since I'm new to Python. I tried RoR a few times but it never quite "clicked" and I couldn't figure out what was going on; I'd have an idea for something I'd want to do but staring at a blank project template I had no idea where to go there. Django clicked almost immediately, and I was even able to follow along the tutorial and figure out how to change the poll application into the beginnings of the project I now have working great, and surprisingly minimal "oh god that was a dumb noob way to do that" moments that tend to be easy to fix.

So far I really love how much faster it is to make better things than in, well, been using mostly PHP so far. Mostly I like how it is usually easier to and it usually "defaults" to the best practice of doing things, so even when I'm developing under a time crunch I don't feel like I'm making compromises. They really did nail that whole "perfectionists with deadlines" thing. My app makes solid and judicious use of scriptaculous and TinyMCE and a few other things I had never used before, and I was surprised at how easy it was to get something rather advanced functionality-wise going very quickly.

I just really hope migrations are added eventually (although this is promising, but I haven't had time to investigate it: http://www.aswmc.com/dbmigration/ ) and that there somehow becomes a way to create new views without editing and/or creating 3 files across 2 editors though maybe if I set up a proper urlconf I'd have it easier. Still, one of the only things I miss from RoR is that it'd create skeleton files and hook up wires automatically for that sort of thing.

Oh and thanks for the slicehost recommendation earlier, I'm in the market for a new VPS and I had ordered one at another webhost that I totally love for my shared hosting but I've been getting dicked around pretty bad with the VPS. CentOS only (ugh), yum mysteriously missing after the first control-panel-initiated wipe but who cares it loving sucks anyway, only tolerable after a bunch of effort to use debootstrap to get Debian on it (Ubuntu hits something weird that as best I can tell is a kernel bug) and run everything from a chroot. Combine that with some billing issues slicehost solves by being cheaper, well, I hope the positive reviews I hear pan out. :)

e: I hope mod_python doesn't suck too bad, I don't think I have much of a choice for getting cPanel to run this without me wanting to kill myself using anything else

e2: The #django channel on freenode is insanely helpful, good folk there. Just be nice to Magus, he's a bit gruff but he's a saint for as helpful as he is.

Space Kimchi fucked around with this message at 01:10 on Jul 9, 2008

Allie
Jan 17, 2004

bitprophet posted:

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).

Like I said, my beef with it stems from experience with using it directly, i.e. without a framework abstracting it out of the way. When you have a system developed only for mod_python, you can only develop applications on mod_python. This makes any kind of development a huge pain because you can't do it outside of mod_python and Apache, and its code reloading isn't really predictable and doesn't work for applications installed into site-packages.

When you're using it from Django this isn't really an issue, because someone did all the hard work for you already, and you don't have to do development on mod_python. The performance differences between the two modules are basically irrelevant, and I'm not sure what you mean by more "layered." WSGI is a great specification. It doesn't tie you down to any one web server, you can use whatever WSGI server you like. mod_python predates WSGI - it's archaic and unwieldy in comparison now.

The author of mod_wsgi delineates some specific differences between the two modules in this mailing list post. Among more practical differences is the ability to reload specific Python applications (by updating the modification date of a WSGI script file) and the extensive options for setting resource limits on Python processes (e.g. you can reload the processes after N requests, or reload them after N seconds idle time, etc.). I also foresee the Python community moving toward mod_wsgi because of all of these reasons, and because it's still actively developed and specifically designed for a much wider array of use cases (e.g. in shared hosting environments).

Other options include FastCGI/SCGI and flup, but I personally don't use flup anymore because I ran into issues with it timing out long running HTTP connections (where this wasn't an issue with other platforms). It doesn't help that flup isn't really maintained anymore, and the author hasn't responded to my bug reports. There's also no community around it, as far as I can tell.

MonkeyMaker
May 22, 2006

What's your poison, sir?
OK, I can't figure this one out. I'm trying to provide an edit profile method for users to, well, edit their profiles. This includes image uploading. The following function works great for everything except that both their uploaded image and the renamed one get saved to the system. Obviously I only want the renamed one.

code:
def edit_profile(request):
	logged_in = check_logged_in(request.session.get('writer_id'))
	if logged_in:
		w = Writer.objects.get(id=request.session.get('writer_id'))
		if request.POST:
			profileform = ProfileForm(request.POST, request.FILES)
			if profileform.is_valid():
				new_profile = profileform.save(commit=False)
				new_profile.id = w.id
				new_profile.date_joined = w.date_joined
				new_profile.password = w.password
				# new_profile.image = w.image
				if request.FILES:
					result = safe_image(request.FILES['image'])
					if result['status']:
						from django.conf import settings
						from StringIO import StringIO
						from PIL import Image
						image = Image.open(StringIO(request.FILES['image']['content']))
						image = image.convert("RGB")
						image_path = '%s/writer_images/%s_image.jpg' % (settings.MEDIA_ROOT, new_profile.id)
						image.save(image_path, 'jpeg')
						new_profile.image = '%s_image.jpg' % new_profile.id
					else:
						return rtr("writers/edit_profile.html", {
							'errors': result['errors'],
							'profileform': ProfileForm(request.POST, request.FILES)
						})
				new_profile.save()
				return HttpResponseRedirect("/profile/")
			else:
				profileform = ProfileForm(request.POST, request.FILSE)
				return rtr("writers/edit_profile.html", {
					'profileform': profileform
				})
		else:
			profileform = ProfileForm(instance=w)
			return rtr("writers/edit_profile.html", {
				'writer': w,
				'profileform': profileform
			})
	else:
		loginform = LoginForm()
		return rtr("writers/login.html", {
			'errors': ("You're not logged in!",),
			'loginform': loginform,
		})
Anything else I've done stupid, please point out to me.

duck monster
Dec 15, 2004

mod_python is loving terrible, unless you need to do a very small subscript of 'very wierd' apache tasks (such as rolling a http auth driver or something).

I blame it almost entirely for being the reason python is not the dominant web coding language on the net.

And for the loving life of me I still can't work out the caching.

Puddy1
Aug 28, 2004
I'm new to django and python so go easy on me here, but what I'm trying to do is run some code whenever a model is saved to the database, although I don't know how to do that. Is there some sort of method I can overwrite when I save this particular model?

hey mom its 420
May 12, 2007

Yeah, you usually do that by overwriting the save method or by using signals. The way to overwrite the save method is pretty straightforward.
code:
class Car(models.Model):
    manufacturer = models.CharField(_('Manufacturer'), max_length=30)
    model = models.CharField(_('Model'), max_length=20)
 
    def save(self):
        #stuff that will happen before the save goes here
        super(Car, self).save() #don't forget this line!
        # stuff that will happen after the save goes here
As for when to use signals and when to override the save method, well, you usually want to overwrite the save method when it's about something that's closely related to the model (like making a folder on save, auto populating some fields, etc.) and you probably want to use signals when you're sending off emails, doing some sort of reporting or just generally stuff that isn't so closely tied to the model itself.

hey mom its 420 fucked around with this message at 22:31 on Jul 9, 2008

bitprophet
Jul 22, 2004
Taco Defender

Puddy1 posted:

I'm new to django and python so go easy on me here, but what I'm trying to do is run some code whenever a model is saved to the database, although I don't know how to do that. Is there some sort of method I can overwrite when I save this particular model?

http://www.djangoproject.com/documentation/model-api/#overriding-default-model-methods

edit: BONUUUUUUUUUUS :argh:

Sivart13
May 18, 2003
I have neglected to come up with a clever title

MonkeyMaker posted:

OK, I can't figure this one out. I'm trying to provide an edit profile method for users to, well, edit their profiles. This includes image uploading. The following function works great for everything except that both their uploaded image and the renamed one get saved to the system. Obviously I only want the renamed one.
I don't know about your actual problem, but I know personally I have a stylistic dislike of indentation that goes as deep as yours. Since the "else" clause for most of your "if"s ends with a return, I would refactor all the conditionals like this:
code:
if not profileform.is_valid():
  profileform = ProfileForm(request.POST, request.FILSE)
  return rtr("writers/edit_profile.html", { 'profileform': profileform })

new_profile = profileform.save(commit=False)
[[...keep going on with your life at the same level of indentation..]]
There's definitely an argument for doing it either way, and I'm not much of a django developer yet so I don't know how this sort of code is supposed to look in practice, but I've seen too much PHP code that continually opens up "if (poo poo is ok) {}" blocks and ends with a big ugly chain of else.

Space Kimchi
Jan 7, 2007

by Peatpot

duck monster posted:

mod_python is loving terrible, unless you need to do a very small subscript of 'very wierd' apache tasks (such as rolling a http auth driver or something).

I blame it almost entirely for being the reason python is not the dominant web coding language on the net.

And for the loving life of me I still can't work out the caching.

Wait so there IS caching? drat no wonder.

When I installed my app the other day on an actual server using mod_python the admin pages would randomly 404 on me. Like, completely randomly. The next day it was fine.

If this is a sign of things to come maybe I should look into mod_fcgi.

Xenos
Jun 17, 2005

WickedMetalHead posted:

webfaction seems to be decent for cheap hosting too.

I've used webfaction for a few months, and for a shared host they are beyond awesome.

Puddy1
Aug 28, 2004
Thanks Bonus and bitprophet for answering my previous question. I have another one for you guys now. I have this method in my view that gets called when I go to http://thesite.com/blah, but I'm only letting staff access it. The problem is I don't know how to login as staff to test this! I mean, I have the login information, I'm just a web development noob and have no clue how the request.user gets set to a staff member.

WickedMetalHead
Mar 9, 2007
/dev/null
if you have contrib.admin just login via your admin pannel?

WickedMetalHead
Mar 9, 2007
/dev/null
or if your asking how to restrict it, there is a shortcut for that, uh i forget waht it is though.

Space Kimchi
Jan 7, 2007

by Peatpot
It's late and I'm tired and I don't have the energy to go into detail (especially since this is one area I'm still learning a lot about) but look up context instances and what you have to do to access user information from a template. Also look up the decorators; when you include them you can put @login_required in front of a view function to restrict it to logged-in users. There are probably similar ones for staff and admins.

Puddy1
Aug 28, 2004

WickedMetalHead posted:

if you have contrib.admin just login via your admin pannel?

Oh wow, I'm a moron, I was going to the wrong page, I got it working. Thanks.

ege bamyasi
Aug 9, 2004
I'm getting a ViewDoesNotExist error, "Could not import problems.views. Error was: No module named views", when I try to get my app running on Dreamhost. I have views.py and models.py in the subdirectory "problems", and both of them work on my local machine.

I've tried different chmod settings for the files. I also noticed that no .pyc files were being created. I tried doing python compileall.py, which created the .pyc but didn't affect the problem. I don't really understand what process normally compiles the .py files, so I'm not sure what else to do. Any ideas?

bmoyles
Feb 15, 2002

United Neckbeard Foundation of America
Fun Shoe
Do most of you still use projects with Django? I was just reading http://www.pointy-stick.com/blog/2007/11/09/django-tip-developing-without-projects/ and it makes sense. I don't know what's considered best practices though...

WickedMetalHead
Mar 9, 2007
/dev/null
I typically use startproject. But keep all my apps on the python path. Then my apps are not tied to that particular project and are reusable.

saiyr
May 23, 2004

WickedMetalHead posted:

I typically use startproject. But keep all my apps on the python path. Then my apps are not tied to that particular project and are reusable.
I do this as well. I am fine with the defaults that startproject uses, and I don't really think settings.py is overwhelming, so I'm happy with it.

Also, newforms-admin was merged to trunk 2 hours ago.

WickedMetalHead
Mar 9, 2007
/dev/null

saiyr posted:

Also, newforms-admin was merged to trunk 2 hours ago.

oh snap i didnt notice this! Time to play

Sivart13
May 18, 2003
I have neglected to come up with a clever title

saiyr posted:

Also, newforms-admin was merged to trunk 2 hours ago.
This is an epic change. Like, to the level that that trac page should have festive balloons and fireworks following your cursor.

ATLbeer
Sep 26, 2004
Über nerd

Sivart13 posted:

This is an epic change. Like, to the level that that trac page should have festive balloons and fireworks following your cursor.

Followed by rewriting all your models.py files :\

It's a great change just breaks a lot.

king_kilr
May 25, 2007

ATLbeer posted:

Followed by rewriting all your models.py files :\

It's a great change just breaks a lot.

There's a snippet on djangosnippets that tries to automate creating the new admin.py files.

bitprophet
Jul 22, 2004
Taco Defender
Moving to NFA is not actually that hard, I've been using it for a while and had to rewrite my entire book's code examples to conform to it, a few months ago. Didn't take that long, considering.

It's basically just replacing every inner Admin class with either a one-line "registration" of your model with the default admin site (if you did the "class Admin: pass" bit) or the one-line registration plus an external <Model class name>Admin class with whatever options you had in your inner class.

The nice thing is that once you get used to this way of doing things you realize how much neater it is, and it's only one or two extra lines of code per model class, if that, depending on how many admin options you need. This plus the older newforms setup of having distinct ModelForm classes really refactors things so that your models, as chunks of code, are distinct from the forms and/or admin settings that relate to them.

The Red Baron
Jan 10, 2005

Is there any way to get ImageField to work on a Windows machine (for development, of course etc.)? It calls os.path.normpath internally, which causes forward slashes in upload_to to be converted into backward slashes. Needless to say, this doesn't work too well on a web server.

bitprophet
Jul 22, 2004
Taco Defender
That seems like an odd bug to me; what version are you using, 0.96 or some recentish SVN checkout? I would not be surprised if that was something extant in 0.96 that's been fixed more recently.

If it's still around in SVN I'd say it was just overlooked, so look real hard for an existing Trac ticket about it (chances of one existing for something like this are high) and then add a note or patch to that ticket if none exists, or make a new ticket w/ patch if there isn't a ticket yet. Then, of course, feel free to patch your local version until that patch is accepted and merged to trunk :)

The Red Baron
Jan 10, 2005

Latest SVN version, but turns out I was somewhat jumping to conclusions, as it only affects the filename stored in the database and what's shown in the admin interface, not what the end result is. get_FOO_url() returns correct forward-slashed paths as expected :)

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've been playing around with the alpha 1.0 release and newforms-admin and I've run into a roadblock.

I've got three tables that I want to populate from one form. The tables are Volunteer, Address and Qualifications. Volunteer has a ForeignKey field for Addresses and a ManyToManyField for Qualifications. When I use newforms to generate a form for Volunteer, I get choice fields for both Address and Qualifications. The choice field for Qualifications is fine (and is populating fine) but I also get a choice field for Address, when I'd rather it render it's own input fields so users can enter new addresses. I can't find any way to get this to work. Is there documentation on this anywhere? Or any tips? All my attempts end at template exceptions or hard to track down errors.

(I know I could build the form myself and handle the populating of seperate tables in the view, but I can't imagine what I'm trying to do isn't possible, I'm just not looking in the right place).

bitprophet
Jul 22, 2004
Taco Defender
What you want is called "inline editing" and in NFA it's handled with a few admin-related classes. See here for an example, I can't be arsed to find any official docs for it at the moment (not sure if/how any official docs for NFA were merged into the live site docs).

So you just want to make an inline class for Address, and then mention it in an 'inlines' attribute of the admin class for Volunteer, and you should be all set.

vvv Aha, that's where they stuck it, thanks. Will have to read it over to see how well it's improved over the old "docs" aka "a couple of infrequently updated wiki pages" :)

bitprophet fucked around with this message at 13:33 on Jul 28, 2008

king_kilr
May 25, 2007
Here's the inline stuff: http://www.djangoproject.com/documentation/admin/#inlinemodeladmin-objects

Zenobia
Nov 11, 2007

i can't see the captcha image
where is it
Thanks for all the help I've gotten already (especially Bonus).

I'd like to auto-populate the "user" field in a model (foreign key to User) with the current request.user when a ModelForm of this model is submitted. I've searched and found a couple of guides, but they're all from ye olde times before ModelForm. I don't really understand how to use the information in the docs, since I'm currently using generic views.
Do I need to write my own form handling view for this, or is there an easy way to implement this using the update_object generic view?

hey mom its 420
May 12, 2007

Hehe, no problem. If you have a ModelForm, you can pass a keyword argument of commit=false when you call its save method.
code:
f = CarForm(request.POST)
car = f.save(commit=false)
car.owner = request.user
car.save()
For more info, check out the docs on model forms.

Zenobia
Nov 11, 2007

i can't see the captcha image
where is it
I saw that in the docs, but I have no idea where to put that code or if it's possible to use this in conjunction with generic views.

Adbot
ADBOT LOVES YOU

bitprophet
Jul 22, 2004
Taco Defender
In general, anything having to do with "code" implicitly means you can't use it with generic views, since generic views are what they are (namely a way to AVOID writing actual code). In order to use commit=False you'd need to write a wholly custom view for editing, which isn't that bad (it's maybe ten lines of code or so).

It's usually an either-or decision like this; the only time you can mix generics with custom code is if your intended logic can fit around the generic view somehow (such as writing a view which sets up a QuerySet you can't built in a URLconf, and then calls the generic view with that QS, which does the rest of the work).

The big thing about Django, then, is knowing what to use when; when to use the super shortcuts like generics or the admin, vs using the (still very rapid, thanks to the ORM and the forms library and so forth) approach of custom views.

bitprophet fucked around with this message at 02:35 on Jul 29, 2008

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