views:

38

answers:

3

Hey,

I want to set up a Django server that allows certain users to access certain media. I'm sure this can't be that hard to do and I'm just being a little bit silly.

For example I want USER1 to be able to access JPEG1, JPEG2 and JPEG3 but not JPEG4, and USER2 to be able to access JPEG3 and JPEG 4.

[I know I should be burnt with fire for using Django to serve up media, but that's what I'm doing at the moment, I'll change it over when I start actually running on gas.]

A: 

You just need to frob the response appropriately.

Ignacio Vazquez-Abrams
Thanks, I hadn't seen this page. RTFM and all that...
A: 

You can put the media in http://foo.com/media/blah.jpg and set up a media/(?P<file>.*) in urls.py to point to a view blahview that checks the user and their permissions within:

from you_shouldve_made_one_anyways import handler404
def blahview(request,*args,**kwargs):
  if cannot_use( request.user, kwargs['username'] ): return handler404(request)
  ...

Though just to be clear, I do not recommend serving media through Django.

eruciform
I super, double promise not to serve media through Django when it starts becoming important.Thanks thou, your example makes it a bit clearer.
A: 

You can send a file using django by returning the file in the request as shown in Vazquez-Abrams link.

However, you would probably do best by using mod_xsendfile in apache (or similar settings in lighttpd) due to efficiency. Django is not as fast at sending it, one way to do so while keeping the option of using the dev server's static function would be http://pypi.python.org/pypi/django-xsendfile/1.0

As to what user should be able to access what jpeg, you will probably have to implement this yourself. A simple way would be to create an Image model with a many-to-many field to users with access and a function to check if the current user is among those users. Something along the line of:

if image.users_with_access.filter(pk=request.user.id).exists():
    return HttpResponse(image.get_file())

With lots of other code of course and only as an example. I actually use a modified mod_xsend in my own project for this very purpose.

Jens Alm
Thanks for this. This is both parts of what I wanted to know even if I wasn't very clear with describing it.Sorry I can't upvote the answer more.