In Django humanize naturalday filter, you could not get the time part since a programming issue, If you apply it like:
{% load humanize %}
{{ response.date_submitted|naturalday:"Y/n/j H:i" }}
You can get 'today', 'yesterday', 'tomorrow' or empty, but you can not get such as '2009/9/10 11:56'
So I change it like above code. Now you can get 'today', 'yesterday', 'tomorrow' or '2009/9/10 11:56'
If you want anonymous visitors to your site, or parts of your site to be authenticated as real users so that you can treat them as such in your views and models, use this snippet. Add the above AuthenticationBackendAnonymous middleware into AUTHENTICATION_BACKENDS in your settings.py and use the snippet anonymous_or_real(request) in your views, which returns a user. Comment out the bit where it creates a profile if you are not using profiles.
This trick is for caching a view only if it passes some condition, for example, if there are more than zero items in a list. The same methodology could be used for conditional applying of other decorators.
Use HTTP Authorization to log in to django site.
If you use the FORCE_HTTP_AUTH=True in your settings.py, then ONLY Http Auth will be used, if you don't then either http auth or django's session-based auth will be used. This assumes that the regular auth middleware is already installed.
If you provide a HTTP_AUTH_REALM in your settings, that will be used as the realm for the challenge.
Having both a decorator and a middleware means that for site-wide http auth, you only need to specify it once, but the same code can be used as a decorator if you want part of your site protected using htty basic auth, and the other bits freely visible.
Of course, since this is basic auth, then you need to make sure your site is running under SSL (HTTPS), else your users passwords are effectively transmitted in the clear.
Based loosely on [Eric's middleware](http://ericholscher.com/blog/2009/sep/5/debugging-django-production-revisited/), this middleware will show the technical 500 page (which you'd get if DEBUG == True) to any user who is (1) superuser and (2) a member of the settings.TECHNICAL_500_GROUP_NAME group. (If no setting exists, 'Technical Errors' is the presumed group name.
I agreed with the comments that caching should be unnecessary given the (presumptive) edge case of exception + superuser. Assuming you don't have tons of superusers, this code is a good bit simpler.
This template filter, "jumptime" will find any timecodes in a chunk of text and convert them to links that can be used to jump a video player to that point. E.g., If there is the string "3:05", it will be converted into a link that can be used to jump to that point. This is similar to what youtube does.
For information on how to implement, see Django's [custom template tag information](http://docs.djangoproject.com/en/dev/howto/custom-template-tags/#howto-custom-template-tags).
You'd use this with some javascript like this:
`jQuery(document).ready(function(){
jQuery('a.jumpToTime').bind('click',function(){
player.sendEvent('PLAY');
player.sendEvent('SEEK', jQuery(this).attr('value'));
});
});`
This adds an 'fbshell' management command which starts up a Python shell with an authenticated [pyfacebook](http://code.google.com/p/pyfacebook/) instance ready to make requests.
This is very useful for testing out facebook requests or performing administration tasks without hooking a debugger into your application.
This snippet should be saved to
/yourproject/management/commands/fbshell.py
See [custom management commands](http://docs.djangoproject.com/en/dev/howto/custom-management-commands/) for a description of how this works.
If you are already using pyfacebook in your app then you'll already have the right settings, so just run :
$ python manage.py fbshell
A browser window will pop up, prompting you for authentication (unless you're already logged in to facebook). Press enter in the shell when you're finished this, and you'll be dropped into a shell with the session key, uuid, and name printed.
Now you can use the facebook instance:
>>> facebook.friends.get()
>>> [...]
If you haven't used pyfacebook in your app, you'll need at least the following settings in your settings.py
FACEBOOK_API_KEY = 'your_api_key'
FACEBOOK_SECRET_KEY = 'your_secret_key'
Truncates a string after a certain number of chars.
Question:
> *Why don't you use the built-in filter slice?*
I need the "three points" (...) only when it really truncates.
Adds http://hostname or https://hostname before every URL generated by a Django url function.
**Example:**
Normally, something like YourModel().get_absolute_url() would return `/2009/09/02/slug`. However, this is not an absolute URL, because it does not include an HTTP schema or host.
With this middleware, YourModel().get_absolute_url() will return `http://yourdomain.com/2009/09/02/slug`.
This will also work for calls to reverse() or the {% url %} template tag.
**Installation:**
Drop this code into yourproject/middleware/scriptprefix.py.
**Usage:**
In your settings.py, add:
MIDDLEWARE_CLASSES = (
# ...
'yourproject.middleware.scriptprefix.ScriptPrefixMiddleware',
# ...
)
A formset class where you can add forms as you discover the need within your code. There is also the ability to add ManagmentForm fields.
If you ever found yourself in a situation where 1) you have repeated forms that need to be displayed in different locations, or 2) if you find the application logic works better if you add forms as you discover you need them, this code will help you out.
Below is pseudo code based on a real implementation I used. Each form had a save button and the SELECTED_PAYMENT field was set through JavaScript. It is very difficult to use JavaScript with repeated forms, without using a formset.
from myProject.myApp import myFormsUtils
from myProject.myApp.forms import PaymentForm
SELECTED_PAYMENT = 'SELECTED_PAYMENT'
# extra_fields format: {Field name: (Field type, Initial value)}
l_extra_fields = {SELECTED_PAYMENT: (forms.IntegerField, -1)}
PaymentFormSetType = myFormsUtils.formset_factory(PaymentForm, extra=0, extra_fields=l_extra_fields)
if request.method == 'POST':
paymentFormSet = PaymentFormSetType(data=request.POST)
if paymentFormSet.is_valid():
li_curFormIdx = pagaFormSet.management_form.cleaned_data[SELECTED_PAYMENT]
paymntForm = paymentFormSet.forms[li_curFormIdx]
... do stuff ...
# To generate the formset
paymentFormSet = PagamentoFormSetType()
# You can re-add a form retrieved (as in the one above)
l_form = paymentFormSet.add_form(paymntForm)
# Or use the add function just like creating a new form
l_form = paymentFormSet.add_form(personID=argPersonID, propID=argPropID, year=argYr, amt=lc_Amt)
I then stored the `l_form` variables above directly into a unique Context structure and displayed them each individually in my template. Of course this also meant that I also had to output the `paymentFormSet.management_form` explicitly within my template.
EDIT 09-11-2009: Modified the initial_form_count() method to properly handle initial form values in conjunction with dynamically added forms.
This view snippet is a helper for implementing file download handlers. There is a standard to encode Unicode filenames properly, but many browsers have different protocols.
The default encoding is assumed to be UTF-8.
This function lets you save an instance of a model to another database based on a connection argument. Useful when doing data migrations across databases. Connection is anything that would work as a django.db.connection
I'm not sure if this handles proxy models or model inheritance properly, though.