When using the django web administration page to add blog posts, it's nice to be able to preview the post to catch layout glitches, typos and markup issues. The best way to do this is to have a preview page.

To add a preview page, the model should have:

  1. a boolean field that determines whether the post is public or not
  2. a smart get_absolute_url function.

Separate your posts

The first is easy:

    is_public = models.BooleanField(default=False)

Make your URLs smart

The second:

 def get_absolute_url(self):
    if self.is_public:
        return "/%s/blog/%s/%s/" % (self.language, 
           self.pub_date.strftime("%Y/%m/%d").lower(), self.slug)
    else:
        return "/%s/blog/preview/%d" %(self.language,self.id)

The django admin uses the get_absolute_url function to put a "Display on site" button on an object's page. So when you have public entries, you get to see what all the world sees, but when an entry is not public, the get_absolute_url function returns a special url.

Add a pre-view

The final piece to the puzzle is to have a view that is protected:

   @login_required 
   @user_passes_test(lambda u: u.is_staff)
   def entry_preview(request, entry_id):
      entry = get_object_or_404(Entry, pk=entry_id)
      return render_to_response('entry_detail.html', {'entry':entry}, 
        context_instance=RequestContext(request))

I use the is_staff property, but this can easily be changed to something else.

Don't forget to add the relevant url to your urls.py :

(r'^preview/(?P<entry_id>\d+)/$', entry_preview),

That's all!

You gotta love Django. I got from idea to implementation, and of course blog post in about 30 minutes! And, most of which I was hunting a bug in my middleware which trashed the account login redirect.

May 7, 2007, 6:23 a.m. More (246 words) 3 comments Feed
Previous entry: Going international, pt. 1
Next entry: Going international, pt. 2: URL design

Comments

1

Comment by Alexander Solovyov , 3 years, 4 months ago :

Really cool idea! ;) Thanks.

2

Comment by Orestis Markou , 3 years, 3 months ago :

Thanks :) Glad to be of service!

3

Comment by test , 3 years, 3 months ago :

test


This post is older than 30 days and comments have been turned off.