I have problem in try-except
The file is views.py
function 'noun_check' return nouns of the sentence that I received from contenct.para(=input)
If there is no noun in the sentence than function 'noun_check' return error
If the error occur, go to except and return(request, 'main/desktop.html'), and receive another sentence.
And If I got nouns, I return render(request, 'main/introduction.html', context). This is the way I thought.
But error occured in function 'noun_check', logic doesnt' go to except, and return render(request, 'main/introduction.html', context)
Could you explain why try-except doesn't work?
def submit(request):
if request.method == 'POST' and request.POST['input'] != '':
try:
content = Diary_content()
content.para = request.POST['diary_input']
tokenized_nouns = noun_check(content.para)
context = {'para' : content.para, 'emotions':tokenized_nouns}
return render(request, 'main/introduction.html', context)
except:
return render(request, 'main/desktop.html')
I seperate the function, and made function if error occur return False
And use temp = function(sentence) \n if temp == 0: ...
Althogh 'temp == 0' is True, logic doesn't go under 'if function'
Related
#app.route('/predict', methods=['GET', 'POST'])
def predict1():
# radio = 0
if request.method == 'POST':
value = request.get_json()
if(value['radioValue'] == 'word'):
radio = 0
return "ok"
elif(value['radioValue'] == 'sentence'):
radio = 1
return "ok"
else:
if(radio==0):
lists = ["my","word"]
elif(radio==1):
lists = ["my","sentence"]
return jsonify({'prediction': lists})
Hello, I am new to Flask and web development. So, here is my question, I am getting two radio button value named word and sentence. I want to pass lists = ["my","word"] if value is word else lists = ["my","sentence"].
But here jsonify() is not returning anything. So what am I doing wrong here?
Though it return lists if I declare radio variable outside if-else block as you can see I commented them out.
Also if I don't return anything inside post what I did as return "ok" it doesn't return anything even if I declare radio = 0 or 1 outside if-else block.
A short explanation will be really helpful.
If you check your debug log, you will probably see a NameError where radio is not defined. This is due to radio being a local variable, and not a session variable as you probably intended.
To store variables for further usage in Flask, you need to use sessions.
from flask import session
#app.route('/predict', methods=['GET', 'POST'])
def predict1():
if request.method == 'POST':
value = request.get_json()
if(value['radioValue'] == 'word'):
session["radio"] = 0
return "ok"
elif(value['radioValue'] == 'sentence'):
session["radio"] = 1
return "ok"
else:
if(session["radio"]==0):
lists = ["my","word"]
elif(session["radio"]==1):
lists = ["my","sentence"]
return jsonify({'prediction': lists})
I am getting a ValueError that the class below didn't return any httpresponse when i try to redirect to a template. the redirect is supposed to go to the stripe payment view.
here is an entire class that has the redirect call
class CheckoutView(View):
def get(self, *args, **kwargs):
form = forms.CheckoutForm()
context = {
'form': form
}
return render(self.request, "checkout.html", context)
def post(self, *args, **kwargs):
form = forms.CheckoutForm(self.request.POST or None)
try:
equipment_order = models.EquipmentOrder.objects.get(user=self.request.user, ordered=False)
if form.is_valid():
street_address = form.cleaned_data.get('street_address')
apartment_address = form.cleaned_data.get('apartment_address')
country = form.cleaned_data.get('country')
zip = form.cleaned_data.get('zip')
'''
TODO: add functionality to these fields
same_shipping_address = form.cleaned_data.get('same_shipping_address')
save_info = form.cleaned_data.get('save_info')
'''
payment_option = form.cleaned_data.get('payment_option')
billing_address = models.BillingAddress(
user=self.request.user,
street_address=street_address,
apartment_address=apartment_address,
country=country,
zip=zip
)
billing_address.save()
equipment_order.billing_address = billing_address
equipment_order.save()
if payment_option == 'S':
return redirect('create:payment', payment_option='stripe')
elif payment_option == 'P':
return redirect('create:payment', payment_option='paypal')
else:
messages.warning(self.request, "Invalid payment option")
return redirect('create:checkout')
except ObjectDoesNotExist:
messages.error(self.request, "You do not have an active order")
return redirect("create:order_summary")
1) Remove the try/except i think its better
2) I think you have a problem on 'payement_option' , maybe it doesnt give any value of expected , try to print it first to see what does it give
3) remove the ' or None ' from CheckoutForm
4) you can avoid using 'self' by importing form in that way :
from .forms import CheckoutForm
...
form = CheckoutForm(request.POST)
The above answer may work fine but as I tried your code it throws the same error as you described whenever you leave the form field empty or no payment method is selected.
After trying your code the best possible solution I figure out is this. I know this is not a perfect solution but it worked 😅
Suggestion: Try to move your else statement under if instead of nesting it after elif statement. And change your else to given below.
Old:
else:
messages.warning(self.request, "Invalid payment option select")
return redirect('core:checkout')
New:
else :
messages = 'Invalid payment option select'
return HttpResponse(messages)
Proof: Invalid payment option select
I'm currently learning Django however I'm torn on how to structure the equivalent of add method using it. I'm creating a URL shortener and I'm between the following methods to implement in creating the shortened URL:
def shorten(request):
if request.method == 'POST':
http_url = request.POST.get("http_url","")
if http_url: # test if not blank
short_id = get_short_code()
new_url = Urls(http_url=http_url, short_id=short_id)
new_url.save()
return HttpResponseRedirect(reverse('url_shortener:index'))
else:
error_message = "You didn't provide a valid url"
return render(request, 'url_shortener/shorten.html', { 'error_message' : error_message })
return render(request, 'url_shortener/shorten.html')
vs.
def shorten(request):
http_url = request.POST["http_url"]
if http_url:
short_id = get_short_code()
new_url = Urls(http_url=http_url, short_id=short_id)
new_url.save()
return HttpResponseRedirect(reverse('url_shortener:index'))
else:
error_message = "You didn't provide a valid url"
return render(request, 'url_shortener/shorten.html', { 'error_message' : error_message })
return render(request, 'url_shortener/shorten.html')
Specifically, I want to know the best practice on the following:
Is it best practice to explicity test if method is post or http_url = request.POST["http_url"] is enough
Is http_url = request.POST.get("http_url","") recommended to be used or this is just suppressing the error?
If (2) is not recommended, how can I make the http_url required and throw an error? I also tried the following but the except block is not triggered when I submit a blank form
def shorten(request):
if request.method == 'POST':
try:
http_url = request.POST["http_url"]
short_id = get_short_code()
new_url = Urls(http_url=http_url, short_id=short_id)
new_url.save()
return HttpResponseRedirect(reverse('url_shortener:index'))
except KeyError:
error_message = "You didn't provide a valid url"
return render(request, 'url_shortener/shorten.html', { 'error_message' : error_message })
return render(request, 'url_shortener/shorten.html')
request.POST["key"]
will throw a KeyError when the key is not present in the dictionary. You can use a try...catch clause to handle the error.
Generally though, its idiomatic and perfectly normal to do:
request.POST.get("key")
More about get here.
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).
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....