PanPan PanPan - 3 months ago 26
Python Question

URL passes parameter in my Django project

I am just a beginner of Django, these days I followed a mooc to learn Django, I wanted to set up my first website, but something went wrong and I can not figure out. I wanted to write a regex with parameter 'cate' in URLS.py to match the video function in my view.py, judging whether 'cate' eequals 'editors', if yes it will bring back data with attribute "editors_choice". However, I found no it never changes, so I printed 'cate' in view.py and found it always None and I still don't know why.

Following is my code:

def video(request, cate=None):
print(cate)
context = {} =
if cate is None:
video_list = Video.objects.all()
if cate == 'editors':
video_list = Video.objects.filter(editors_choices=True)
else:
video_list = Video.objects.all()
page_robot = Paginator(video_list, 16)
page_num = request.GET.get('page')
try:
video_list = page_robot.page(page_num)
except EmptyPage:
video_list = page_robot.page(page_robot.num_pages) # raise HTTP404("Empty")
except PageNotAnInteger:
video_list = page_robot.page(1)
context['video_list'] = video_list
return render(request, 'ten_movie.html', context)





'cate' parameter in urls.py




templete

Answer Source

Two url patterns shouldn't share the same name. Rename the other one with the cate parameter to something else.

Then add a regex end-of-string character to the first pattern to prevent it from overlapping with the second.

url(r'^video/$', video, name='video'),
url(r'^video/(?P<cate>[A-Za-z]+)$', video, name='video_filtered'),