This is a ModelForms-based rewrite of the create_object and update_object generic views, with a few added features. The views now accept a "form_class" argument optionally in place of the "model" argument, so you can create and tweak your own ModelForm to pass in. They also accept a "pre_save" callback that can make any additional changes to the created or updated instance (based on request.user, for instance) before it is saved to the DB.
Usage: just save the code in a file anywhere on the PythonPath and use the create_object and update_object functions as views in your urls.py.
**Update**:
[Django AdMob](http://github.com/johnboxall/django_admob/tree/master) pluggable app on github.
Given a Django ``request`` object and dict of admob parameters returns a Admob ad.
If no ad can be retrieved displays a one pixel Admob tracker image.
For the future:
* Make a template tag for this?
* Filter out other unneeded META parameters for the admob_post dict?
While we're on the topic of SSLRedirect (See snippet 240 and 880) here's what I add to the end of my ssl middleware module, so that SSLRedirect wont break my automated testing.
It simply creates a dummy middleware class that removes the SSL argument, but does not do any redirecting. If you were to simply remove the middleware from settings, the extra SSL argument will then get passed on to all the relevant views.
Of course, you'll need to define a TESTING variable in settings, or change this to something else like settings.DEBUG. Having the separate variable for testing allows you to run your server in DEBUG mode without side effects like the change above.
Add-on for auth app of newforms-admin branch, adding more information about users and their groups at user and group list in admin interface. Also, nice example on customization of contributed django admin apps.
It adds the following to the user list interface: fields for is_superuser and is_staff, last login time; by default, short names of groups user is in (mousehover to see full names)
It adds the following to the to group list interface: list of users in your groups.
To enable, just put it somewhere and import it from your main urls.py:
import useradmin
Sometimes I need to truncate a string after a number of characters, usually to avoid breaking the page layout. When the string we have to truncate is a filename I don't want to hide its extension so a user can easily recognize the file.
My solution is add the ellipsis at the middle of the string converting
`ALongLongLongTitleDocumentThatExemplifiesThisSnippet.txt`
into
`ALongLongLong...hisSnippet.txt`
This is a simple helper to make custom permission decorators for Django views.
Perhaps you have an edit_comment view which you want to make sure current user is the owner of:
>def edit_comment(request, comment_id):
>>if request.user == Comment(id=comment_id).user:
>>>... do authorized things ...
>>else:
>>>... do unauthorized things ...
>>...
>>...
In this view, you might do a quick check `if request.user == Comment(id=comment_id).user`, however you now need to duplicate this code all over the place whenever you want to check if a comment is owned by the current user.
Instead, you can use the built in login_required decorator, and your own decorator to do the test:
>@permission
>def user_owns_comment(request, comment_id):
>>return request.user == Comment(id=comment_id)
>
>@login_required
>@user_owns_comment
>def edit(request, comment_id):
>> ...
>> ...
>> ...
The "tester" function will post a message using the messages module built into Django, and redirect the user to the root. It allows access and executes the view if the tester function returns anything that evaluates to True.
Your permission tester should either strictly specify the same arguments as the view, or take additional *args, and **kwargs to prevent syntax errors on extra arguments being passed along.
This snippet provides support for dynamically importing templates. This helps you to avoid naming collisions and other problems.
The format is as follows:
1. `module.submodule.app:template.html`
2. `module.submodule.app:subfolder/template.html`
3. `module.submodule.app:/subfolder/template.html`
Assuming the module is located in '/var/', these would map (respectively) to:
1. `/var/module/submodule/app/templates/template.html`
2. `/var/module/submodule/app/templates/subfolder/template.html`
3. `/var/module/submodule/app/templates/subfolder/template.html`
The colon splits the the python module from the template directory, meaning you can import from anything that has a "templates" directory. This helps me to avoid naming collisions by specifying the application I'm referring to, without having to put long paths in my extends and include tags inside other templates. It's also dynamic in that if I move a library outside the old path, it has no effect on the templates.
To get this rolling, in your `settings.py` file, add the following::
>TEMPLATE_LOADERS = (
> 'addons.template_loader.load_template_source', # <--- add this
> 'django.template.loaders.app_directories.load_template_source',
> 'django.template.loaders.filesystem.load_template_source',
># 'django.template.loaders.eggs.load_template_source',
>)
As Simon Willison mentions in his [Debugging Django](http://simonwillison.net/2008/May/22/debugging/) presentation, using the Test Client in the interpreter can be a great way to take a peek at the raw results from a view. In some cases you may need to add additional headers to the request (for instance a piece of middleware may rely on them).
Though it is not mentioned in the reference documentation, a quick peek at the code confirmed my hopes that it would be possible to add data to the request. The Client *get* and *post* methods both accept an **extra** kwargs parameter that allow you to populate the request with additional data.
This template filter is rewritten, courtesy of Eric Moritz.
It is meant to be used when displaying status messages from Twitter. A regular expression is used to replace all @username replies with a link to that user's Twitter page.
In use at [http://ryanberg.net/blog/statuses/](http://ryanberg.net/blog/statuses/)
This class works in compatibility with a ModelForm, but instead of show a form, it shows the field values.
The Meta class attributes can be used to customize fields to show, to be excluded, to divide by sections, to urlize text fields, etc.
**Example 1:**
class InfoSingleCertificate(ModelInfo):
class Meta:
model = SingleCertificate
sections = (
(None, ('vessel','description','document','comments','status',)),
('Issue', ('issue_date','issue_authority','issue_location',)),
)
**Example 2:**
class InfoSingleCertificate(ModelInfo):
class Meta:
model = SingleCertificate
fields = ('vessel','description','document','comments','status',
'issue_date','issue_authority','issue_location',)
**How to use:**
Just save this snippet as a file in your project, import to your views.py module (or a new module named "info.py") and create classes following seemed sytax you use for ModelForms.
As users would login to their accounts to update their CC info, the expiration date always threw them off. The default format for displaying a datetime.date object is
>YYYY-MM-DD
Obviously the expiration date on your credit card uses the MM/YY format. I finally got around to creating a custom field/widget to handle this particular piece of data.
Use like so...
class CustomerForm(forms.ModelForm):
cc_exp = DateFieldCCEXP()
class Meta:
model = Customer
Usage: (if you save it as pigmentation.py as I did)
{% load pigmentation %}
{% autoescape off %}
{{ somevariable|pygmentize }}
{% endautoescape %}
There already a few of this code around, but this one is pretty clean, and includes css. It also works in both the development server and Dreamhost (python2.4 in my django config) without any unicode problems.
You're looking at the top-rated snippets currently on the site; if you'd like to contribute, sign up for an account and you'll be able to rate any snippet you see.