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. Template tag - list punctuation for a list of items by shapiromatron 9 months, 4 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 4 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 5 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

Please login first before commenting.