I just used the mimetypes python standard library to guess filetypes via file names.
It assumes the user followed naming conventions and does not attempt to read the data.
I just used the mimetypes python standard library to guess filetypes via file names.
It assumes the user followed naming conventions and does not attempt to read the data.
How to make SSL work on Django when the certification is done on the front-end server & apache is only listening on http.
I have nginx working as a reverse proxy for Apache / mod_python serving Django, somewhat according to the instructions here:
http://lethain.com/entry/2007/jul/17/dreamier-dream-server-nginx/
Basically, Nginx sits in the front, and forwards all requests but /media/ to apache.
My problem arose when I wanted to implement this SSL Redirect middleware: http://www.djangosnippets.org/snippets/880/
Last time I set up SSL on Django, I had nginx forward HTTPS requests to a separate apache virtual host, also listening on port 443. The SSL certification was on apache, so Djangos request.is_secure() returned True with no problems.
This time though, I have nginx dealing with the SSL, and forwarding the request to the same apache as regular http (one apache vhost), so apache is blissfully unaware of ssl. This means request.is_secure() always returns false, which means the SSLRedirect middleware endlessly loops around a redirect. Endlessly redirecting because is_secure() always returns False.
To fix the problem I just set up my nginx to add a header “HTTP_X_FORWARDED_PROTOCOL” = “https”
and replaced the request.is_secure() in our SSLRedirect middleware with a check to first see if the above mentioned header is in request.META, and then if its value is ‘https’. Return true if that is the case, and we successfully get a redirect.
I guess the value of it doesn’t matter, just that it exists vs not, but that feels very dirty.
Update:
You must edit the above mentioned snippet somewhere in the _is_secure(self, request): definition.
Add:
if 'HTTP_X_FORWARDED_PROTOCOL' in request.META:
return True
and edit nginx.conf (mine lives in /etc/nginx/nginx.conf):
Wherever you have your nginx listening on port 443, you know, something likeserver { listen 443; ...:add a
proxy_set_header X-Forwarded-Protocol https;to your configuration where you have your other headers set (right inside the location brackets).Restart nginx and apache and you are good to go.
So just now on IRC somebody was suggesting “DjangoSniffer” (was referring to djangosnippets.org but djangosnippets is so blatantly obvious & impossible to forget, that nobody questioned it) which lead to a correction: “DjangoSniff”? which lead to me searching django+sniff on google, and #1 result was: http://www.flickr.com/photos/jacqamoe/2382980232/
Django the cat, sniffing something.
Categories: Django
Tagged: Django, Django Sniff, Djangosniffit
The last extremely simple post about “How to get the object instance primary key in Django” reminded me of something.
Here’s something that I never really knew how to use until stumbling across it randomly some months ago.
Ever have a random object that you don’t know the fields of?
Or ever not remember whether your field was called short_description or shortdescription?
You can print all keys like so:
for key in your_object.__dict__.keys():
print key
For more depth: you can try dir(your_object)
The built-in function dir() is used to find out which names a module defines.
Another update from SmileyChris! Hey, theres a reason I don’t ask #Django about every little question. This way, at least, everybody gets to learn when the question is searched on google. IRC Logs never make it up there ![]()
SmileyChris:
Better to access the names via the Model meta options: [f.name for f in model_or_instance._meta.fields]
As a secondary hint, if you just need to “get” one field instance, you can use ._meta.get_field(‘field_name’)
Thanks!
Somebody asked on #Django IRC: what is an easy way to get an objects primary key? I was shocked to hear he couldn’t find it on google.. and I guess it’s true. This is probably the very first stepping stone in learning Django.
I say: Do the Django Tutorials, they are short, well written, and fun!
Besides, its got a hassle-free return policy (90 days).
Well, uh…
object_instance.id = your primary key
Wait… I was wrong. here’s an update from SmileyChris:
Actually, object_instance.pk would be more correct. “id” is just the default primary key field, whereas “pk” is an alias to the field which is defined as the primary key.
Categories: Django
Tagged: Django, Primary Key
Often times it’s necessary to have data stored PER user. A perfect example of this (and my particular problem) is/was a shopping cart: the core of any e-commerce site.
How do we do that? One of the problems is that the users in question are anonymous users. If they were registered users, we could easily take request.user and identify them that way. For anonymous users, we need cookies to identify who’s who.
Luckily Django automatically generates nice cookies that ID the user in a secure fashion (not anything like: logged_in=1) so most of the work is done.
Basically, request.session is a mutable dictionary. Fantastic!
That means you can literally do something like this:
request.session['Arbitrary'] = 'This is Arbitrary Data'
and retrieve it any time you wish in the same fashion:
data = request.session['Arbitrary']
This is useful for a shopping cart because you can create a cart, and put its ID in request.session to know which user session it belongs to.
like so:
newcart = Cart()
request.session['shopping_cart'] = newcart.id
and every time you need to access a users cart request.session['shopping_cart']identifies the cart they are using!
Note: You would have write a statement so that a new cart is created if request.session['cart'] is blank. You should have a check in place to do that. If not request.session['shopping_cart'], create cart, else get cart.
This clearly isn’t limited to shopping carts though… Cool stuff.
Categories: Django
Tagged: Arbitrary Data, Django, Shopping Cart
If you are wondering what part of your Django model is wrong because it is spitting out a nameless IntegrityError, it might be this:
I had a model with Unique=True & Blank=True that caused description-less IntegrityErrors because with two objects that have a field ” (blank), or Null, it was no longer unique.
I wanted the field to be Unique, IF and only if it was not blank or null.
I’ll just use Blank=True, null=True and let it be not unique if it ever does.
If you need to create a form preview and confirmation page in Django, you can always find the snippets online or read the docs http://www.djangoproject.com/documentation/form_preview/
I think we can all agree Django has some amazing docs. It warrants the common IRC response: “This is the answer to your question, as the docs clearly state”.
I want to note that this is not what I recommend doing. Use some of the more robust form preview classes. But for purposes of LEARNING, I think it is great to make something on your own. It’s the only way I learn, at least. Programming devices beyond my skill level are as good as magic to me.
So, a few months ago I was making some forms and wanted a form preview, but I couldn’t figure out how to make it. You know, those things where you click “continue” and the next page redisplays all of your data and says: “Please make sure this information is accurate”.
Anyways, being new to Django myself, I wanted to make my own instead of downloading a snippet. Again, I can’t learn that way. It stays magic, and I’m not trying to learn magic.
I just thought of a simple workaround and put a hidden form field in the form whose value is changed depending on the submit stage.
Turns out that is exactly how the form_preview works!
Basically, a simple data entry view would look like this:
from myapp import myform
def entry(request):
if request.POST:
form = myform(request.POST)
if form.is_valid():
form.save()
return render_to_response('form.html',{'form':form})
form = myform()
return render_to_response('form.html', {'form':form})
This would render the form, and on POST, it would call save() if form is valid. Otherwise, re-render the form w/ errors.
To change this to accept a confirmation view, add a hidden variable to your form Template.
How about something like this:
<input type="hidden" name="stage" id="id_stage" value="{{ stage }}"/>
Now we can pass the stage variable to the template via the view.
def entry(request):
if request.POST: #If POST
form = myform(request.POST) #fill form data
if form.is_valid():
if request.POST['stage'] == '1':
form.save()
return render_to_response('form.html', {'form':form, 'stage':'1'}) #Set stage to 1 since form is valid
return render_to_response('form.html', {'form':form})
form = myform()
return render_to_response('form.html', {'form':form})
You can see that this now adds the value “1″ to hidden field “stage” if the form is valid. It then re displays the form. If you POST again while stage == “1″, the form saves. If the form is not valid , the original form is redisplayed anyways and stage is blank.
So, it turns out the form_preview does basically this with some clever tricks that is useful to look at.
Enjoy!
Categories: Django
Tagged: Django, Form Preview, Forms, form_preview