Python Flask, displaying an input from one page on another - python

None of the other answers on this seem to solve my problem. I am trying to display a greeting that says "Welcome to the app [user]" when someone logs in. I am not sure how to get the greet page to display this message.
Here is my login function
#app.route("/login2", methods=["POST", "GET"])
def login():
if request.method == "POST":
session.permanent = True
user=request.form["nm"]
session["user"] = user
return render_template("greet.html")
else:
if "user" in session:
return redirect(url_for("greet"))
return render_template("login2.html")
Here is my login.html page
{% extends "base.html" %}
{% block title %}Log In Page{% endblock %}
{% block content %}
{% with messages = get_flashed_messages() %}
{% if messages %}
{% for msg in messages %}
<p>{{msg}}</p>
{% endfor %}
{% endif %}
{% endwith %}
<form action="#" method="post">
<p>Name: </p>
<p><input type="text", name="nm" /></p>
<p><input type="submit", value="submit" /></p>
</form>
{% endblock %}
And here is greet.html, which should display the message that I want.
{% extends "base.html" %}
{% block content %} <h1>Welcome</h1>
<p>Hi, Welcome to the app {{}} .</p>
{% endblock %}
I believe that I need to pass something into the {{}} on the greet.html page, but I do not know what to pass in here.

In your login route when the method is POST pass the user object to the template.
#app.route("/login2", methods=["POST", "GET"])
def login():
if request.method == "POST":
session.permanent = True
user=request.form["nm"]
session["user"] = user
return render_template("greet.html", user=user)
else:
if "user" in session:
return redirect(url_for("greet"))
return render_template("login2.html")
Now you can use it in the template
<p>Hi, Welcome to the app {{user.name}} .</p>

Related

Flask flashed messages not showing

I'm trying to flash messages in Flask using flash(), but the messages aren't appearing on the page. It isn't in the source code for the page either when looking at it with Dev Tools.
Here is the code that I have in my base.html It is outside of the blocks:
{% with messages = get_flashed_messages(with_categories=true) %}
<p>1</p>
{% if messages %}
<p>2</p>
{% for message, category in messages %}
<p>3</p>
{% if category == 'success' %}
<p>4</p>
<div class='message success'>
<p>{{ message }}</p>
</div>
{% elif category == 'error' %}
<div class='message error'>
<p>{{ message }}</p>
</div>
{% endif %}
{% endfor %}
{% endif %}
{% endwith %}
Python code(shortened to include relevant bits)
#app.route('/suggestion', methods=['GET', 'POST'])
def suggestion():
if request.method == 'POST':
...
content = f'Name: {name}\nEmail: {email}\nQuestion: {question}\nAnswer: {answer}\nType: {type}\nTopic: {topic}'
if sensible == 'Agreed' and accurate == 'Agreed':
email = Email()
sent = email.sendEmail(content)
if sent:
flash('Suggestion submitted successfully', category='success')
else:
flash('Error submitting suggestion. Please try again later',
category='error')
return redirect(url_for('suggest'))
Using the p tags to see where it's failing, I can tell that the {% if messages %} isn't working, but I don't know why.
I'm using flash('Message', category='success') to send the messages. I've looked at the Flask documentation and can't figure out what I'm doing wrong.
Please can someone help?
Have a look at this implementation
Routes.py
#auth.route("/login", methods=["GET", "POST"])
def login():
form = LoginForm()
if request.method == "POST":
if form.validate_on_submit():
user = User.query.filter_by(email=form.email.data).first()
if user is not None and user.confirm_password(form.password.data):
login_user(user)
flash("Login successful", "success")
return redirect(url_for("home.index"))
flash("Invalid email or password", "error")
return render_template("auth/login.html", form=form)
_message.html template
<div class="flash-message">
<div class="msg-wrapper">
{% with messages=get_flashed_messages(with_categories=true) %}
{% if messages %}
{% for category,message in messages %}
<p class="{{category}} message">{{message}}</p>
{% endfor %}
{% endif %}
{% endwith %}
</div>
</div>
Looping through the messages and categories in reverse

Django form only sending GET requests

I have this add page which uses a django form to get information which i am trying to store within "tasks" list and display in the todo html page.
i believe all my syntax is correct but it is not displaying the list of tasks when I submit the form.
on cmd it detects a GET request every time i submit the form, shouldnt it be saying post?
views:
from django.shortcuts import render
from django import forms
tasks = []
class newTaskForm(forms.Form):
task = forms.CharField(label="new task")
# Create your views here.
def index(request):
return render(request, "tasks/todo.html", {
"tasks": tasks
})
def add(request):
if request.method == "POST":
form = newTaskForm(request.POST)
if form.is_valid():
task = form.cleaned_data["task"]
tasks.append(task)
else:
return render(request, "tasks/add.html", {
"form": form
})
return render(request, "tasks/add.html", {
"form": newTaskForm
})
add:
{% extends "tasks/layout.html" %}
{% block body %}
<form action="{% url 'tasks:add' %}">
{% csrf_token %}
{{ form }}
<input type="submit">
</form>
Veiw list
{% endblock %}
todo:
{% extends "tasks/layout.html" %}
{% block body %}
<h1> To Do List</h1>
<ul>
{% for task in tasks %}
<li> {{ task }}</li>
{% endfor %}
</ul>
Add items
{% endblock %}
as #Iain Shelvington suggested, you need to put method="post" as
{% block body %}
<form method="post" action="{% url 'tasks:add' %}">
{% csrf_token %}
{{ form }}
<input type="submit">
</form>
Veiw list
{% endblock %}

Why doesn't me flask app redirect the user?

I'm creating a flask blog. After the registration form is completed, I want to redirect the user back to the home page and show the user a message.
The problem is that the user doesn't get redirected. It only flashes once.
Python code:
#app.route("/register", methods=['GET', 'POST'])
def register():
form = RegistrationForm()
if form.validate_on_submit():
flash(f'Account created for {form.username.data}!')
return redirect(url_for('home'))
return render_template('register.html', title='Register', form=form)
HTML code:
{% with messages = get_flashed_messages(with_categories=true) %}
{% if messages %}
{% for category, message in messages %}
<div class="alert alert-success">
{{ message }}
</div>
{% endfor %}
{% endif %}
{% endwith %}

Inputs are not showing in django form

My form inputs are not showing. It's just a button. i think homepage.html doesn't getting this form
Forms.py
class NameForm(forms.Form):
your_name = forms.CharField(label='Your name', max_length=100)
Views.py
def get_name(request):
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = NameForm(request.POST)
# check whether it's valid:
if form.is_valid():
# process the data in form.cleaned_data as required
# ...
# redirect to a new URL:
return HttpResponseRedirect('/')
# if a GET (or any other method) we'll create a blank form
else:
form = NameForm()
return render(request, 'mainApp/homepage.html', {'form': form})
homepage.html
{% extends "mainApp/wrapper.html" %}
{% block title %}Главная{% endblock %}
{% block content %}
<h1>Main page</h1>
{% include "mainApp/includes/somehtml.html" %}
<br>
<form action="/account/username/" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit" />
</form>
<br>
{% endblock %}
It shoes only "Submit" button. How can I fix it?
Please change
{{form}}
to {{form.as_p}}
Views.py
from app_name.forms import * # Change app_name with your app name
def get_name(request):
temp_context = {} # Check here
if request.method == 'POST':
acc_form = NameForm(request.POST) # Check here
temp_context["acc_form"] = acc_form # Check here
if acc_form.is_valid(): # Check here
return HttpResponseRedirect('/')
else:
temp_context[“acc_form”] = NameForm() # Check here
return render(request, 'mainApp/homepage.html', temp_context) # Check here
homepage.html
{% extends "mainApp/wrapper.html" %}
{% block title %}Главная{% endblock %}
{% block content %}
<h1>Main page</h1>
{% include "mainApp/includes/somehtml.html" %}
<br>
<form action="/account/username/" method="post">
{% csrf_token %}
{{ acc_form }} # Check here;
# you can also try {{ acc_form.as_table }} or {{ acc_form.as_p }} if there any issue
<input type="submit" value="Submit" />
</form>
<br>
{% endblock %}

Django - template - User in never authenticated

User is never authenticated even when the user is logged in. Right sidebar always displays Not Loggedin.Do i need to return something to base.html? And how will i do that ? do i need a new function in views.py ? but there is no url for base.hthl. What i am missing?Please be specific i am in web dev. PS: i also tried if request.user.is_loggedin and some other
base.html
<div id="sidebar">
{% block sidebar %}
<ul>
<li>Notes</li>
</ul>
{% endblock %}
</div>
<div id="rightsidebar">
{% block rightsidebar %}
{% if request.user.is_authenticated %}
Loggedin
{% else %}
Not Loggedin
{% endif %}
{% endblock %}
</div>
<div id="content">
{% block content %}This is the content area{% endblock %}
</div>
views.py
def auth_view(request):
username = request.POST.get('username','')
password = request.POST.get('password','')
user = auth.authenticate(username = username, password = password)
if user is not None:
if user.is_active:
auth.login(request,user)
return HttpResponseRedirect('/accounts/loggedin')
else:
return HttpResponseRedirect('/accounts/auth_view')
else:
return HttpResponseRedirect('/accounts/invalid')
To be able to use
{% if request.user.is_authenticated %}
You need to do the following in you view:
from django.template import RequestContext
def view(request):
my_data_dictionary = {}
# code here
return render_to_response('template.html',
my_data_dictionary,
context_instance=RequestContext(request))
def view(request):
# code here
return render_to_response('template.html', {},
context_instance=RequestContext(request))
Because you need to use context processors.

Categories

Resources