I want to build a website with Flask and WTForms. But I cannot get the text input to work (The page will not let me enter any text into the boxes). Can you show me what is wrong?
This is what the page looks like:
This is the form I created with WTForms
from flask_wtf import FlaskForm
from wtforms import SubmitField, IntegerField
from wtforms.validators import DataRequired, NumberRange, EqualTo
class RequestDataForm(FlaskForm):
feature_count = IntegerField('Number of features', validators=[DataRequired(), NumberRange(min=1, max=50)])
effective_rank = IntegerField('Effective Rank', validators=[DataRequired(), NumberRange(min=1, max=EqualTo(feature_count))])
noise = IntegerField('Noise', validators=[DataRequired(), NumberRange(min=0, max=1)])
submit = SubmitField('Submit')
This is the layout.html
<!DOCTYPE html>
<html>
<style>
</style>
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
</head>
<body>
<main role="main" class="container">
<div class="row">
<div class="col-md-8">
{% with messages = get_flashed_messages(with_categories=true) %}
{% if messages %}
{% for category, message in messages %}
<div class="alert alert-{{ category }}">
{{ message }}
</div>
{% endfor %}
{% endif %}
{% endwith %}
{% block page_content %}{% endblock %}
</div>
</div>
</main>
</body>
</html>
and this is my page.html
{% extends 'layout.html' %}
{% block page_content %}
<div class="content-section">
<form method="POST" action="">
{{ form.hidden_tag() }}
<fieldset class="form-group">
<legend class="border-bottom mb-4">Fill with values.</legend>
<div class="form-group">
{{ form.feature_count.label(class="form-control-label") }}
{{ form.feature_count.label(class="form-control form-control-lg") }}
</div>
<div class="form-group">
{{ form.effective_rank.label(class="form-control-label") }}
{{ form.effective_rank.label(class="form-control form-control-lg") }}
</div>
<div class="form-group">
{{ form.noise.label(class="form-control-label") }}
{{ form.noise.label(class="form-control form-control-lg") }}
</div>
</fieldset>
<div class="form-group">
{{ form.submit(class="btn btn-outline-info") }}
</div>
</form>
</div>
{% endblock page_content%}
According to your HTML you are only outputting the label for each form element not the element itself. Try updating them all to:
<div class="form-group">
{{ form.noise.label(class="form-control-label") }}
{{ form.noise(class="form-control form-control-lg") }}
</div>
Related
I am writing a website on Flask, and I encountered a problem that when I send an email with a link to a password recovery page, the http address of which has a token that changes every time, the template that I connected is not generated at all. with completely wrong css styles.
Although the same template is connected in the same way to other pages and everything is fine, what is needed is generated
Here is my view function to handle this page
#app.route('/reset_password/<token>', methods=['POST', 'GET'])
def reset_token(token):
if current_user.is_authenticated:
return redirect(url_for('index_page'))
user = User.verify_reset_token(token)
if user is None:
flash('Неправильний,або застарілий токен', category='error')
return redirect(url_for('reset_password'))
form = ResetPasswordForm()
if form.validate_on_submit():
hash_password = generate_password_hash(form.password.data)
user.password = hash_password
db.session.commit()
return render_template('reset_password.html', title='Відновлення паролю', form=form,
css_link=css_file_reset_password_request_page)
For comparison, here is a function that connects to the same css-style
#app.route('/reset_password', methods=['POST', 'GET'])
def reset_password():
if current_user.is_authenticated:
return redirect(url_for('index_page'))
form = RequestResetForm()
if form.validate_on_submit():
user = User.query.filter_by(email=form.email.data).first()
if user is None:
flash('Неправильний email', category='error')
else:
send_reset_email(user)
flash('Повідомлення було надіслано на вашу електронну пошту,зайдіть туди,щоб отримати '
'інструкції', category='success')
return render_template('reset_password_request.html', title='Відновлення паролю', form=form,
css_link=css_file_reset_password_request_page)
But as a result, these pages have a completely different look
Here is the html template of this page(It is the same as reset_password_request from the previous function, only with some changes)
{% extends 'base.html' %}
{% block body %}
{{ super() }}
{% for cat, msg in get_flashed_messages(True) %}
<div class="flash {{cat}}">{{msg}}</div>
{% endfor %}
<div class="container">
<form class="box" method="POST">
{{ form.hidden_tag() }}
<h1 title="Будь ласка,придумайте новий надійний
пароль">Оновлення паролю</h1>
<div class="group">
<label>{{ form.password.label }}</label>
{{ form.password }}
</div>
<div class="group">
<label>{{ form.double_password.label }}</label>
{{ form.double_password }}
</div>
<div class="group">
<center><button>Відновити</button></center>
</div>
</form>
</div>
{% endblock %}
THIS IS MY base.html FILE
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="{{ css_link }}" type="text/css"/>
<script src="https://kit.fontawesome.com/b8991598b2.js"></script>
{% block title %}
{% if title %}
<title>{{ title }}</title>
{% else %}
<title>Сайт</title>
{% endif %}
{% endblock %}
</head>
<body>
<div class="content">
<header class="p-3 bg-dark text-white">
<div class="container">
<div class="d-flex flex-wrap align-items-center justify-content-center justify-content-lg-start">
<a href="/" class="d-flex align-items-center mb-2 mb-lg-0 text-white text-decoration-none">
<svg class="bi me-2" width="40" height="32" role="img" aria-label="Bootstrap"><use xlink:href="#bootstrap"></use></svg>
</a>
<ul class="nav col-12 col-lg-auto me-lg-auto mb-2 justify-content-center mb-md-0">
<li>Home</li>
<li>Features</li>
<li>Pricing</li>
<li>FAQs</li>
<li>About</li>
</ul>
<div class="search-box">
<input class="search-txt" type="text" placeholder="Search...">
<a class='search-btn' href="#">
<i class="fas fa-search"></i>
</a>
</div>
<div class="text-end">
Sign-up
Login
Logout
</div>
</div>
</div>
</header>
{% block body %}
{% endblock %}
</div>
<footer class="footer">
<ul class="nav justify-content-center border-bottom pb-3 mb-3">
<li class="nav-item">Home</li>
<li class="nav-item">Features</li>
<li class="nav-item">Pricing</li>
<li class="nav-item">FAQs</li>
<li class="nav-item">About</li>
</ul>
</footer>
</body>
</html>
And this is my connect to css_files in main.py
css_file = 'static/css/main.css'
css_file_authorization = 'static/css/login_form.css'
css_file_reset_password_request_page = 'static/css/request_passsword.css'
But here is an example of a page that is generated after switching from email:
And here is the one that should have been generated, and is generated in the case of the second handler function
Maybe someone knows how to solve it
I'm trying to build a simple signup and login form but I'm getting below error. I've tried to fix it by going through the documentation but no luck. can you please help.
"werkzeug.routing.BuildError: Could not build url for endpoint 'auth.Esp_Index'. Did you mean 'auth.login' instead?"
code in init.py
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
db = SQLAlchemy()
def create_app():
app = Flask(__name__)
app.config['SECRET_KEY'] = '\xbd\xc5H\xe5\xd0rX\xcc\x11\x99'
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://support:support#rea-lnx-tdin01:5432/postgres'
db.init_app(app)
from .auth import auth as auth_blueprint
app.register_blueprint(auth_blueprint)
return app
Code in auth.py
from flask import Blueprint, render_template, redirect
auth = Blueprint('auth',__name__)
#auth.route('/login', methods=["GET", "POST"])
def login():
return render_template('Loginpage.html')
#auth.route('/Esp_Index', methods=["GET", "POST"])
def registration():
#return '<h1> welcome to Index page </h1>'
return render_template('Esp_Index.html')
Html Templates
Code in Base Template
<!DOCTYPE html>
<html lang="en">
<head>
{% block head %}
<title>{% block title %}{% endblock %}</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="application/x-javascript"> addEventListener("load", function() { setTimeout(hideURLbar, 0); }, false); function hideURLbar(){ window.scrollTo(0,1); } </script >
<!-- Custom Theme files -->
<link href="{{url_for('static',filename='css/Styles.css')}}" rel="stylesheet" type="text/css" media="all" />
<!-- //Custom Theme files -->
<link href="//fonts.googleapis.com/css?family=Roboto:300,300i,400,400i,700,700i" rel="stylesheet"> <!-- //web font -->
{% endblock %}
</head>
<body>
<div id="content" >
<a href="{{url_for('auth.Esp_Index')}}" />
<a href="{{url_for('auth.login')}}" />
{% block content %}
{% endblock %}
</div>
<ul class="colorlib-bubbles">
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
Code in Esp_Index.html
{% extends "ESP_Base.html" %}
{% block title %}Web Console{% endblock %}
{% block head %}
{{ super() }}
{% endblock %}
{% block body %}
{% block content %}
<h1>Web Console SignUp Portal Form</h1>
{% with errors = get_flashed_messages() %}
{% if errors %}
{% for error in errors %}
<div class="alert alert-warning alert-dismissible fade show" role="alert">
<strong>{{ error }}</strong>
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
{% endfor %}
{% endif %}
{% endwith %}
<div class="main-w3layouts wrapper">
<div class="main-agileinfo">
<div class="agileits-top">
<form action="" method="POST">
<input type="text" name="Username" placeholder="Username" value="{{request.form.get.Username}}">
<input type="Email" name="Email" placeholder="Email" value="{{request.form.get.Email}}">
<input type="Password" name="Password" placeholder="Password" value="{{request.form.get.Password}}">
<input type="Password" name="RepeatPassword" placeholder="ConfirmPassword" value="{{request.form.get.RepeatPassword}}">
<input type="submit" value="SIGNUP">
</form>
<p>Don't have an Account? Login Now!</p>
</div>
</div>
</div>
{% endblock %}
{% endblock %}
Code in Loginpage.html
{% extends "ESP_Base.html" %}
{% block title %}Web Console {% endblock %}
{% block head %}
{{ super() }}
{% endblock %}
{% block body %}
{% block content %}
<h1>Web Console SignUp Portal Form</h1>
{% with errors = get_flashed_messages() %}
{% if errors %}
{% for error in errors %}
<div class="alert alert-warning alert-dismissible fade show" role="alert">
<strong>{{ error }}</strong>
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
{% endfor %}
{% endif %}
{% endwith %}
<div class="main-agileinfo">
<div class="agileits-top">
<form action="" method="POST">
<input type="text" name="Username" placeholder="Username" value="{{request.form.get.Username}}">
<input type="Password" name="Password" placeholder="Password" value="{{request.form.get.Password}}">
<p><input type = "submit" value = "Login"/></p>
</form>
</div>
</div>
{% endblock %}
{% endblock %}
When build a URL with url_for() in Flask, you should pass the endpoint of the view function, the default value of endpoint is the name of the view function, not the URL rule.
So you should write this in your template:
<a href="{{ url_for('auth.registration') }}" />
So, I've been trying to create a user login. When I click submit on my login form, I get this error:
Exception Type: TypeError
Exception Value: 'function' object is not iterable
Here's the full Traceback: http://dpaste.com/3D1B7MG
So, If I'm reading the Traceback correctly, the problem is in the {% extends "base.html" %} line of all_poss.html. So would that would mean the problem is actually inside base.html? or in the view that controls all_posts?
My all_posts.html
{% extends "base.html" %}
{% load staticfiles %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<style></style>
<title></title>
</head>
<body>
</body>
</html>
base.html
{% load staticfiles %}
{% load crispy_forms_tags %}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<HTML>
<HEAD>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">
<link rel="stylesheet" href="{% static 'css/base.css' %}">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="assets/css/bootstrap-responsive.css" rel="stylesheet">
<TITLE>{% block title %}{% endblock %}</TITLE>
</HEAD>
<BODY>
{% block content %}
<div class="navbar-wrapper">
<div class="post_button" style="width:58px; margin:0 auto;">
Submit a Post
</div> <!-- /.post_button-->
<div class="log_bar">
<ul>
{% if user.is_authenticated %}
<li>Welcome,</li>
<li>{{ user.username }}</li>
<li>|</li>
<li>Log Out</li>
{% else %}
<li>Please</li>
<li><a data-toggle="modal" data-target="#modal-login" href="">log in</a></li>
<li>or</li>
<li><a data-toggle="modal" data-target="#modal-register" href="">sign up</a></li>
{% endif %}
</ul>
</div><!-- /.log_bar -->
<nav class="navbar navbar-fixed-left navbar-static-top">
<div class="container-fluid">
<!-- Collect the nav links, forms, and other content for toggling -->
<ul class="nav navbar-nav ">
<li class="active">Home <span class="sr-only">(current)</span></li>
<li>All</li>
<li>New</li
<li class="dropdown">
Top<span class="caret"></span>
<ul class="dropdown-menu">
<li>hour</li>
<li>24 hrs</li>
<li>week</li>
<li>month</li>
<li>year</li>
<li>beginning of time</li>
<li role="separator" class="divider"></li>
<li>Custom Search</li>
</ul>
</li>
</ul>
</div><!-- /.container-fluid -->
</nav>
<div id="side_bar">
<form class="navbar-form navbar-static-top navbar-right" role="search" id="navBarSearchForm">
<div class="input-group">
<input type="text" class="form-control" placeholder="Search">
<span class="input-group-btn">
<button type="submit" class="btn btn-default" id="search_btn">
<span class="glyphicon glyphicon-search"></span>
</button>
</span>
</div>
</form>
</div><!-- /.side-bar -->
<button class="btn-block" id='hideshow' value='hide/show' style="display: block; height: 100%;"></button>
{% include 'register.html' %}
{% include 'login.html' %}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"> </script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"> </script>
<script type="text/javascript" src="{{ STATIC_URL }} /static/jquery.js"></script>
<script type="text/javascript" src="{{ STATIC_URL }} /static/jquery.leanModal.js"></script>
{% endblock %}
</BODY>
</HTML>
views.py
def login(request):
"""
Log in view
"""
if request.method == 'POST':
form = AuthenticationForm(data=request.POST)
if form.is_valid():
user = authenticate(username=request.POST['username'], password=request.POST['password'])
if user is not None:
if user.is_active:
django_login(request, user)
return render(request, 'all_posts.html', {'user': request.user})
else:
form = AuthenticationForm()
return render_to_response('login.html', {
'authenticationform': form,
}, context_instance=RequestContext(request))
def all_posts(request):
post_list = TextPost.objects.all().order_by('-score'))
paginator = Paginator(post_list, 100) # Show 100 contacts per page
registrationform = RegistrationForm(request.POST or None)
authenticationform = AuthenticationForm(request.POST or None)
page = request.GET.get('page')
try:
posts = paginator.page(page)
except PageNotAnInteger:
# If page is not an integer, deliver first page.
posts = paginator.page(1)
except EmptyPage:
# If page is out of range (e.g. 9999), deliver last page of results.
posts = paginator.page(paginator.num_pages)
return render(request, 'all_posts.html', {'posts': posts, 'registrationform': registrationform, 'authenticationform': authenticationform, 'user': request.user})
Edit 1: login.html login.html and register.html are identical modals, one with a login form and the other with the registration one.
{% load staticfiles %}
{% load crispy_forms_tags %}
<div class="modal" id="modal-login">
<div class="modal-dialog">
<div class="modal-content">
<form enctype="multipart/form-data" method="post" action="login/">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h3 class="modal-title">Log In</h3>
</div>
<div class="modal-body">
{% csrf_token %}
{{ authenticationform|crispy }}
</div>
<div class="modal-footer">
<input type='submit' class="btn btn-primary" value="Log In" />
</div>
</form>
</div>
</div>
</div>
Edit 2: register.html
{% load staticfiles %}
{% load crispy_forms_tags %}
<div class="modal" id="modal-register">
<div class="modal-dialog">
<div class="modal-content">
<form enctype="multipart/form-data" method="post" action="register/">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h3 class="modal-title">Register</h3>
</div>
<div class="modal-body">
{% csrf_token %}
{{ registrationform|crispy }}
</div>
<div class="modal-footer">
<input type='submit' class="btn btn-primary" value="Register" />
</div>
</form>
</div>
</div>
</div>
Alright, I was able to solve it.
The problem was apparently in my base.html where I had:
<li>{{ user.username }}</li>
and
<li>Log Out</li>
and I just changed the href="{% %}" tags to "profile/" and "logout/"
respectively.
I ran into this error while doing the Django tutorial.
The core problem was in my app's urls.py, in urlpatterns, with the second argument here:
path('', views.index, views.IndexView.as_view(), name='index'),
It should have been:
path('', views.IndexView.as_view(), name='index'),
Not sure how the extra views.index snuck in there but it was causing the problem. (as to why that exact error occurs - not going to dig too deep)
I believe this is preferable to deleting the {% url '...' id %} call and hard-coding its result as advised in the solution above.
I was previously using 0.6 version of django-registration.Now I upgraded to 0.8 ,and some issues are cropping up in my webapp
I have in the templates/registration folder ,these files needed for register(among others)
activation_complete.html
activation_email.txt
activation_email_subject.txt
registration_form.html
registration_complete.html
The registration_form.html is
{% extends "registration/auth_base.html" %}
{% block content %}{{block.super}}
<div class="subtitle short">Register</div>
<div id="registerform" class="box half">
<form action="/myapp/account/register/" method="POST">{% csrf_token %}
{% if form.non_field_errors %}
{{ form.non_field_errors }}
{% endif %}
<fieldset class="registerfields">
<p><label for="id_username">Username:</label> {{ form.username }}</p>
{% if form.username.errors %}<p class="error">{{ form.username.errors }}</p>{% endif %}
<p><label for="id_email">EmailAddress:</label>{{ form.email }}</p>
{% if form.email.errors %}<p class="error">{{ form.email.errors }}</p>{% endif %}
<p><label for="id_password1">Password:</label>{{ form.password1 }}</p>
{% if form.password1.errors %}<p class="error">{{ form.password1.errors }}</p>{% endif %}
<p><label for="id_password2">Password(again):</label>{{ form.password2 }}</p>
{% if form.password2.errors %}<p class="error">{{ form.password2.errors }}</p>{% endif %}
<p>
<input type="submit" value="Submit" />
</p>
</fieldset>
</form>
</div>
{% endblock %}
The template registration_complete.html is as below
{% extends "registration/auth_base.html" %}
{% block content %}{{block.super}}
<p id="message">Registration Complete! Check your email</p>
{% endblock %}
Also here is the auth_base.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Myapp{% block title %} {% endblock %}</title>
<LINK REL=StyleSheet HREF="{{MEDIA_URL}}css/myapp.css" TYPE="text/css" MEDIA="screen, print"/>
<link rel="shortcut icon" href="{{ MEDIA_URL }}img/myapp-icon.ico"/>
</head>
<body>
<div id="content">
{% block content %}
{% endblock %}
</div>
<div id="sidebar">
<h3> page info </h3>
{% block whatis %}
{% endblock %}
</div>
<div id="homelnk">
<img class="centerpage" src="{{ MEDIA_URL }}img/home.png">
</div>
</body>
</html>
But when I submit a new user details for registration,I am not getting this registration_complete page.I still get a registration form with blank fields
Still,the activation link is sent to the email , and I am able to login as the new user..Why is the registration_complete page not shown?This used to work in the older version of django-registration ..I couldn't find anything in the upgrade guide regarding the templates..
Any advice appreciated
I use this template for registration_form.html:
{% extends "base.html" %}
{% load i18n %}
{% block content %}
<form method="post" action=".">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="{% trans 'Submit' %}" />
</form>
{% endblock %}
You can find more of those here :
https://github.com/nathanborror/django-registration/tree/master/registration/templates/registration
I'm working on a project and we need to add a form to add an event. It lists the name, date, time, and address. I got the form to work but when I added the base, the form doesn't show up on the web page with the base loaded. I'm thinking it has something to do with my html file. Here is my html file.
{% extends "base.html" %}
{% block heading %}My Events{% endblock %}
{% block content3 %}
</h1><b><font size="5">Save Event</b></h1></font>
<form method="POST" action=".">{% csrf_token %}
{{form.as_p}}
<input type ="submit" value="Add Event"/>
</form>
{% endblock %}
views:
def add_event(request):
user = request.user
events = user.event_set.all()
if request.method == "POST":
form = EventForm(request.POST)
if form.is_valid():
event = Event.objects.create(
eventname = form.cleaned_data['eventname'],
eventdate = form.cleaned_data['eventdate'],
eventtime = form.cleaned_data['eventtime'],
address = form.cleaned_data['address'],
user = request.user
)
return HttpResponseRedirect('/')
else:
form = EventForm()
variables = RequestContext(request, {
'form': form
})
return render_to_response('add_event.html',variables)
base:
HTML (base.html)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>DelMarVa Happenings | {% block title %}{% endblock %}</title>
<link rel="stylesheet" href="/site_media/style.css" type="text/css" />
</head>
<body>
<div id="wrapper">
<div id="masthead">
<div id="logo">
<img src="/site_media/Delmarva.gif" width="100px" height="80px" />
</div>
<h1>DelMarVa Happenings</h1>
<br />
<h4>A listing of events in and around Delaware, Maryland, and Virginia</h4>
</div>
<div id="nav">
{% if user.is_authenticated %}
<h3>welcome, {{ user.username }}</h3>
{% else %}
<h3>welcome, guest</h3>
{% endif %}
<ul>
<li><a href="/">home<a/></li>
{% if user.is_authenticated %}
<li>add event</li>
<li>my events</li>
<li>my account</li>
<li>logout</li>
{% else %}
<li>login</li>
<li>register</li>
{% endif %}
</ul>
</div>
<div id="ads">
<img src="/site_media/ad.jpg" />
</div>
<div id="main">
<h2>{% block head %}{% endblock %}</h2>
{% block content %}{% endblock %}
</div>
</div>
</body>
</html>
Your base.html does not have a {% block content3 %} - rename the block name in base, or the extended template to match each other.
Make sure to leave space between form.as_p and the braces. As such, {{ form.as_p }}