Django url that changes with argument passed

Question:

I am making a shopping website and I want to make one url that will help in separating men and women’s apparel.

What I want to do

when you enter .../men/ it should display all products whose gender matches men
and same for .../women/

my url looks like

urlpatterns = [
    url(r'^$', views.home, name='home'),
    url(r'^upload/$', views.upload, name='uploadproduct'),
    url(r'^(?P<gender>w+)/$', views.sex),
    # url(r'^(?P<gender>w+)', views.sex,),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

but whatever alphanumeric argument I pass in gender in the url, it does not recognize it. It display Men’s Products.
example even if I go .../nfjwiene/ it will display all men’s products.
and also if I go .../women/ the same happens.

my view looks:

def sex(request, gender=''):
    if gender == 'men' or 'Men':
        u='M'
    elif gender == 'women' or 'Women':
        u='F'
    else:
        u='err'
    result = Product.objects.filter(sex=u)
    return render(request, 'sex.html', {'item': result}, gender) 
Asked By: Yogesh Kumar

||

Answers:

Seems like the problem is in your if statement;

if gender == 'men' or 'Men':

Always returns True, it checks if gender equals ‘men’ first, and if it fails, goes to the second condition which is just ‘Men’, which resolves to True. You should write your if statement as follows:

if gender == 'men' or gender == 'Men':

Same goes for woman check as well.

Answered By: Ozgur Akcali
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.