POST data not always making to my logic, despite updating the django model properly
def new_record(request):
form = RecordForm(request.POST or None)
if request.method == 'POST':
if form.is_valid():
form.save()
return HttpResponseRedirect('/new_record')
else:
form = RecordForm()
item1 = request.POST.getlist('checkbox_1')
item2 = request.POST.getlist('checkbox_2')
item3 = request.POST.getlist('checkbox_3')
print(item1)
print(item2)
print(item3)
if 'on' in item1:
print("Checkbox 1 is true")
write_pdf_view(textobject='textobject', exam_record_number='123')
else:
print("Checkbox 1 is False")
if 'on' in item2:
print("Checkbox 2 is true")
else:
print("Checkbox 2 is False")
if 'on' in item3:
print("Checkbox 3 is true")
else:
print("Checkbox 3 is False")
return render(request=request,
template_name='main/new_record.html',
context={"form": form}
)
What I'm hoping to do is basically check if a checkbox is selected and pass a value into a function if this is true, for now I've fixed y write_pdf_view values to something I know exists and that's not working either (I imported that above)
I feel like this might be trivial for someone with experience, I'm a new hobbyist just looking to learn! Any help much appreciated.
Your if statements are executing during GET and not POST.
I would recommend structuring your code using the class-based view structure, as follows:
from django.views import View
class NewRecord(View):
def get(self, request):
return render(request, 'main/new_record.html', {'form': RecordForm})
def post(self, request):
form = RecordForm(request.POST)
if form.is_valid():
form.save()
item1 = request.POST.get('checkbox_1', None)
##place the rest of your logic here
return HttpResponseRedirect('/new_record')
Related
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'
#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 working on a PUT request to be able to modify data in my JSON file, using Flask and Python. The problem is it won't save the changes made.
Below is my code:
#app.route('/updated', methods = ['POST', 'PUT' 'GET'])
def update():
try:
title = request.form['title']
print title
if request.method == 'POST':
with open("articles.json", 'r+') as json_File:
articles = json.load(json_File)
for article in articles['article']:
if title == article['title']:
print article['title']
print article['author']
print article['article_id']
article['title'] = title
article['author'] = request.form['author']
article['text'] = request.form['text']
article['article_id'] = request.form['article_id']
print article
save_article = json.dumps(article, json_File)
else:
print "article could not be added"
#json_File.close()
return render_template('updated.html', save_article = save_article, article = article)
except:
print "This didn't work."
return render_template('errorHandler.html'), 404
Example from (http://blog.luisrei.com/articles/flaskrest.html)
#app.route('/echo', methods = ['GET', 'POST', 'PATCH', 'PUT', 'DELETE'])
def api_echo():
if request.method == 'GET':
return "ECHO: GET\n"
elif request.method == 'POST':
return "ECHO: POST\n"
elif request.method == 'PATCH':
return "ECHO: PACTH\n"
elif request.method == 'PUT':
return "ECHO: PUT\n"
elif request.method == 'DELETE':
return "ECHO: DELETE"
Probably best to have a if/elif/else for each method in the decorator, prevents weird bug and edge cases.
I think you should change this part:
if request.method == 'POST' or request.method == 'PUT':
For better practices, i think you should do:
if request.method == 'POST' or request.method == 'PUT':
# do your code here, which edit into your database
if request.method == 'GET':
# do GET code here, which return data from your database
Or separate your https methods into different functions
First of all, json.dumps() "dumps" to a string, not a file. So
save_article = json.dumps(article, json_File)
will return a string which is then bound to the save_article variable, but the file is not actually modified. You probably meant to use json.dump(article, json_File) which does accept a file as the second argument.
Note: The file argument is silently ignored in Python 2, which I assume that you are using because it would show up as an error in Python 3.
There might be other problems. One is that articles will be appended to the file, but it would seem that the intention of the code is to update an existing article. It's generally impractical to update text files in place. A better method would be to iterate over the articles, updating those that match the title. Then rewrite the whole file once at the end. Here's an example:
with open("articles.json", 'r') as json_File:
articles = json.load(json_File)
# update any matching articles
for article in articles['article']:
if title == article['title']:
article['author'] = request.form['author']
article['text'] = request.form['text']
article['article_id'] = request.form['article_id']
# rewrite the whole JSON file with updated dictionary
with open("articles.json", 'w') as json_File:
json.dump(articles, json_File)
As you are updating the article data you might want to consider using a simple database to manage it. You could take a look at Flask SQLAlchemy.
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.