Login

URL models

Author:
diverman
Posted:
October 9, 2009
Language:
Python
Version:
1.1
Tags:
middleware urls models foreignkey model generic url foreign-key genericforeignkey contenttypes 404 contenttype content-type
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. Automatically setup raw_id_fields ForeignKey & OneToOneField by agusmakmun 6 months, 2 weeks ago
  2. Crispy Form by sourabhsinha396 7 months, 1 week ago
  3. ReadOnlySelect by mkoistinen 7 months, 3 weeks ago
  4. Verify events sent to your webhook endpoints by santos22 8 months, 3 weeks ago
  5. Django Language Middleware by agusmakmun 9 months ago

Comments

Please login first before commenting.