I'm new to Django. Please help me with the below.
I have a User form who provides URL1 and URL2.. These URLs need to be passed to another Python script[redirects.py] which will do the Validation to check whether they are in a valid URL format and return the Message to the User.
Now my question is how to write my views.py so as to get this done. I got to know that we can import the redirects.py in my views.py and call it. But I'm not aware of how to print the messages in my browser. Please help. Let me know if any more info is required.
def shortcuts_process(request):
print request.POST
return HttpResponse("Source is %s\nDestination is %s" % (request.POST['source'],request.POST['destination']))
Update :
This is my script overview. I have got a python script[redirects.py] in my system which accepts Source and Destination URLs. Once accepted, it validates whether they are in URL format, then takes backup, then add them into .htaccess and display the line added to the file. While doing all this, it keeps intimating the User with the information on whats happening in the script.
Now I have made the django to create a web portal which provides the User to input source and Destination. Now i want to call the script from views.py and print all those redirects.py Script output in User's web browser.
Please help me in getting this, I have spent an entire day looking for this answer. Thanks.
Update 2:
Please let me know why the below is not getting displayed in my browser
From views.py
def shortcuts_process(request):
if 'source' in request.POST and 'destination' in request.POST and request.POST['source'] and request.POST['destination']:
src=request.POST['source']
desti= request.POST['destination']
my_result=process_input(src,desti)
return render_to_response('results.html',{'result': my_result}
From results.html :
<html>
<head>
This is the result page to User
</head>
<body>
<ul>
{% for each_line in result %}
<p>{{ each_line }}</p>
{% endfor %}
</ul>
<p>
I'm supposed to be printed</p>
</body>
</html>
From browser output :
This is the result page to User
I'm supposed to be printed
From Linux prompt :
[10/Jun/2013 04:41:11] "GET /redirects HTTP/1.1" 200 727 [10/Jun/2013
04:41:14] "GET /choice?selection=shortcuts HTTP/1.1" 200 817 The URL
is not in the right format The URL is not in the right format
[10/Jun/2013 04:41:18] "POST /shortcuts.conf HTTP/1.1" 200 125
So now my question, why the Message The URL is not in the right format is not getting displayed on browser rather it displays in Linux prompt. Please help. Thanks
Whatever string you want to display in the browser, return it in the HttpResponse.
You could try something like:
#validation.py
def validate(url1, url2):
# perform validation here
if valid:
return "urls are valid"
else:
return "urls are invalid"
#views.py
def shortcuts_process(request):
print request.POST
url1 = request.POST.get('url1', '')
url2 = request.POST.get('url2'. '')
return HttpResponse(validate(url1, url2))
Hope that helps.
For form validation, please refer to Chapter 7 in the django book (http://www.djangobook.com/en/2.0/chapter07.html)
Thanks all.. I managed to get the answer.
Rather having my function validate_url to print the values, changing it to return has given me the desired result.
I'm being so dumb to find this out. Failure is the stepping stone of Success !! :O)
Related
I am writing a tool to record and monitor downtime on a range of equipment.
I have my file structure as below:
File Structure
Sites is just a subfolder containing individual HTMLS for where the equipment is located.
Currently, flask runs webapp.py which contains:
>from . import app
>#app = (__init__.app)
>from . import views
>from . import ReportingTool
views.py has all of my #app.route's in it, up until the [site].html files. From there, on the [site].html file I ask for input from the user. I haven't started writing code to record the user input in any meaningful way, just want to get the data to a python script and commit them to variables. To this end, in the html file I have
<body>
<div class="menu">
<form method="post" enctype="multipart\form-data" action="{{ url_for('downTime') }}">
<fieldset class="datafieldset">
This then requests different data from the user in the form of multiple field sets as seen here: fieldsets
as you see in the code snippet above I set the action to be url_for('downTime'), downTime is a function in my python file ReportingTool.py. this throws out an error, "werkzeug.routing.exceptions.BuildError: Could not build url for endpoint 'downTime'. Did you mean 'supportguide' instead?" traceback
Is there something I need to add or specify on the html document to enable this page (and the other [site].html pages to call functions from the ReportingTool.py file? the #app.route that calls the [site].html file is this and that is called with a redirected from here I've only got it setup like that becuase I wanted the name for the site to appear in the address bar.
Thanks in advance.
I am not sure on steps to fix as I am kind of throwing myself in the deep end to learn basic coding by creating an application for my workplace to replace an excel spreadsheet I created.
You are not reaching the downTime function in the ReportingTool.py file. I suggest trying add_url_rule in your views.py by adding the /reported endpoint referencing the downTime function in ReportingTool.py. Something like this;
app.add_url_rule('/reported', 'ReportingTool.downTime', view_func=ReportingTool.downTime, methods=METHODS)
This answer is based on the responds for this question. You are trying to reach a function in a different file from your main view file. Assuming you are calling the page with the form from a function in the views.py file.
Solved with info from Kakedis' input, and the links they provided.
I added:
app.add_url_rule('/reported', 'ReportingTool.downTime', view_func=ReportingTool.downTime, methods=METHODS)
to webbapp.py, then:
#app.route('/reported')
def downTime():
try:
DTref = request.form['refDT']
except:
DTref = "No Reference"
print(DTref)
print("reported")
return(render_template("/UserRip.html"))
to ReportingTool.py
This now prints the above to console to confirm it's pulling the correct func and brings the user back to the starting page.
I'm trying to create a list of clickable links to external URLs. My HTML file looks like this
<ul>
{% for post in posts %}
<li><a href={{url_for('go_to_reddit', url=post.url)}}>{{ post.title }}</a></li>
{% endfor %}
</ul>
and the python file like this
#app.route('/redirect/"<url>"')
def go_to_reddit(url):
print("Redirecting to ", url)
return redirect(url)
I keep getting the following error whenever I press on one of the links
Not Found
The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.
I know it's not reaching the redirect function even though it hits the URL since my console doesn't print anything.
I don't think you can have quotes in a route parameter i.e. #app.route('/redirect/"<url>"') should be #app.route('/redirect/<url>') . Put another way, try dropping the quote around <url>
If you can't have quotes in a url parameter and you need to pass a complete url, then you should consider passing it as a query parameter e.g. /redirect/?link=post.url. Then in your handler for the route, you will do url = request.values.get('link', None)
I have a login page for a flask app with cloud database, I want to test the results after logging in, specifically, I want to test the HTML elements after logging in. I have seen people test return status code or using assertIn to check if data exist.
Is there a way for me to target a specific HTML tag, like <h1 id="userTitle"> </h1> from rendered templates after POST username, password to the route function login()
def test_users_login(self):
result = self.app.post('/login', data=dict(username='Nicole', password='abc123'), follow_redirects=True)
# I want to check the HTML tag's text value data after logging in
self.assertEqual(result.data.getTag("h1", b"Nicole") #What I imagined using <h1>
self.assertEqual(result.data.getId("user", b"Nicole") #What I imagined using id
#This returns true which is okay, because 'Nicole' exists in the whole page
self.assertIn(b'Nicole', result.data)
In my rendered jinja2 template I have this which is after logging in.
<h1 id="userTitle">{{ session['username'] }},Welcome!</h1>
I guess assertIn works well, but I just want to know how to test an HTML tag without running a browser test.
Although I didn't get a correct answer from here, but I just managed to do the unit-test with just assertIn, by checking the contents of the page.
Thanks everyone
I'm rendering a bunch of posts on a page where a user can browse listings and click on one of them and be sent to a 'singles page' for more information on whatever product they clicked. This method works for every link EXCEPT for the first one.
Anytime I click on the very first link of the page, I get a Not Found: The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again. error.
The logic I have in place for the HMTL/jinja is (everything is closed off properly, I'm cutting some unnecessary code for the sake of brevity):
{% set i = 0 %}
{% for row in data %}
{% set i = i + 1 %}
<a href="/iLike/{{ i }}">
<li>content</li>
</a>
and my python code:
#app.route('/iLike/<int:num>', methods=['GET','POST'])
def single2(num):
try:
loc = session.get('loc')
transType = session.get('transType')
data = singlesQuery()
return render_template('single.html', loc=loc,transType=transType,data=data[num-1])
except Exception as e:
return (str(e))
There is no need to build URLs manually. The best way it to use flask's built-in function url_for:
{{url_for('single2', num=i)}}
There is also no need for calculating the i manually, becaue there is built-in loop.index and loop.index0:
{% for row in data %}
<a href="{{url_for('single2', num=loop.index)}}">
I believe this should always create a valid URL.
I have a form that has to be filled and I have written the code using mechanize to fill the form details and submit it. Everything is working fine as expected and I'm able to submit it and I'm also getting the confirmation as Form Submitted Successfullyin the next page.
Now, I have to read this content, the Status- Form Submitted Successfully or if the attempt is not successful - Form NOT Submitted Successfully from the next page (page after submission of the form) along with other details like my name, form number, form name and status which all are displayed in one line.
DEV D 0911 Scientific_Conference Form Submitted Successfully
After the code - res = br.submit(), how do I read all these contents of the next page and display it in my output. What should I do to capture the next page contents and display accordingly? Any suggestions would be appreciated. Kindly help me in understanding this process. Thanks in advance.
I'm not even able to display the html contents.
Code I used (but not working):
res = br.submit()
final = res.geturl()
print final
x = br.open(final)
print "Loading...\n"
print (x.read())
print "program ended"