A generic base class for extending ModelAdmin views. This can be used likewise:
def myview(self, request, object_id):
obj = self._getobj(request, object_id)
< do something >
def get_urls(self):
urls = super(MyAdmin, self).get_urls()
my_urls = patterns('',
url(r'^(.+)/myview/$',
self._wrap(self.myview),
name=self._view_name('myview')),
)
return my_urls + urls
We often need to use a Profile form and we want to be able to modify the first_name, last_name and sometimes the email address.
Here is how I do it.
In this case I want to check the email so I did a specific form for it. But it is quite easy to add it.
The counter initializes the variable to 0, and next it increments one by one:
{% load counter_tag %}
{% for pet in pets %}
{% if pet.is_cat %}
{% counter cats %}
{% else %}
{% counter dogs %}
{% endif %}
{% endfor %}
# cats: {{cats}}
# dogs: {{dogs}}
You can use `UrlModel` to provide URL functionality to any instance of any model and any language (language support can be removed from this). Each model must have own view method, that returns HttpResponse. I was inspired by Flatpages. It is useful for small sites and static pages.
`class Page(UrlModel):
text = models.TextField()
def view(self, request)
# do something here
return HttpResponse(...)`
If you request static files such as images, javascript or css using http rather than https, the browser will complain that your site is not secure.
This simple context processor will replace http:// with https:// in your MEDIA_URL if your static files are being included from an https page.
In your settings.py just replace 'django.core.context_processors.media' with your new context processor.
A decorator that can be applied to your views to turn ObjectDoesNotExist exceptions into Http404 exceptions. This means people will see a "Page not found" error rather than an "Internal Server Error" when they are request something that does not exist in the database.
Example:
@raise_404
def show_event(request, id):
event = Event.objects.get(id)
return render_to_response('events/show_event.html', { 'event' : event })
When working with the ContentType model there are generally two issues.
1. Models are listed in the table but not imported.
2. Unicode only returns model not application so being able to select a a app/model is sometimes difficult when to applications have a model with the same name.
This snippet gets a listing of imported models and creates a drop down for selection. I also included a function that uses the returned from to get and
save the correct ContentType within the primary model.
This is a simple URI Querystring generator that can be used with Django for generating URI Querystring and preserving the current
Currently working to port into a template tag to allow
{% urlgen page|5 %} {% urlgen page 5 %} {% urlgen page,5 %}
OR
{% urlgen sort name display all %} etc..
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.
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.
Ripped this out of a project I'm working on. The field renders as two <select> elements representing the two-level hierarchy organized events Facebook uses. Returns the id's Facebook wants.
You're looking at the most-bookmarked snippets on the site; if you'd like to help useful snippets show up here, sign up for an account and you'll get your own bookmarks list.