I have a list of articles.
After I press Edit, I am redirected to another page containing in the url the id of the article that wants to be edited.
Edit
This is where I am redirected:
And I want the inputs to be filled with the title and the body text of the respective article.
This is my backend function:
#app.route('/edit_article/<string:id>', methods=['POST', 'GET'])
def edit_article(id):
conn = mysql.connect()
cursor = conn.cursor()
result = cursor.execute("SELECT * from articles where id=%s", [id])
data = cursor.fetchone()
if result < 0:
flash("Article does not exist!")
cursor.close()
conn.close()
return render_template("edit_article.html", data=data)
How can I use data to fill those inputs? Please help. Thank you.
I will put also the edit_article.html
{% extends 'layout.html' %}
{% block body %}
<div class="container">
<div class="jumbotron">
<h1>Bucket List App</h1>
<form class="form-addArticle">
<label for="inputTitle" class="sr-only">Title</label>
<input type="name" name="inputTitle" id="inputTitle" class="form-control" placeholder="Title" required autofocus>
<label for="inputBody" class="sr-only">Body</label>
<input type="text" name="inputBody" id="inputBody" class="form-control" placeholder="Body" required autofocus>
<button id="btnEditArticle" class="btn btn-lg btn-primary" type="button">Update article</button>
</form>
<p class="text-center" style="color:red" id="message"></p>
</div>
</div>
{% endblock %}
You can just need to add value="{{ ... }}" to your inputs:
<input type="name" value="{{ data[0] }}" name="inputTitle" id="inputTitle" class="form-control" placeholder="Title" required autofocus>
<input type="text" value="{{ data[1] }}" name="inputBody" id="inputBody" class="form-control" placeholder="Body" required autofocus>
But it's recommended to name the values:
name, text = cursor.fetchone()
return render_template("edit_article.html", name=name, text=text)
and then
<input type="name" value="{{ name }}" name="inputTitle" id="inputTitle" class="form-control" placeholder="Title" required autofocus>
<input type="text" value="{{ text }}" name="inputBody" id="inputBody" class="form-control" placeholder="Body" required autofocus>
But I'd personally recommend WTForms module instead of rendering forms manually - it can for example help to validate your inputs properly.
Related
I have 3 form inputs that will be submitted when one master button is clicked to then be passed into a view as the request parameter. I would like to get the values of first_name, last_name and email inside my view using request.get(). When the button is clicked the values inside my form appear as None
HTML:
<div id="form_content">
<form action="" method="post">
<section class="form_inputs">
<label for="first_name">First Name:</label>
<input type="text" id="first_name">
</section>
<section class="form_inputs">
<label for="last_name">Last Name:</label>
<input type="text" id="last_name">
</section>
<section class="form_inputs">
<label for="email">Email:</label>
<input type="text" id="email">
</section>
<input type="submit" value="Submit">
</form>
</div>
views.py
def home(request):
form_response = request.GET.get("form_content")
print(form_response)
context = {"title": "Home"}
return render(request, "myApp/home.html", context)
first you need to add csrf_token in your code for post method and also give a name for each input like this :
<div id="form_content">
<form action="" method="post">
{% csrf_token %}
<section class="form_inputs">
<label for="first_name">First Name:</label>
<input type="text" name="first_name" id="first_name">
</section>
<section class="form_inputs">
<label for="last_name">Last Name:</label>
<input type="text" name="last_name" id="last_name">
</section>
<section class="form_inputs">
<label for="email">Email:</label>
<input type="text" name="email" id="email">
</section>
<input type="submit" value="Submit">
</form>
</div>
and then:
def home(request):
first_name = request.POST['first_name']
last_name = request.POST['last_name']
email = request.POST['email']
print(first_name, last_name, email)
context = {"title": "Home"}
return render(request, "myApp/home.html", context)
In your input tags, you have not passed the name parameter. Pass the name parameter in your input tags, as Django collects the data from the name tags.
For example, in your case, it must be:
<input type="text" id="id_first_name" name="first_name">
<input type="text" id="id_last_name" name="last_name">
<input type="text" id="id_email" name="email">
I'm trying to build a simple application using Leaflet in Flask, but I have a problem with the form. I want to send data from the form to my database but when I use the POST method, Flask doesn't want to read this method. When I used only GET, all values were empty in the database. When i used POST and GET nothing happened, none of the rows were added to the database.
forms.py
class EventForm(FlaskForm):
date_start = DateField(validators=[DataRequired()])
date_end = DateField(validators=[DataRequired()])
type = StringField(validators=[DataRequired()])
name = StringField(validators=[DataRequired()])
len_route = FloatField(validators=[DataRequired()])
mapa.html with Leaflet map and the form
<div id="fields">
<form action="" method="post">
<input type="text" id="route_len" class="form-control mb-2" name="route_len_input" placeholder="Długosc trasy">
<br>
<button id="draw-button" class="btn btn-success">Rysuj trase</button>
<br><br>
<input type="text" id="name" class="form-control mb-2" name="name_input" placeholder="Nazwa">
<br>
<input type="datetime-local" id="date_st" class="form-control mb-2" required name="date_st_input" placeholder="Data startu">
<br>
<input type="datetime-local" id="date_end" class="form-control mb-2" required name="date_end_input" placeholder="Data końcowa">
<br>
<select id="type" class="form-control mb-2" name="type_input">
<option></option>
<option value="Bieganie">Bieganie</option>
<option value="Rower">Rower</option>
<option value="Nordic walking">Nordic Walking</option>
</select>
<br>
<button type="submit" id="end-button" name="sub" class="btn btn-danger">Zakończ rysowanie</button>
<br><br>
</form>
</div>
routes.py
#app.route('/mapaa',methods=["GET","POST"])
def mapa():
if request.method == "POST":
data_pocz = request.form['date_st_input']
data_kon = request.form['date_end_input']
nazwa = request.form['name_input']
typ = request.form['type_input']
dlugosc = request.form['route_len_input']
event_database = Event(date_start=data_pocz, date_end=data_kon, type=typ, name=nazwa, len_route=dlugosc)
db.session.add(event_database)
db.session.commit()
return render_template('mapaa.html', title='Mapa')
You should link the form to your flask method
<form method="POST" action="/mapaa"> [...]
I saw all the conversations about this issue, but I can't solve it. I am new in this Python-Django programming so if anyone can help me? :)
This is my views.py:
class HistoryProjectCreate(CreateView):
template_name = 'layout/create_proj_history.html'
model = ProjectHistory
project = Project.objects.latest('id')
user = User.id
fields = ['user', 'project', 'user_start_date']
success_url = reverse_lazy('git_project:index')
Var project has to return latest project ID from database, and I have to use it ID in my html form:
<form class="form-horizontal" action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
<label for="user"></label>
<input id="user" type="text" name="user" value="{{ user.id }}" ><br>
<label for="project">Project title: </label>
<input id="project" type="text" name="project" value="{{ project.id }}" ><br>
<!--Here - "project.id" I need latest project ID-->
<label for="user_start_date">Start date: </label>
<input id="user_start_date" type="date" name="user_start_date" value="{{ projectHistory.user_start_date }}" ><br>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-success">Submit</button>
</div>
</div>
</form>
I am not sure if project = Project.objects.latest('id') is correct statement for getting the latest ID from Project table.
If you want the last Id of project, you need to order by id, and use last() function available on queryset
project = Project.objects.order_by('id').last()
Order_by doc
Last function doc
I'm a bit confused with all the django stuff and forms, I hope you can help me.
I'm migrating a cmd line app to django, and I think I don't need to mess with models (db) atm. I just would like to pass the parameters filled in a form to a python script that use these fields as parameters. I would like to keep my html code and skip render the form with a python form class since it has a lot of css code inside each one.
At the moment I have this form:
<form class="nobottommargin" id="template-contactform" name="template-contactform" action="{% url 'get_data' %}" method="post">
{% csrf_token %}
<div class="col_half">
<label for="name">Project Name <small>*</small></label>
<input type="text" id="name" name="name" value="{{ current_name }}" class="sm-form-control required" />
</div>
<div class="col_half col_last">
<label for="group">Project Group <small>*</small></label>
<input type="text" id="group" name="group" value="{{ current_group }}" class="required sm-form-control" />
</div>
<div class="clear"></div>
<div class="col_half">
<label for="version">Project Version<small>*</small></label>
<input type="text" id="version" name="version" value="{{ current_version }}" class="required sm-form-control" />
</div>
<div class="col_half col_last">
<label for="pType">Project Type<small>*</small></label>
<select id="pType" name="pType" class="required sm-form-control">
<option value="">-- Select One --</option>
<option value="bundle">Bundle</option>
<option value="multiple">Multiple</option>
<option value="git">Git</option>
</select>
</div>
<div class="col_half">
<label for="pPath">Project path<small>*</small></label>
<input type="text" id="pPath" name="pPath" value="{{ current_path }}" class="required sm-form-control" />
</div>
<div class="clear"></div>
<div class="col_full hidden">
<input type="text" id="template-contactform-botcheck" name="template-contactform-botcheck" value="" class="sm-form-control" />
</div>
<div class="col_full" style="margin: 50px 0 0 0 ">
<button class="button button-3d nomargin" type="submit" id="template-contactform-submit" name="template-contactform-submit" value="submit">Create Project</button>
</div>
</form>
So, I want to figure out what's the best way to write the get_data function. I also need some sort of custom validation about some fields that involves other checks that exceeds the basic checks, such as max_chars on each field. That means I need to create some sort of my own form.is_valid() function.
Hope you can help me!
Regards
I am trying to create a page to register users but the submit button in my bootstrap form isn't working. When I hit the submit button, I get a bad request error. Here is the code in my python file:
#app.route('/register', methods=['GET', 'POST'])
def register():
if request.method == 'POST':
if not request.form['username']:
error = 'You have to enter a username'
elif not request.form['email'] or '#' not in request.form['email']:
error = 'You have to enter a valid email address'
elif not request.form['password']:
error = 'You have to enter a password'
elif get_user_id(request.form['username']) is not None:
error = 'The username is already taken'
else:
print(request.form['username'])
db = get_db()
db.execute('INSERT INTO user (username, email, pw_hash) VALUES (?, ?, ?)',
[request.form['username'], request.form['email'],
generate_password_hash(request.form['password'])])
db.commit()
flash('You were successfully registered and can login now')
return render_template('control.html')
return render_template('register.html')
also i have a html file register.html:
{% extends 'layout.html' %}
{% block title %}Sign-up{% endblock title %}
{% block body %}
<div class="container">
<form class="form-register" role="form" method="post" action="{{ url_for('register') }}">
<h2 class="form-register-heading">Please sign up</h2>
<label for="username" class="sr-only">Username</label>
<input type="username" id="inputUsername" class="form-control" value="{{ request.form.username }}" placeholder="Username" required autofocus>
<label for="email" class="sr-only">Email address</label>
<input type="email" id="inputEmail" class="form-control" value="{{ request.form.email }}" placeholder="Email address" required autofocus>
<label for="password" class="sr-only">Password</label>
<input type="password" id="inputPassword" class="form-control" placeholder="Password" required >
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign up</button>
</form>
</div>
{% endblock body %}
I can't find where I did it wrong, I'm new to python and flask!
Your input fields have no name attribute. This will cause all of your checks to result in KeyErrors. The first step is to add the attribute to each input.
<input name="username" type="text" id="inputUsername" class="form-control" value="{{ request.form.username }}" placeholder="Username" required autofocus>
Note that I also checked the type attribute as there is no username type. email and password are valid values, email being added in HTML5.
The next step will be to change how you check for the fields. If you only care about the presence of the field, in is the way to go.
if 'username' not in request.form:
If, however, you also want a truty value, the get method is what you want.
if not request.form.get('username'):