Django doesn't refresh my request object when reloading the current page.

Posted by Boris Rusev on Stack Overflow See other posts from Stack Overflow or by Boris Rusev
Published on 2010-05-30T09:08:47Z Indexed on 2010/05/30 9:12 UTC
Read the original article Hit count: 728

Filed under:
|
|
|
|

I have a Django web site which I want ot be viewable in different languages. Until this morning everything was working fine. Here is the deal. I go to my say About Us page and it is in English. Below it there is the change language button and when I press it everything "magically" translates to Bulgarian just the way I want it. On the other hand I have a JS menu from which the user is able to browse through the products. I click on 'T-Shirt' then a sub-menu opens bellow the previously pressed containing different categories - Men, Women, Children. The link guides me to a page where the exact clothes I have requested are listed. BUT... When I try to change the language THEN, nothing happens. I go to the Abouts Page, change the language from there, return to the clothes catalog and the language is changed...

I will no paste some code.

This is my change button code:

function changeLanguage() {
    if (getCookie('language') == 'EN') {
        setCookie("language", 'BG');
    } else {
        setCookie("language", 'EN');
    }
    window.location.reload();
}

These are my URL patterns:

urlpatterns = patterns('',
    # Example:
    # (r'^enter_clothing/', include('enter_clothing.foo.urls')),

    # Uncomment the admin/doc line below and add 'django.contrib.admindocs' 
    # to INSTALLED_APPS to enable admin documentation:
    # (r'^admin/doc/', include('django.contrib.admindocs.urls')),

    # Uncomment the next line to enable the admin:
    (r'^site_media/(?P<path>.*)$', 'django.views.static.serve',
        {'document_root': '/home/boris/Projects/enter_clothing/templates/media', 'show_indexes': True}),
    (r'^$', 'enter_clothing.clothes_app.views.index'),
    (r'^home', 'enter_clothing.clothes_app.views.home'),
    (r'^products', 'enter_clothing.clothes_app.views.products'),
    (r'^orders', 'enter_clothing.clothes_app.views.orders'),
    (r'^aboutUs', 'enter_clothing.clothes_app.views.aboutUs'),
    (r'^contactUs', 'enter_clothing.clothes_app.views.contactUs'),
    (r'^admin/', include(admin.site.urls)),
    (r'^(\w+)/(\w+)/page=(\d+)', 'enter_clothing.clothes_app.views.displayClothes'),
)

My About Us page:

@base
def aboutUs(request):
    return """<b>%s</b>""" % getTranslation("About Us Text", request.COOKIES['language'])

The @base method:

def base(myfunc):
    def inner_func(*args, **kwargs):
        try:
            args[0].COOKIES['language'] 
        except:
            args[0].COOKIES['language'] = 'BG'

        resetGlobalVariables()
        initCollections(args[0])

        categoriesByCollection = dict((collection, getCategoriesFromCollection(args[0], collection)) for collection in collections)   

        if args[0].COOKIES['language'] == 'BG':
            for k, v in categoriesByCollection.iteritems():   
                categoriesByCollection[k] = reduce(lambda a,b: a+b, map(lambda x: """<li><a href="/%s/%s/page=1">%s</a></li>""" % (translateCategory(args[0], x), translateCollection(args[0], k), str(x)), v), "")
        else:
            for k, v in categoriesByCollection.iteritems():   
                categoriesByCollection[k] = reduce(lambda a,b: a+b, map(lambda x: """<li><a href="/%s/%s/page=1">%s</a></li>""" % (str(x), str(k), str(x)), v), "")

        contents = myfunc(*args, **kwargs)

        return render_to_response('index.html', {'title': title, 'categoriesByCollection': categoriesByCollection.iteritems(), 'keys': enumerate(keys), 'values': enumerate(values), 'contents': contents, 'btnHome':getTranslation("Home Button", args[0].COOKIES['language']), 'btnProducts':getTranslation("Products Button", args[0].COOKIES['language']), 'btnOrders':getTranslation("Orders Button", args[0].COOKIES['language']), 'btnAboutUs':getTranslation("About Us Button", args[0].COOKIES['language']), 'btnContacts':getTranslation("Contact Us Button", args[0].COOKIES['language']), 'btnChangeLanguage':getTranslation("Button Change Language", args[0].COOKIES['language'])})
    return inner_func

And the catalog page:

@base
def displayClothes(request, category, collection, page):
    clothesToDisplay = getClothesFromCollectionAndCategory(request, category, collection)

    contents = ""

    pageCount = len(clothesToDisplay) / ( rowCount * columnCount) + 1
    matrixSize = rowCount * columnCount
    currentPage = str(page).replace("page=", "")
    currentPage = int(currentPage)  - 1
    #raise Exception(request)           

    # this is for the clothes layout
    for x in range(currentPage * matrixSize, matrixSize * (currentPage + 1)):
        if x < len(clothesToDisplay):
            if request.COOKIES['language'] == 'EN':
                contents += """<div class="clothes">%s</div>""" % clothesToDisplay[x].getEnglishHTML()
            else:
                contents += """<div class="clothes">%s</div>""" % clothesToDisplay[x].getBulgarianHTML()
            if (x + 1) % columnCount == 0:
                contents += """<div class="clear"></div>"""

    contents += """<div class="clear"></div>"""

    # this is for the page links                
    if pageCount > 1:
        for x in range(0, pageCount):
            if x == currentPage:
                contents += """<a href="/%s/%s/page=%s"><span style="font-size: 20pt; color: black;">%s</span></a>""" % (category, collection, x + 1, x + 1)  
            else:
                contents += """<a href="/%s/%s/page=%s"><span style="font-size: 20pt; color: blue;">%s</span></a>""" % (category, collection, x + 1, x + 1)

    return """%s""" % (contents)

Let me explain that you needn't be alarmed by the large quantities of code I have posted. You don't have to understand it or even look at all of it. I've published it just in case because I really can't understand the origins of the bug.

Now this is how I have narrowed the problem. I am debuging with "raise Exception(request)" every time I want to know what's inside my request object. When I place this in my aboutUs method, the language cookie value changes every time I press the language button. But NOT when I am in the displayClothes method. There the language stays the same. Also I tried putting the exception line in the beginning of the @base method. It turns out the situation there is exactly the same. When I am in my About Us page and click on the button, the language in my request object changes, but when I press the button while in the catalog page it remains unchanged.

That is all I could find, and I have no idea as to how Django distinguishes my pages and in what way.

P.S. The JavaScript I think works perfectly, I have tested it in multiple ways.

Thank you, I hope some of you will read this enormous post, and don't hesitate to ask for more code excerpts.

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about python