I am having an Error in Django Search Views - python

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})

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

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})

Related

How would I receive multiple items from a model form thro' Select2MultipleWidget and ModelChoiceField?

I have a view and a model form as shown below. I initially could get a single item ID to use inn the view. Now I need multiple items selected from a Select2MultipleWidget. How would I do this? I already tried as shown in my code. I can understand that the data from the form to the view is not correct.
def new_issue(request,pk):
borrowed = request.session.get('teacher_borrowings')
if request.method == 'POST':
form = IssueForm(request.POST,pk=pk)
if form.is_valid():
try:
book = form.cleaned_data['book_id'].id
form.save(commit=True)
books = Books.objects.filter.get(id=book)
Books.Claimbook(books)
return redirect('all_borrowed_teacher', borrowed=borrowed)
except Exception as e:
return redirect('/')
else:
pass
return render(request, 'item.html)
def new_issue(request,pk):
borrowed = request.session.get('teacher_borrowings')
if request.method == 'POST':
form = IssueForm(request.POST,pk=pk)
if form.is_valid():
try:
book = form.cleaned_data['book_id'].id
form.save(commit=True)
books = Books.objects.filter.get(id=book)
Books.Claimbook(books)
return redirect('all_borrowed_teacher', borrowed=borrowed)
except Exception as e:
return redirect('/')
else:
pass
return render(request, 'item.html)
The error
Select a valid choice. That choice is not one of the available choices.

Django form has no attribute 'cleaned_data'

This is the code I have, and when I run it on Django, I am met with this error: 'Title' object has no attribute cleaned_data
def new(request):
form = Title(request.POST)
if request.method == "POST":
if form.is_valid:
title = form.cleaned_data["title"]
text = form.cleaned_data["text"]
util.save_entry(title, text)
else:
return render(request, "encyclopedia/error.html",{
"form":NewForm()
})
return redirect(reverse('page', args = [title]))
return render(request, "encyclopedia/newpage.html",{
"form1":Title(),
"form": NewForm()
})
You are probably getting the exception thrown in your return statement where you are instantiating a new Title object. This object only gets the cleaned_data attribute when is_valid method has been called upon. Hence you haven't called this on the new Title object and that is the reason why you are getting the error.
you use form = Title(request.POST), but the line after you check whether the request.method equals POST or not. i think yo should move that line inside the if statement
is_valid() it's a function
def new(request):
form = Title(request.POST)
if request.method == "POST":
if form.is_valid():
title = form.cleaned_data["title"]
text = form.cleaned_data["text"]
util.save_entry(title, text)
else:
return render(request, "encyclopedia/error.html",{
"form":NewForm()
})
return redirect(reverse('page', args = [title]))
return render(request, "encyclopedia/newpage.html",{
"form1":Title(),
"form": NewForm()
})

How do I use identation in try block properly?

This piece of code is getting me an error of invalid syntax on first return render line. I guess I have messed up my identation, but i do not know how exactly I did.
def searchView(request):
if request.method == 'GET':
query = request.GET.get('search')
try:
result = Vacancy.objects.filter(name__icontains = query)
return render(request, "search.html", {'vacancies': result })
else:
return render(request, "search.html", {})
your try
should have except
do this
try:
#something
except:
pass
i.e
def searchView(request):
if request.method == 'GET':
query = request.GET.get('search')
try:
result = Vacancy.objects.filter(name__icontains = query)
except:
pass
return render(request, "search.html", {'vacancies': result })
else:
return render(request, "search.html", {})

Django queryset with variable value

I am writing dynamic filters in django for my database where I am using the below code where I have 2 variables(p_type,s_type):
p_type=[]
s_type=[]
query = request.GET.get("q")
p_type =request.GET.get("p_type")
s_type = request.GET.get("s_type")
#messages.add_message(request, messages.INFO, p_type)
#messages.add_message(request, messages.INFO, s_type)
if query:
queryset_find = queryset_list.filter(
Q(FP_Item__contains=query))
context = {'object_list': queryset_find}
return render(request, 'index.html', context)
elif p_type:
queryset_find = queryset_list.filter(
Q(p_type__contains=s_type))
context = {'object_list': queryset_find}
return render(request, 'index.html', context)
else:
context = {'object_list': queryset}
return render(request, 'index.html', context)
but django returns error at below line
Q(p_type__contains=s_type))
I have dynamic radio button where the value of p_type matches with my database but even though I am receiving the following error:
Exception Type: FieldError
Exception Value:
Cannot resolve keyword 'p_type' into field. Choices are: ... (same choices which I am using with my database).
Isn't it doable with variable query ? Any other methods ?
model:
class RFP(models.Model):
FP_Item = models.TextField(max_length=1500)
P_63 = models.TextField(max_length=1000)
P_64 = models.TextField(max_length=1000)
If p_type holds the name of the field you want to query, then you can do:
elif p_type:
kwargs = {
'{}__contains'.format(p_type): s_type
}
queryset_find = queryset_list.filter(Q(**kwargs))
...

ModelForm For Registration HttpResponseError

First off, I know what the error means, I'm just confused on the configuration.
I'm getting an error of:
views.Registration didn't return an HttpResponse object
The issue is when I visit localhost/Register, I get the above error.
Q: If I want localhost/Register to show form from RegistrationForm() when it loads the register.html template within render() (at the bottom) when /Register is accessed. How do I do that? Do I need to create another view like /NewUser that I currently have specified? My thought was that render() was going to execute to show the template (with the form inside it) when viewing /Register
Code:
a view of:
def Registration(request):
RegForm = RegistrationForm(request.POST or None)
if request.method == 'POST':
if RegForm.is_valid():
clearUserName = RegForm.cleaned_data['userNm']
clearPass = RegForm.cleaned_data['userPass']
RegForm.save()
try:
return HttpResponseRedirect('/NewUser/?user=' + clearUserName)
except:
raise ValidationError('Invalid Request', code='300') ## [ TODO ]: add a custom error page here.
else:
RegForm = RegistrationForm()
return render(request, 'VA/reuse/register.html', {
'form': RegForm
})
You need to render something if the request is 'GET' instead of 'POST': ie.
def Registration(request):
RegForm = RegistrationForm(request.POST or None)
if request.method == 'POST':
if RegForm.is_valid():
clearUserName = RegForm.cleaned_data['userNm']
clearPass = RegForm.cleaned_data['userPass']
RegForm.save()
try:
return HttpResponseRedirect('/NewUser/?user=' + clearUserName)
except:
raise ValidationError('Invalid Request', code='300') ## [ TODO ]: add a custom error page here.
else:
RegForm = RegistrationForm()
return render(request, 'VA/reuse/register.html', {
'form': RegForm
})
else:
RegForm=RegistrationForm()
return render(request, 'template.html', {'formset': RegForm})
of course, you should change the context for your template, depending on whatever it is you need to render.
No, you should just move everything from the else onwards back one indentation level. Otherwise, nothing is returned if the request is not a POST.

Categories

Resources