Search code examples
pythondjangodjango-templatesdjango-viewsslug

Passing slug from Template to View in django


I have an application wherin I am trying to pass a slug field from a template (frames.html) to the views.py. My problem is that I see the URL changing on clicking on the link on frames.html, but it doesn't seem to reach the view.(I have print statements in my views.py which are not getting printed, so that's how I know.). My frames.html is as follows

<div id="FramePage">
   {% for frame in Frames %}
     <p><a href="/frames/{{ frame.slug }}/">{{frame}}</a>                  
    {% endfor %}
</div>

This is the entry in my urls.py

urlpatterns = patterns('',
# Examples:
#url(r'^$', 'vTryON_Django.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^$', 'vTryON.views.home_page'),
url(r'^frames/', 'vTryON.views.VTryONAll'),
url(r'^frames/(?P<frameslug>.*)/$', 'vTryON.views.selectedFrame'),
url(r'^tryonpage/', 'vTryON.views.tryonpage'),
url(r'^uploadPC/', 'vTryON.views.uploadPC'),
url(r'^uploadWebcam/', 'vTryON.views.uploadWebcam'),

)

and this is my view function in views.py

def selectedFrame(request, frameslug):
    #print('selectedFrame')
    frame= VTryON.objects.get(slug=frameslug)
    #print(frame)
    context={'frame':frame}
    #print('context')
    return render_to_response('selectedframe.html', context, context_instance=RequestContext(request))

As I mentioned, i can see my URL change from http://127.0.0.1:8000/frames/ to http://127.0.0.1:8000/frames/FR123/ after I click on the link on frames.html. Am I configuring it wrongly in urls.py? I am a beginner in python /django. Please help me out.Thanks in advance.


Solution

  • The problem is in your URLs. Your frames URL does not terminate the regex at the end. So it also matches anything that simply starts with "frames", which includes "frames/FR123".

    You should ensure that all URLs explicitly end with $ to prevent this.

    url(r'^frames/$', 'vTryON.views.VTryONAll'),