How do you integrate HTML with Django? - python

I have an HTML file that has a web page design with a single form, for a user to enter his name. I want to create an six entry array for every submission (to later be filled with information on another page)
Is Django the proper utility to use for this? I would like to have the html design file and the python back end processing as separate files. If so, can anyone point me towards a good place to read about integrating HTML and underlying python codes that process HTML submission forms?

Django may be overkill for this. If all you want is a way to link a form to some backend Python code, a micro framework like Flask might be a better choice.
Here is how you do a simple form with Flask:
Create a directory project and inside it, a directory templates
Your template is simple:
{% if name %}
Hello {{ name }}
{% endif %}
<form method="POST">
<input type="text" name="name" value="Enter your name">
<input type="submit">
</form>
Save that as index.html in the templates subdirectory.
Create a file called go.py in the project directory, and in it copy and paste this:
from flask import Flask
from flask import render_template
from flask import request
app = Flask(__name__)
#app.route('/',methods=['POST','GET'])
def process_form():
if request.method == 'POST':
form_input = request.form['name']
return render_template('index.html',name=form_input)
else:
return render_template('index.html')
if __name__ == '__main__':
app.run(debug=True)
Finally from the project directory, type:
python go.py
Open your browser and go to http://localhost:5000/

You can create html form in Django, though you may have to convert the form to a template.
In case this you first time to use django, you may go though the official Django book

Django provides a template system (in which the presentation files are separate from the business logic and the entire system is highly decoupled). The template language is simple (but very powerful) text substitution on top of an existing text file. You can use the Django templates in HTML (full or partial), text, XML, JSON, or nearly any other text-based format.
Django also allows you to hook into another template system, but I don't know a lot about how that works.
Look at the Django template documentation for more information.

Related

How do I clear out user input after each use on pythonanywhere- trying to use Flask sessions

I am trying to build a simple site where a user inputs a paragraph of information (which is largely the same format each time), then I have a function that alters that paragraph to simplify it (the simplify_report function below), and spits the simplified version out for the user to have.
So far the program below works really well and I'm mostly happy with it. However, I am using pythonanywhere and the "comments" variable is global so it doesn't erase the simplified report when I reload the page (they just build up). I have looked into Flask's sessions option, but I just can't seem to figure out making it work with the below program (all the examples I'm seeing are for user login and I just need the site to be cleaned up/cleared out with each reload).
Alternatively, could I at least add a button the user could push to clear out the old outputs/comments? How would I go about that?
I appreciate any help!
#From the main file:
from flask import Flask, render_template, request, url_for, redirect
from run import simplify_report
app = Flask(__name__, template_folder="templates")
comments =[]
app.config["DEBUG"] = True
#app.route("/", methods=["GET", "POST"])
def index():
if request.method == "GET":
return render_template("page.html", comments=comments)
newreport = simplify_report(request.form["contents"])
comments.append(newreport)
return redirect(url_for('index'))
#Relevant section from my page.html file:
{% for comment in comments %}
<div class="row">
{{ comment }}
</div>
{% endfor %}
As a side note, my 'newreport' generated is all jumbled into one line and I can't seem to figure out how to format it to separate it into separate different lines. Not my main issue here though.
You need to store the data outside your web app on PythonAnywhere. Consider using a database for that. There is no persistency for data in the memory, as processes serving your web app could stop and start on a different server at any time.

how to use dynamic templates in python pyramid

i've finished developing a website, it's working fine however i am trying to optimize my website by adding dynamic templates, and want to make sure that if it can be done on pyramid python.
for example, in my jinja template i have the following:
{% block article_detail %}
<form action="{{request.route_url('Sports_News_Action',action=action)}}" method="post" class="form">
{% if action =='edit' %}
{{ form.id() }}
example in my controller:
#view_config(route_name='Sports_News_Action', match_param='action=create',
renderer='StarAdmin:templates/edit_sports.jinja2')
def general_create(request):
entry = SportNews()
the request route will have to match the one in my controller in order to run the function. what i want to do is how do i replace the one in jinja with a dynamic variable, to use the one jinja template lets say for different views/controllers with different route_names.
I think in your situation the simplest solution is to leave action undefined and the browser will submit the request to the current url. You only need to specify action if you want to submit the form to a different url than the current. That being said, you can use lots of different options in pyramid to generate a url as well. For example, request.url is the current url, or request.matched_route.name is the name of the current matched route.

Extending a base tpl file and editing the body of it in bottle

I am familiar with flask, and trying hands on bottle module. I wanted to have a single base.tpl file which can have an editable body and the other tpl files could extend this base file and edit in its body to change the content. Like in flask, using jinja, we could use {% block bodyContent %}{% endblock %} and insert the html body content later when needed. How can we achieve the same with bottle module?
Bottle comes with jinja2 support, out of the box. Here's a toy example, just to illustrate. Note that you may prefer to use Bottle's jinja2_view rather than return a template directly.
from bottle import jinja2_template
app = Bottle()
home_template = '''
{{greeting}} - Thanks for stopping by.
'''
app.route('/')
def home():
return jinja2_template(home_template, greeting='Hello!')
You can find examples of more advanced usage here.
Actually bottle comes with this solution built into it's own template engine.
https://bottlepy.org/docs/dev/stpl.html#template-functions
include(sub_template, **variables)
Render a sub-template with the specified variables and insert the resulting text into the current template. The function returns a dictionary containing the local variables passed to or defined within the sub-template:
% include('header.tpl', title='Page Title')
Page Content
% include('footer.tpl')
rebase(name, **variables)
Mark the current template to be later included into a different template. After the current template is rendered, its resulting text is stored in a variable named base and passed to the base-template, which is then rendered. This can be used to wrap a template with surrounding text, or simulate the inheritance feature found in other template engines:
% rebase('base.tpl', title='Page Title')
<p>Page Content ...</p>
This can be combined with the following base.tpl:
<html>
<head>
<title>{{title or 'No title'}}</title>
</head>
<body>
{{!base}}
</body>
</html>

Grab and manipulate user data without models

I'm not sure if this is even possible, but I would like to grab a user's input, pull it into my views.py, manipulate it, and then use that data in other views.
I do not need this data stored in a database, as I won't be referencing it again, and I want to keep this as lightweight as possible.
Currently, I'm trying to pull data from espn's fantasy football site using the python library espnff. My homepage consists of a textfield box and a submit button (Think of google.com).
I have functions set up that will comb through an espn url such as http://games.espn.com/ffl/clubhouse?leagueId=123456 to grab the leagueID, from there I make use of espnff to grab more info on that league.
My ideal use case is someone comes to my site, copies and pastes their league url like the one above, clicks submit and then brings them to https://example.com/{{ leagueID}/ which will display different info that I gather.
I have not found a way to do this without submitting the user input to a model. Is possible to avoid using the database? If so how?
Not sure I understood it right, but what you are trying to do can easily be done without using any models/database or any other kind of persistent storage.
The user submits that information using the form, you grab the URL from the request object in your view, parse the URL to get the league_id and then redirect the user to /{league_id}.
Then on that view, you gather the league_id parameter (from the url), use the library (espnff) to fetch the data with that id and then render the template with that data.
For example, the implementation would be something in these lines:
Make a form in your html template:
<form method="post" action="/">
{% csrf_token %}
<input type="text" name="league_url"/>
<input type="submit" value="Submit" />
</form>
in urls.py:
url(r'^$', index_view, name="index"),
url(r'^(?P<league_id>[0-9]+)$', league_view, name="league_view")
in views.py:
def index_view(request):
if request.method == 'POST':
league_url = request.POST.get('league_url', None)
# Your code to parse the URL and extract the ID
return HttpResponseRedirect('/{}'.format(league_id))
else:
# render form template
def league_view(request, league_id):
# your code here using the league_id
# and render the page with data
(I didn't tested that code, I just wrote it quickly as an example of the flow)
The django documentation describes quite extensively how to do caching with django. You can find the documentation on how to set that up here
Once it's been set up you simply use the cache in the following way
from django.core.cache import cache
cache.set('my_key', 'my_value', 60) # number is in seconds
value = cache.get('my_key')
You can provide dictionaries and such as values. The caching framework will serialize that for you using pickle.

How to show widgets on pages in Flask?

How can I create a widget on the site, such as login forms, dynamic menu (items taken from the database), site statistics?
I know that you can render a template that will extend out of a base template. And in the base template you can create these widgets.
But I do not know how to move the logic from the base template to my code. For example, the selection data for the block. Such actions certainly can be done in the template, but it would be a poor method in my opinion.
Sorry for my bad English. If you can not understand, I'll try to rephrase.
You would use a python library called WTForms. It helps you write code for creating forms and other widgets backed by database which you can render using jinja2 templates.
class YourForm(Form):
your_field1 = TextField()
....
your_fieldn = SubmitField()
#app.route('/')
def view():
form=YourForm()
return render_template('your.html', form=form)
In your.html
<form >
{{ form.your_field1 }}
....
{{ form.your_fieldn }}
</form>
Check out this flask pattern for form validation and rendering to know more about it.
Edit: To create global variables available to all templates,there are two ways:
You can use global dict of jinja environment.
This is the code:
app.jinja_env.globals.update({'variable':1})
You can use ContextProcessor. Code:
#app.context_processor
def inject_variable():
return dict(variable=1)
Now you can access variable in any template of your app.

Categories