way to store POST variables when using django - django-templates

with a form am searching schools nearby and displaying them as table.
inside views.py
def method1:
printquery = request.POST.copy()
zip = printquery['zip']
if not zip:
city = printquery['city']
state = printquery['state']
zip = getZip(city,state)
results = zipObj.getSchools(zip);
render_to_response('some.html',{'results':results,'query':printquery,})
inside template
<form id="print-search" target="_blank" action="" method="post" name="print">
<input type="hidden" value="{%if query%}{{query}}{%endif%} name="query"/>
<input type ="submit" value="Print the Results" name="submitPrint"/>
</form>
<table>
{% block xxx%}displays schools result {%endblock%}
</table>
when the "Print the results" button is clicked.I want to use 'query',
do the search again and print in separate page[I have no choice of storing in session id].
Problem am facing is, {{query}} is a turing to a string i.e.,u"{'zip': u'76123'"} on which i cannot do something like query['zip'],
Is there a way to solve this. Ideas are most welcome.

Instead of taking the whole dictionary as value, do something like this
<form id="print-search" target="_blank" action="" method="post" name="providerprint">
<input type="hidden" value="{%if query.zip %}{{query.zip}}{%else%}""{%endif%}" name="zip"/>
<input type="hidden" value="{%if query.city %}{{query.ciyt}}{%else%}""{%endif%}" name="city"/>
<input type="hidden" value="{%if query.state %}{{query.state}}{%else%}""{%endif%}" name="state"/>
<input type ="submit" value="Print this Search" name="submitProviderprint"/>
</form>
inside the views.py we can access this as
zip = params['zip']
city = params['city']
state = params['state']
and it worked for me.:)

Related

Using Scrapy for Crawling Pages Post Authentication

Taking cues and ideas from a previous post , I tried to come up with my own code.
However, using my code I've noticed that it doesn't really scrape anything and probably doesn't go beyond the authentication level at all. I say this because I don't see any Error Logs even when I put an incorrect password.
My best guess is that the HTML for the authentication fields is not contained in a "Form" tag and hence the formdata is possibly overlooking it. Might be wrong.
My Code so far:
class LoginSpider(BaseSpider):
name = 'auth1'
start_urls = ['http://www.example.com/administration']
def parse(self, response):
return [FormRequest.from_response(response,
formdata={'employee[email]': 'xyz#abc.com', 'employee[password]': 'XYZ'},
formxpath='//div[#class="form-row"]',
callback=self.after_login)]
def after_login(self, response):
if "authentication failed" in response.body:
self.log("Login failed", level=log.ERROR)
return
# We've successfully authenticated, let's have some fun!
else:
return Request(url="http://www.liveyoursport.com/administration/customers",
callback=self.parse_tastypage)
def parse_tastypage(self, response):
sel = Selector(response)
item = Item()
item ["Test"] = sel.xpath("//h1/text()").extract()
yield item
Here's the HTML section:
<div class="content-row">
<div class="special-header-title span_full">
<h3><span class="blue-text">Sign </span>In</h3>
</div>
</div>
<div class="content-row">
<div class="form-section checkout-address-edit span_80" id="sign-in-form" >
<form accept-charset="UTF-8" action="/employees/sign_in" class="new_employee" id="new_employee" method="post"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="✓" /><input name="authenticity_token" type="hidden" value="HQYZa0hNZ2Y+UvtbIk9OxI48Hlsnt+MiYOeV9ql2yWo=" /></div>
<div>
<div class="form-row">
<div class="form-col-1"><label for="employee_email">Email</label></div>
<div class="form-col-2">
<input id="employee_email" name="employee[email]" size="30" type="email" value="" />
</div>
</div>
<div class="form-row">
<div class="form-col-1"><label for="employee_password">Password</label></div>
<div class="form-col-2">
<input id="employee_password" name="employee[password]" size="30" type="password" />
</div>
</div>
</div>
<div class="form-row form-row-controls">
<div class="form-col-1"></div>
<div class="form-col-2">
<input class="sign-in-button f-right" name="commit" type="submit" value="Sign in" />
</div>
</div>
</form> <br>
Forgot your password?<br />
Didn't receive unlock instructions?<br />
</div>
From the docs:
formxpath (string) – if given, the first form that matches the xpath
will be used.
but it seems that you are not matching the form, rather the parent div.
Try it like this:
return [FormRequest.from_response(response,
formdata={'employee[email]': 'xyz#abc.com', 'employee[password]': 'XYZ'},
formxpath='//form[#id="new_employee"]',
callback=self.after_login)]
Also, if you only have one form element on the page, you don't need to define formxpath.

How to preserving textbox value after submission

"help me out am newbis in django"
in Template
<form method="get" role="search">
<input type="text" name="search" class="form-control" placeholder="Search">
<button type="submit">submit</botton>
</form>
after clicking on form submit ,it displays search result but text box value is null. i want to search keyword there ...
how to achieve this using java script .. ?
1-using the manual form
just put request.GET.search in the value, nothing to change in your views
template
<form method="GET">
Search: <input type="text" name="search"
value="{{ request.GET.search }}">
<input type="submit" value="Search">
</form>
2 - using forms
What about if you use form? Well, we will use session variable here.
forms.py
from django import forms
class SearchForm (forms.Form) :
search = forms.CharField(max_length=100)
template
<form method="GET">
{{ form.as_p }}
<input type="submit" value="Search">
</form>
views.py
from django.shortcuts import render
from app_name.forms import SearchForm
def myview(request):
if request.GET.get('search'):
request.session['search'] = request.GET.get('search')
#do query searching here
form = SearchForm(initial={
'search': request.session.get('search')
})
return render(request, 'search_page.html', {
'form': form
})
If you are working with a form object, then in your view, you can do:
def myview(request):
if request.method=="GET":
form = SearchForm(request.GET)
return render(request, 'searchPage.html', {'form':form,})

Textbox and variables javascript and HTML

I want to set two JavaScript variables as the values of these textboxes.
Can anyone can help me?
<form name="myform1">
<input type="number" name="pop_size" value="3">
<input type="button" value="Pop Size" id="population" onclick="setValue()">
</form>
<form name="myform2">
<input type="number" name="totalIterations" value="2">
<input type="button" value="Iterations" id="Iterations" onclick="setValue()">
</form>
You can use getElementsByName() to get a list of elements by their names in the form. Since your names are unique (which isn't necessary in the spec, but is a good idea for this exact reason), the array returned by that function should have exactly one element in it. Something like this:
var firstVariable = document.getElementsByName('pop_size')[0].value;
var secondVariable = document.getElementsByName('totalIterations')[0].value;
Or did you mean that you want to set the values to what's in a variable? That would be the reverse:
document.getElementsByName('pop_size')[0].value = firstVariable;
document.getElementsByName('totalIterations')[0].value = secondVariable;

Logging into a website using Mechanize and Nokogiri?

I am having some difficulty with one of our service providers login forms. The other sites are working fine but for some reason I can't get past their login form.
The website login for is like this:
<form accept-charset="UTF-8" action="/sessions" class="new_user_session" id="new_user_session" method="post"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="✓" /><input name="authenticity_token" type="hidden" value="kaLEkPesQfeheronzGTdfnVAzpuUiC+VmjVXBu540n8=" /></div>
<fieldset class="big">
<div class="form-row">
<div class="form-label">
<label for="user_session_email">Email</label>
</div>
<div class="form-field">
<input id="user_session_email" name="user_session[email]" size="30" type="text" />
</div>
</div>
<div class="form-row">
<div class="form-label">
<label for="user_session_password">Password</label>
</div>
<div class="form-field">
<input id="user_session_password" name="user_session[password]" size="30" type="password" />
</div>
<div class="form-comment"><p>Forgot your password?</p></div>
</div>
<div class="form-row optional">
<div class="form-field">
<label for="user_session_remember_me"><input name="user_session[remember_me]" type="hidden" value="0" /><input id="user_session_remember_me" name="user_session[remember_me]" type="checkbox" value="1" /> Remember me for 2 weeks</label>
</div>
</div>
</fieldset>
I have tried to login using the same code as other the other sites but it doesn't work.
# Create a new mechanize object
agent = Mechanize.new
# Load the dial9 website
page = agent.get("http://webapplication.co.uk")
# Select the first form
form = agent.page.forms.first
form.username = 'username
form.password = 'password'
# Submit the form
page = form.submit form.buttons.first
I have also tried a different way of logging in as suggested in other SO questions/answers:
email = 'user#domain.com'
password = 'password
# Create a new mechanize object
agent = Mechanize.new
# Load the postmarkapp website
page = agent.get("https://domain.com")
# Select the first form
form = agent.page.forms.first
form.field_with(:email => "user_session_email").value = email
form.field_with(:password => "user_session_password").value = password
# Submit the form
page = form.submit form.buttons.first
Using this method of authentication I get the following output when running the rake task:
undefined method `email' for [hidden:0x3fef2ab2b994 type: hidden name: utf8 value: ✓]:Mechanize::Form::Hidden
Upon closer inspection the above error seems to be due to the fact that there is a field immediately after the form is started:
<form accept-charset="UTF-8" action="/sessions" class="new_user_session" id="new_user_session" method="post"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="✓" /><input name="authenticity_token" type="hidden" value="kaLEkPesQfeheronzGTdfnVAzpuUiC+VmjVXBu540n8=" /></div>
Am I missing something? If so, what? Any pointers are appreciated!
Try changing
form.field_with(:email => "user_session_email").value = email
form.field_with(:password => "user_session_password").value = password
to
form.field_with(:name => "user_session[email]").value = email
form.field_with(:name => "user_session[password]").value = password

How to get Index of the FORM Element in the WebBrowser Control?

let say a site has 2 forms: one search form and the other is a registration form...
<form>
Search: <input type="text" name="s">
<input type="hidden" name="a" value="search">
<input type="submit" value="Search">
</form>
[..]website content blabla[...]
<h2>Registration</h2>
<form>
E-Mail: <input type="text" name="email">
<input type="hidden" name="a" value="reg">
<input type="submit" value="Register">
</form>
If I submit a form, I want to know to which form the clicked submit button belongs. GetElementbyId is not possible because the id is not always available. I want to get the index. Any ideas? (WebBrowser Element in VB.NET or C#)
You cant refer to Form object of Input Element e.g btn.Form.Name should work; give it a try
http://msdn.microsoft.com/en-us/library/aa703812(v=vs.85).aspx (reference to IHTMLInputElement::form Property)