Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoiding redundant code in mobile/desktop with Django sites framework

According to the Django docs, the best practice for serving a mobile and desktop application would appear to be the following:

views.py

from django.contrib.sites.models import Site

def my_view(request):
    current_site = Site.objects.get_current()
    if current_site.domain == 'foo.com':
        # Render desktop home page
    elif current_site.domain == 'm.foo.com':
        # Render mobile home page

Unfortunately this means that I'll be making the if/then choice in every single view I write. Is it possible for me to instead do the following:

views.py

from django.contrib.sites.models import Site

current_site = Site.objects.get_current()
if current_site.domain == 'foo.com':
    def my_view(request):
        # Render desktop home page
elif current_site.domain == 'm.foo.com':
    def my_view(request):
        # Render mobile home page

I'd like to get some sense of the possibility here before I start tearing through my views.py in an attempt to test this the hard way.

like image 859
IanWhalen Avatar asked Dec 07 '25 02:12

IanWhalen


2 Answers

Have you looked at this app: http://pypi.python.org/pypi/django-mobility?

Using a middleware for detecting the device and decorators to switch templates depending on the incoming device are a good approach to avoid redundant if/else constructs.

And if you look at the examples given for django-mobility they look pretty similiar to your desired construct:

def view(request):
    ...

@mobilized(view)
def view(request):
   ...
like image 85
arie Avatar answered Dec 08 '25 14:12

arie


You can use middleware to detect whether or not the request is to the 'm' subdomain or not, and then specify the correct URL conf to direct you to the views you want. I've been using a modified version of the django-subdomains app for this and it's been working nicely. This is an effective and simple solution if your view logic for your mobile site is quite different from the view logic of your regular site. Here's the link:

https://github.com/tkaemming/django-subdomains

Then all you have to do is write a new URL conf for your mobile site, specify this in your settings, and then write your views/templates for your mobile site just like you would for your regular app.

like image 43
Spike Avatar answered Dec 08 '25 15:12

Spike



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!