Login

URL models

Author:
diverman
Posted:
October 9, 2009
Language:
Python
Version:
1.1
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. codigo alto nivel by MrRocklion 6 days, 4 hours ago
  2. Load template from specific app by Krzysiek555 3 weeks, 5 days ago
  3. PostgreSQL JSON subqueries by dolamroth 4 weeks ago
  4. "Magic Link" Management Command by webology 6 months ago
  5. Closest ORM models to a latitude/longitude point by simonw 6 months ago

Comments

Please login first before commenting.