BangolPhoenix
BangolPhoenix

Reputation: 393

error when rendering through get_object_or_404 django

The following code in my views.py throws an error if I don't use else conditional statement specifying detail = None

Is there any better way to simplify the code without using else statement? (just in case you don't understand the structure of my app, it only has detail, and list templates. list.html only shows the list of name record in model, and detail only shows the each name in detail page.)

def SimpleView(request, sluggy=None):
    s = Simple.objects.all()
    if sluggy:
        detail = get_object_or_404(Simple, slug=sluggy)
    else:
        detail=None
    return render(request,'simple_app/list.html',{'s':s,'d':detail})

def detaily(request,sluggy):
    sluggys = get_object_or_404(Simple,slug=sluggy)
    return render(request, 'simple_app/detail.html',{'sluggy':sluggys})

Upvotes: 0

Views: 144

Answers (2)

Daniel Roseman
Daniel Roseman

Reputation: 599630

You can build up the context directly:

def SimpleView(request, sluggy=None):
    context = {'s': Simple.objects.all()}
    if sluggy:
        context['d'] = get_object_or_404(Simple, slug=sluggy)
    return render(request,'simple_app/list.html', context)

(Though please use more descriptive names for the template vars; there's no reason to use single characters.)

Upvotes: 2

SwapnilBhate
SwapnilBhate

Reputation: 274

If you are really fixated on no using the else part, you should define the detail variable before the if statement. So if "if qualification" is not satisfied, "detail" variable in return statement will at-least have a defined value as None.

 def SimpleView(request, sluggy=None):
    s = Simple.objects.all()
    detail=None
    if sluggy:
        detail = get_object_or_404(Simple, slug=sluggy)
    return render(request,'simple_app/list.html',{'s':s,'d':detail})

def detaily(request,sluggy):
    sluggys = get_object_or_404(Simple,slug=sluggy)
    return render(request, 'simple_app/detail.html',{'sluggy':sluggys})

Upvotes: 1

Related Questions