Submitting empty form and weird output - python

Here's my form :
<form action = "/search/" method = "get">
<input type = "text" name = "q">
<input type = "submit" value = "Search">
</form>
And here's my view:
def search(request):
if 'q' in request.GET:
message = 'You searched for: %r' % request.GET['q']
else:
message = 'You submitted an empty form :('
return HttpResponse(message)
When I try to input something everything works fine, except for weird u' ' thing. For example when I enter asdasda I get the output You searched for: u'asdsa'. Another problem is that when I submit an empty form the output is simply u'', when it should be "You submitted an empty form :(". I'm reading "The Django Book", the 1.x.x version and this was an example..

The "weird u thing" is a unicode string. You can read about it here: http://docs.python.org/tutorial/introduction.html#unicode-strings
And I'm guessing since the user pressed submit, you get a request that has an empty q value (u'') since the user didn't enter anything. That makes sense, right? You should change your if statement to check for this empty unicode string.

For the first problem, try using %s instead of %r. What you're doing is 'raw' formatting, which, when the string is unicode, tells you that. Normal string formatting will just copy the value without the 'u' or quotes.
For the second problem, a text input will always have the key in the dictionary. Instead of you if statement, try:
if request.GET['q'] != "":
to test if the string is empty.

'q' is present in the request.GET dictionary after the form is submitted, it just happens to be empty in that case. Try this, to show the error message when submitting an empty query:
if 'q' in request.GET and request.GET['q'] != '':

The strange u is due to the %r which calls repr-- use %s instead.
>>>'%r' % u'foo'
[out] "u'foo'"
>>>'%s' % u'foo'
[out] u'foo'

Related

How to extract hashtag form a user post/string?

i want to parse a string from a user input that has #hashtag and print out the result together with other words too
just the way facebook and twitter handles it :)
for example:
a user posts
" hello #word, am learning #python and #django today! "
i want the out put to be:
hello #word, am learning #python and #django today!
this is how far i've gone:
#login_required
#ajax_required
def post(request):
last_feed = request.POST.get('last_feed')
user = request.user
csrf_token = (csrf(request)['csrf_token'])
feed = Feed()
feed.user = user
post = request.POST['post']
lookup_hash_tag = post.strip()
hstg=re.compile(r"#(\w+)")
#print pat.findall(s)
for hashtag in hstg.findall(lookup_hash_tag):
post = "<span><a href='/hastag/?q={}'>{}</a> </span> {}".format(hashtag, hashtag, post.replace('#', '#'))
if len(post) > 0:
feed.post = post[:255]
feed.save()
html = _html_feeds(last_feed, user, csrf_token)
return HttpResponse(html)
I have no real idea about your question but I see a few things wrong:
Instead of the for loop over the matches this can be used: re.sub(r'#([\w]+)', r"<span><a href='/hastag/?q=\g<1>'>#\g<1></a> </span>", a)
The post variable gets overridden in the for loop every time.
What is feed?
Lot of extra complexity (post.replace('#', '#') does nothing, having brackets around a variable does nothing, etc)
If the feed is a model, why not making the post field bigger? If you cut at 255, you might loose data (or cut in a middle of a link for example)
Please provide more info otherwise we are just guessing.

How to get the data submitted using POST on Python using Pyramid?

I'm looking for the equivalent of PHP's $_POST[] in Python.
On PHP, when you submit a form you can get its value by using the $_POST[].
How can I get this data on python?
here is my code.
function NewUser(){
var firstName = $('#firstName').val();
var dataString = '&firstName='+firstName;
$.ajax({
type:"POST",
url:"newusers",
data:dataString,
dataType:'text',
success:function(s){
alert(s);
},
error:function(){
alert('FAILED!');
}
})
}
This is where I throw the data.
#view_config(route_name='newusers', renderer='json')
def newusers(self):
return '1';
This code works fine and it returns and alert a string "1".
My question is, how can I get the submitted firstName? and put it on the return instead of "1".
Thank you in advance!
Another variation that should work:
#view_config(route_name='newusers', renderer='json')
def newusers(self):
# Best to check for the case of a blank/unspecified field...
if ('firstName' in self.request.params):
name = str(self.request.params['firstName'])
else:
name = 'null'
return name
Note: Be careful using str() function, particularly in python 2.x, as it may not be compatible with unicode input using characters beyond ascii. You might consider:
name = (self.request.params['firstName']).encode('utf-8')
as an alternative.
I manage to make it work with this code.
#view_config(route_name='newusers', renderer='json')
def newusers(self):
name = str(self.request.POST.get('firstName'))
return name

How can I extract an HTML form value?

Hi I have the following in a page:
input id="cu_first_name" class="input_text" type="text" value="test_name" name="cu_name"
I am trying to extract the value and print it in python.
I use:
username = driver.find_element_by_id("cu_first_name")
print username.text
But this will not work since there is no actual text there, I need the "test_name" to be printed, pls help me!
You've gotten the element by id. From there, you need to get the element's attribute. Give the following a try:
username = driver.find_element_by_id("cu_first_name")
value = username.get_attribute('value')
print value

I copy & pasted working code into my IDE - now Python is throwing tons of errors

I copied and pasted code into my IDE (TextWrangler). Now when I try to run my code, I get a ton of random errors regarding indentation and invalid syntax.
The code worked perfectly before I copied & pasted it from one Django view into another. I'm almost 100% sure the code is still correct in my new view, however, every time it runs I'll get a ton of errors relating to indentation and invalid syntax (even multiline comments like ''' trigger an "invalid syntax on line 234" error.
I've tried switching IDE's over to sublime, and even backspacing all indentations and then retabbing them to no avail. Each time I fix an "error" on one line, a new error on another line is created.
My code is below, please let me know any thoughts on how to fix.
#require_POST
def pay(request):
if request.method == 'POST':
form = CustomerForm(request.POST)
if form.is_valid():
# If the form has been submitted...
# All validation rules pass
#get the customer by session'd customer_id
c = get_object_or_404(Customer, pk = request.session['customer_id'])
#assign shipping info from POST to the customer object
c.first_name = request.POST['first_name']
c.last_name = request.POST['last_name']
c.street_address = request.POST['street_address']
c.city = request.POST['city']
c.state = request.POST['state']
c.zip = request.POST['zip']
#assign email info from POST to the customer object
c.email_address = request.POST['email_address']
stripe.api_key = REDACTED
# Get the credit card details submitted by the form
token = request.POST['stripeToken']
#tries to save the newly added form data.
try:
#save the new customer object's data
c.save()
########## THIS HANDLES CREATING A NEW STRIPE PAYMENT ################
# Create a Customer
try:
customer = stripe.Customer.create(
card=token,
plan="monthly",
email= c.email_address)
#need to save customer's id (ex: c.stripe_id = token.id)
#if there's a token error
except stripe.error.InvalidRequestError, e:
pass
#if the card is declined by Stripe
except stripe.error.CardError, e:
body = e.json_body
err = body['error']
print "Status is: %s" % e.http_status
print "Type is: %s" % err['type']
print "Code is: %s" % err['code']
# param is '' in this case
print "Param is: %s" % err['param']
print "Message is: %s" % err['message']
except stripe.error.AuthenticationError, e:
# Authentication with Stripe's API failed
# (maybe you changed API keys recently)
pass
except stripe.error.APIConnectionError, e:
# Network communication with Stripe failed
pass
except stripe.error.StripeError, e:
# Display a very generic error to the user, and maybe send
# yourself an email
pass
except Exception, e:
# Something else happened, completely unrelated to Stripe
pass
return render(request, 'shipment/confirm.html', {'date' : 'April 15, 2014'})
#passes the context to the template for confirming the customer's data
#context = { 'email_address' : c.email_address, 'first_name' : c.first_name,
# 'last_name' : c.last_name, 'street_address' : c.street_address,
# 'city' : c.city, 'state' : c.state, 'zip' : c.zip, }
#return render(request, 'shipment/pay.html', context)
#If there is a duplicate email it redirects the user back to the form with no error message.
#If anything else happens, it redirects the user back to the form.
else:
form = CustomerForm() # An unbound form
return render(request, 'shipment/createAccount.html', { 'form': form } )
Here's a couple of screenshots of your code in my editor with tabs (set to 4) and space characters shown in a reddish color. As you can see it contains quite a hodgepodge of the two on many lines. Python is very whitespace sensitive and it's important to be consistent. This is usually handled by configuring your editor to always convert tabs to n whitespace characters (or vice versa, but the former is often preferred).
To fix your problem, re-indent everything using a single method. My editor also has a convert-tabs-to-spaces command which could be used first to simplify the task somewhat.
This is why you should use soft tabs instead of hard tabs. You have at least one line that mixes them (check out the line with c.save()), looking at the edit version of your code. Change your IDE settings to always use spaces or tabs (if you haven't already), I recommend spaces.
See this question for how to view whitespace in sublime to find the offending tab character.

BadValueError thrown when entering Integer in html form

I'm working with Python to create a Google App Engine application.To test my app, i am using html forms to enter data.
In my form i have a line:
<tr><td>Age</td><td><input type="number" size="10" name="age"/></td></tr>
and in my model class, a property defined like this:
class Person(ndb.Model):
...
age = ndb.IntegerProperty()
when i test my app locally it displays the form but on entering a value for age, i get a BadValueError: Expected integer, got u '23' message.Posting image because i do not know how to copy command prompt text.I hope it's clear enough.
Edit: This is how the data is been passed from html form.
# Data taken from the registration form (above) is used to
# create a new member.
class PersonHandler(webapp2.RequestHandler):
def post(self):
# need to check this member-name does not exist
name = self.request.get('name')
callback = self.request.get('callback')
member = Member.get_by_id(name)
if member: # This member name already exists.
self.error(409) # This is the HTTP status code for 'unable to process due to conflict'
else:
...
a = self.request.get("age")
member = Member(age=a,...)
member.put()
if callback:
self.response.write(callback + '(' + member.toJSON + ')')
else:
self.response.write(member.toJSON())
Can someone tell me what am doing wrong?
You simply need to convert the retrieved value to an integer:
...
else:
...
a = int(self.request.get("age"))

Categories