Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 682161
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 14, 20262026-05-14T01:33:53+00:00 2026-05-14T01:33:53+00:00

I’m moving from a PHP background into Django development via python, mostly for the

  • 0

I’m moving from a PHP background into Django development via python, mostly for the sake of tackling a MVC (or MVT) that I feel makes the most sense, although in this pattern I’ve started to notice a lot of repeated code in my views.

For example, when logged in I have information regarding the user that I would like to appear on every page, although when using render_to_response and in every view this is required I have to grab the information and pass it to the render_to_response function.

I’m wondering what would be the most efficient way to cut down on the duplicate code which would in essence be required in all views in a particular app.

Thanks in advance.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-14T01:33:53+00:00Added an answer on May 14, 2026 at 1:33 am

    Personally I am a huge fan of decorators, which are a python feature that isn’t specific to Django. Decorators are the perfect syntactic sugar on top of higher-order functions, and they’re especially useful for reducing boilerplate in views — you can quickly define a generalized wrapper function, in which you can put the repetitive code for easy reuse and convenient one-stop refactoring.

    It’s probably easier to show you than explain how they work. Here is a simplified view example:

    def listpage(request):
        return HttpResponse(render_to_string("itemlist.html", {
            "items": Item.objects.filter(visible=True).order_by("-modifydate")
        }))
    
    def itemlist_tags(request, tags):
        return HttpResponse(render_to_string("itemlist.html", {
            "items": Item.objects.tagged(name=tags).filter(visible=True).order_by("-modifydate"),
        }))
    

    … but then say you wanted to make these pages require the user to log in. You might add login code like so:

    def listpage(request):
        if not request.user.is_authenticated():
            return f(request, *args, **kwargs)
        else:
            return HttpResponse(render_to_string("itemlist.html", {
                "items": Item.objects.filter(visible=True).order_by("-modifydate")
            }))
    
    def itemlist_tags(request, tags):
        if not request.user.is_authenticated():
            return f(request, *args, **kwargs)
        else:
            return HttpResponse(render_to_string("itemlist.html", {
                "items": Item.objects.tagged(name=tags).filter(visible=True).order_by("-modifydate"),
            }))
    

    … which is starting to get notably bigger and repetitive, even for a contrived example. You can make your functions slim again with decorators, like so:

    from decorator import decorator

    @decorator
    def loginrequired(f, request, *args, **kwargs):
        if request.user.is_authenticated():
            return f(request, *args, **kwargs)
        else:
            return HttpResponseRedirect("/")
    
    @loginrequired
    def listpage(request):
        return HttpResponse(render_to_string("itemlist.html", {
            "items": Item.objects.filter(visible=True).order_by("-modifydate")
        }))
    
        @loginrequired
    def itemlist_tags(request, tags):
        return HttpResponse(render_to_string("itemlist.html", {
            "items": Item.objects.tagged(name=tags).filter(visible=True).order_by("-modifydate"),
        }))
    
    @loginrequired
    def another_such_function(request):
        (...)
    
    @loginrequired
    def and_again(request):
        (...)
    

    What happens is the decorator function is executed at the time of the function’s definition. The ‘f’ in my example is an object representing the function that the decorator is applied to, which you can manipulate in unending ways.

    This requires the decorator library, which is free on PyPI as are many good python morsels, you’ll find.

    You don’t need the this library to write decorator functions, but it’s helpful, especially in the beginning. They can do a whole lot more — any callable can be a decorator; you can decorate class methods and intercept the self variable; decorators can be chained up, like so:

    @second
    @first
    def originalfunction(*args):
        (...)
    

    I’ll leave the exploration of what you can do with such easy higher-order function manpipulation for you, should this notion whet your appetite. I have many more examples as well, for you or any other curious new python aficionados. Good luck.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

link Im having trouble converting the html entites into html characters, (&# 8217;) i
I have a string like this: La Torre Eiffel paragonata all’Everest What PHP function
this is what i have right now Drawing an RSS feed into the php,
I am currently running into a problem where an element is coming back from
I want to count how many characters a certain string has in PHP, but
I would like to count the length of a string with PHP. The string
For some reason, after submitting a string like this Jack’s Spindle from a text
I have a French site that I want to parse, but am running into
I'm using v2.0 of ClassTextile.php, with the following call: $testimonial_text = $textile->TextileRestricted($_POST['testimonial']); ... and
I'm parsing an RSS feed that has an ’ in it. SimpleXML turns this

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.