coderboy
coderboy

Reputation: 759

I am having an Error in Django Search Views

I am trying to create a search functionality in django. I just wrote the view but i was getting an error with that. I have tried debugging the codes but I don't seems to know where the error is.

Error Log

  File "C:\Users\Habib\Documents\django\FIVERR\Alex_SMS\SMS\core\urls.py", line 2, in <module>
    from . import views
  File "C:\Users\Habib\Documents\django\FIVERR\Alex_SMS\SMS\core\views.py", line 37
    return render(request, "core/search.html", context)
         ^
SyntaxError: invalid syntax

views.py

def search(request):
    if request.method == 'GET':      
        product_name =  request.GET.get('search')    
        try:
            product = Product.objects.filter(name__icontains=product_name)
            context = {"product": product}
        return render(request, "core/search.html", context)
        except:
            product = "What is this"
            context = {"product":product}
    else:
        result = "Sorry there is no product with that name"
        return render(request, "core/search.html", {"result":result})

Upvotes: 0

Views: 96

Answers (2)

markwalker_
markwalker_

Reputation: 12849

You're trying to return during a try/except which you can't do.

You need to return after this block;

def search(request):
    if request.method == 'GET':      
        product_name =  request.GET.get('search')    
        try:
            product = Product.objects.filter(name__icontains=product_name)
            context = {"product": product}
        except:
            product = "What is this"
            context = {"product":product}

        return render(request, "core/search.html", context)

    else:
        result = "Sorry there is no product with that name"
        return render(request, "core/search.html", {"result":result})

It's generally considered bad practise to not catch specific exceptions though.

Here's some good information on exception handling; https://wiki.python.org/moin/HandlingExceptions

Upvotes: 1

coderboy
coderboy

Reputation: 759

I was able to solve the issue by adding an except block as well as removing the return statement after the try statement and adding to after the except block.

views.py

def search(request):
    if request.method == 'GET':      
        product_name =  request.GET.get('search')    
        try:
            product = Product.objects.filter(name__icontains=product_name)
            context = {"product": product}
        except product_name.DoesNotExist:
            product = None
        return render(request, "core/search.html", context)
    else:
        result = "Sorry there is no product with that name"
        return render(request, "core/search.html", {"result":result})

Upvotes: 0

Related Questions