Login

URL models

Author:
diverman
Posted:
October 9, 2009
Language:
Python
Version:
1.1
Tags:
urls model genericforeignkey generic 404 url foreign-key contenttype middleware content-type foreignkey models contenttypes
Score:
1 (after 1 ratings)

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(...)`
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
### models.py ###

from django.contrib.contenttypes.generic import GenericForeignKey, GenericRelation
from django.contrib.contenttypes.models import ContentType
from django.conf import settings
from django.db import models

class Url(models.Model):
     content_type = models.ForeignKey(ContentType)
     object_id = models.PositiveIntegerField(db_index=True)
     content_object = GenericForeignKey()
     url_string = models.CharField(max_length=256, db_index=True)
     language = models.CharField(max_length=2, choices=settings.LANGUAGES, db_index=True)
    
     class Meta:
         unique_together = (('content_type', 'object_id'), ('url_string', 'language'))

class UrlModel(models.Model):
     urls = GenericRelation(Url)

     class Meta:
         abstract = True

     def view(self, request):
         raise NotImplementedError

### middleware.py ###

from django.utils.translation import get_language
from models import Url

class UrlMiddleware(object):
     def process_response(self, request, response):
         if not response.status_code == 404:
             return response

         try:
             url = Url.objects.get(url_string=request.path_info, language=get_language())
         except Url.DoesNotExist:
             return response

         return url.content_object.view(request)

### admin.py ###

from django.contrib.contenttypes.generic import GenericTabularInline
from django.conf import settings
from models import Url

class UrlInline(GenericTabularInline):
     model = Url
     max_num = len(settings.LANGUAGES)

More like this

  1. RFC: Shim to allow view classes rather than functions by peterbraden 5 years, 12 months ago
  2. Format transition middleware by limodou 8 years ago
  3. Auto rendering decorator with options by Batiste 7 years, 1 month ago
  4. Get active page's url by another language (templatetag) by muratcorlu 2 years, 1 month ago
  5. template tag for highlighting currently active page by adunar 6 years, 4 months ago

Comments

Please login first before commenting.