Python return function error - python

While running this function to validate captcha key and value i am not able to return
it show error like this
"AttributeError: 'bool' object has no attribute 'status_code'"
def validate(request):
id=request.GET.get('id','')
key=request.GET.get('key','')
captchavalue = mc.get(str(id))
if captchavalue == key:
return True
else:
return False

By reading the code and the error, I assume that validate is a view. A view must always return a HttpResponse. So if you want to return a response indicating a boolean value, indicating if captchavalue == key, do:
from django.http import HttpResponse
def validate(request):
id=request.GET.get('id','')
key=request.GET.get('key','')
captchavalue = mc.get(str(id))
return HttpResponse(captchavalue == key)
I'm not 100% sure about the import line, but it's something very similar.

I don't know much Django, but it seems it expects you to return a response object instead of a bool value (True / False).
Maybe your code should like more like this:
if captchvalue == key:
return HttpResponse('HTML Page saying OK')
else:
return HttpResponse('HTML Page saying Error')

Related

Raise error if launched output and uses result

I want to raise an error if the user uses return launch and result().
def launch(returnOutput=False):
# Function
if returnOutput:
return "value"
else:
value = "value"
def result():
return value
I want it to say like:
Console > print(launch(True), result())
Error: "Can't get result if launched output."
Is there a way to do this?
I am dumb so i didn't think of this:
def result():
if value == None:
# Throw error
else:
return value

Using Boolean in Django Custom Query Set

Lately I had came to one strange thing when I was working with Django custom querysets. So, I am using request.GET for passing boolean value to my django view. Then I pass this value to my custom queryset function. It seems weird because it works in case of basic query but not with '__isnull'. Are there any differencies?
views.py
if request.GET.get('available'):
items = Item.objects.is_available(request.GET.get('available')) # this works
...
if request.GET.get('order'):
transfers = Transfer.objects.not_working_is_order(request.GET.get('order')) # not working
managers.py
class ItemQuerySet(QuerySet):
def is_available(self, is_available):
return self.filter(is_available=is_available) # this works
class TransferQuerySet(QuerySet):
def is_order(self, bool):
if bool == 'False':
return self.filter(order__isnull=False)
elif bool == 'True':
return self.filter(order__isnull=True) # this works
def not_working_is_order(self, bool):
return self.filter(order__isnull=bool) # not working
mytemplate.html
Not available
myothertemplate.html
Not order
That's because bool is not a boolean, it's a string, you can do something like self.filter(order__isnull=bool == 'True')

TypeError: 'bool' object is not callable using filter function

I m trying to filter out only valid emails addresses,but I getting the below error.
Traceback (most recent call last):
File "C:/Python27/ghhs.py", line 20, in <module>
valid=list(filter(a,email)) TypeError: 'bool' object is not callable
Here is the code:
def fun(email):
for i in email:
if ('#'and'.') in i:
user,url=i.split('#')
web,domain=url.split(".")
if user.replace('-','').replace('_','').isalnum() is False:
return False
elif web.isalnum() is False:
return False
elif len(domain)>3:
return False
else:
return True
else:
return True
if __name__=="__main__":
n=int(input())
email=[raw_input() for i in range(n)]
a=fun(email)
valid=list(filter(a,email))
valid.sort()
print (valid)
The first argument to filter should be a function that will get called for each item in the second argument, but you are calling the function first and passing in the return value. Change your filter call to something like this:
valid=list(filter(fun, email))
ETA
As pointed out in the comments below fun has some other problems. From one, since the function passed to filter gets called for each item, it shouldn't been attempting to loop over its input but just accept a single email address and not a list of addresses.
Also your initial test for characters in the address is broken. Something like this will work better:
def fun(email):
if ('#' in email) and ('.' in email):
user, url = i.split('#')
web, domain = url.split(".")
if user.replace('-','').replace('_','').isalnum() is False:
return False
elif web.isalnum() is False:
return False
elif len(domain)>3:
return False
else:
return True
But better yet, don't reinvent the wheel:
from validate_email import validate_email
valid = list(filter(validate_email, email))

attribute error 'function' object has no attribute 'has_header'

i have been encountered by this error
'function' object has no attribute 'has_header'
my url file contans
url(r'^HighDefs/$', list_HighDefs),
and i have a view defined with the name
list_HighDefs
in views file. I dont know whats wrong.
the view contains
def list_HighDefs(request):
user_logger = Logger()
user_logger.log_stack()
if user_object:
email = user_object.email
uname = user_object.first_name+' '+user_object.last_name
try:
row = allapps_models.highdef.objects.filter(user_email=email, show_status=1)
except Exception:
return error_page(request)
highdefs = []
for m in row:
order_product = int(m.m_id)
state = m.state
try:
category = checkout_models.state.objects.get(pk=product).premature.category.all()
category = category[0].pk
except:
category = 0
if int(category) == 2:
if state != 's':
highdefs.append(m)
return render_to_response('main/HighDefs.html',{'request': request, 'highdefs': highdefs, 'uname' :uname, 'email': email}, context_instance=RequestContext(request))
else:
return(login)
Your view must return an HttpResponse object.
It does this for one branch of your if statement:
return render_to_response(...)
But not in the else branch.
return(login)
If login is a view function that returns an HttpResponse object, then you can change your return statement to
return login(request)
However, I suspect you want to redirect the user to your login page instead. In that case, change your code to:
from django.http import HttpResponseRedirect
return HttpResponseRedirect('/login/')
where /login/ is the url of your login page.
The last line of your view is return login (don't know why you're wrapping your returns in parentheses, it's unnecessary). But presumably login is a function, and you're not calling it. I expect you mean to do return login() or return login(request).

Django - view didn't return an HttpResponse object

I'm facing this exception error and I'm puzzled by it, as this method worked in similar system, appreciate any help or pointers. Many Thanks!
Exception Value: The view Project.qna.views.add_vote didn't return an HttpResponse object.
def add_vote(request):
if request.method == "POST":
q_id = request.POST['vote_form_q_id']
a_id = request.POST['vote_form_a_id']
vote_value = request.POST['vote_form_value']
ok = False
vote_num = None
name = None
if q_id:
try:
question = Question.objects.get(id=q_id)
question.num_vote += int(vote_value)
question.save()
vote_num = question.num_vote
name = 'Question_'+str(q_id)
ok = True
except Question.DoesNotExist:
pass
elif a_id:
try:
answer = Answer.objects.get(id=a_id)
answer.num_vote += int(vote_value)
answer.save()
vote_num = answer.num_vote
name = 'Answer_'+str(a_id)
ok = True
except Answer.DoesNotExist:
pass
if ok and request.is_ajax:
result = simplejson.dumps({
"vote_num": vote_num,
}, cls=LazyEncoder)
response = HttpResponse(result, mimetype='application/javascript')
response.set_cookie(name, datetime.now)
return response
Fix your indention please, also you seem to have a lot of workarounds that could be simplified.
Every django view should return a HttpResponse object, you seem to have a lot of places where this would not be the case. To narrow down your problem change every pass to a print statement to see where your code actually fails. It would be quite helpful if you could present your POST data.
Well it's hard to tell without seeing what kind of request you are making to the view. But are you sending a POST request? Because you don't handle GET requests in any way. Also the indentation is wrong. But that might just be cutting and pasting gone awry.
This is untested, but it's a cleaner and more robust design, which I believe fits in with your logic and highlights the points where returning an HttpResponse is necessary:
def add_vote(request):
if not (request.method == 'POST' and request.is_ajax):
return # Some suitable response here
try:
vote_value = int(request.POST.get('vote_form_value',''))
except ValueError as e:
pass # Some suitable response here
def saveobj(model, key, val): # helper function to reduce code repetition
item = model.objects.get(id=key)
item.num_vote += val
item.save()
return item.num_vote, '%s_%s' % (model.__class__.__name__, key)
for model, key in [(Question, 'vote_form_q_id'), (Answer, 'vote_form_a_id')]):
try:
new_vote_value, name = saveobj(model, request.POST[key], vote_value)
break
except (KeyError, ObjectDoesNotExist) as e:
continue # or error out
else:
pass # neither question or answer found - so suitable response here
# return ajax response here....

Categories