Display username in base.html in Flask - python

I want to add current username in base.html, but I can't understand how make it.
I have got username, which takes from MySQL database
#app/routes
#app.route('/auth', methods=['GET', 'POST'])
def auth():
msg = ''
if request.method == 'POST' and 'username' in request.form and 'password' in request.form:
username = request.form['username']
hash = request.form['password']
salt = b'$2b$12$Mw/92Q0HkYKTR.0.ghNQs.'
password = bytes(hash, encoding='utf-8')
hash_1 = bcrypt.hashpw(password,salt)
cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
cursor.execute('SELECT * FROM user WHERE username = % s AND password = % s', (username, hash_1,))
account = cursor.fetchone()
if account:
session['loggedin'] = True
session['id'] = account['id']
session['username'] = account['username']
msg = 'Logged in successfully !'
return render_template('index.html', msg=msg)
else:
msg = 'Неверное имя пользователя/пароль !'
return render_template('auth.html', msg=msg)
How can I take the username field and get it to the base.html, when user is Loggined in? I tryed to make it with using documentation, but it doesn`t work.
#base.html
{% if g.username %}
<li><span>{{ g.user['username'] }}</span>
{% else %}
<a class="p-2 text-dark" href="/auth">Авторизация</a>
{% endif %}

I make it
{% if session.loggedin %}
<a class="p-2 text-dark" href="/auth">Привет,{{session.username}} </a>
{% else %}
<a class="p-2 text-dark" href="/auth">Авторизация</a>

Related

variable is undefined flask mysql

I need to greet user on the page. F.ex: Hello {{ name }}, but I get the error UnboundLocalError: local variable 'account' referenced before assignment. What is the problem in the code below?
python:
app = Flask(__name__)
mysql = MySQL(app)
#app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
name = request.form['name']
email = request.form['email']
cur = mysql.connection.cursor()
cur.execute('INSERT INTO users(name, email) VALUES(%s, %s)', (name, email))
mysql.connection.commit()
cur.close()
return redirect('profile')
return render_template('index.html')
#app.route('/profile', methods=['GET'])
def profile():
if request.method == 'POST':
name = request.form['name']
email = request.form['email']
cur = mysql.connection.cursor()
cur.execute('SELECT * FROM users')
account = cur.fetchone()
return render_template('profile.html', account=account)
index.html:
<form action="" method="POST">
<span style="color: #fff;">Firstname:</span><input type="text" name="name" placeholder="Type your firstname"><br><br>
<input type="submit" name="submit" value="submit">
</form>
profile.html
<h4 style="color: #fff;">Your firstname: is {{ account['name'] }}</h4>
<h4 style="color: #fff;">Your email: is {{ account['email'] }}</h4>
I can connect to database and fetch users data, but on the profile.html page I get the error
How to solve it? Please help.
You haven't passed the account to the template.
Instead of ,
return render_template('profile.html')
you need to write as,
return render_template('profile.html', account=account)
EDIT:
#app.route('/profile', methods=['GET','POST'])
def profile():
if request.method == 'POST':
name = request.form['name']
email = request.form['email']
cur = mysql.connection.cursor()
cur.execute('SELECT * FROM users')
account = cur.fetchone()
return render_template('profile.html', account=account)
Or if you wanted the profile to be a get request you can do this
#app.route('/profile', methods=['GET','POST'])
def profile():
if request.method == 'POST':
name = request.form['name']
email = request.form['email']
cur = mysql.connection.cursor()
cur.execute('SELECT * FROM users')
account = cur.fetchone()
return render_template('profile.html', account=account)

Django Forms: Cannot show Validation Error

I have a Django Form where I allow the user to submit a value only if his password matches a predefined password set by me : Pass_matcher
Validation works fine, such that if passwords match, value is entered and stored and if not, nothing happens.
However I want that if passwords do not match, I show a simple custom warning message. I looked at other SO questions such as here and here, but I can't seem to get it right.
Note: If the user enters the correct password I do not want to redirect to another page.
forms.py
from django import forms
class TactForm(forms.Form):
password = forms.CharField(widget=forms.PasswordInput(
attrs = {
'class' : 'form-control mb-2 mr-sm-2 mb-sm-0',
'placeholder' : 'Enter Password:',
'id' : 'inlineFormInput',
'required' : 'true'
}
), required = True, label='Tact Password', max_length=100)
tacttime = forms.CharField(widget=forms.TextInput(
attrs = {
'class': 'form-control mb-2 mr-sm-2 mb-sm-0',
'placeholder': 'Enter Tact Time:',
'id' : 'inlineFormInput2'
}
),label='Tact Time', max_length=100)
def clean(self):
cleaned_data = super(TactForm,self).clean()
password = cleaned_data.get('password')
current_tact = cleaned_data.get('tacttime')
if password != 'Pass_matcher':
print('incorrect') #this prints to console if incorrect
raise forms.ValidationError('Incorrect Password') # this does not work
else:
print('correct') #this prints to console if correct
return cleaned_data
views.py
def details(request):
form = TactForm(request.POST or None)
if request.method == 'POST':
form = TactForm(request.POST)
if form.is_valid():
print('here1')
current_tact = form.cleaned_data['tacttime']
password = form.cleaned_data['password']
else:
form = TactForm()
return render(request, 'linedetails/index.html',{'form':form})
template
<div class="user_in" style="text-align:center;">
<form class="form-inline" method="POST" action="{% u$
{% csrf_token %}
{{ form.password }}
{{ form.tacttime }}
<br>
<button type="submit" class="btn btn-outline>
</form>
</div>
The below code is experimental
{% if form.errors %}
{% for field in form %}
{% for error in field.errors %}
<div class="alert alert-danger">
<strong>{{ error|escape }}</strong>
</div>
{% endfor %}
{% endfor %}
{% for error in form.non_field_errors %}
<div class="alert alert-danger">
<strong>{{ error|escape }}</strong>
</div>
{% endfor %}
{% endif %}
I cannot understand why the raise forms.ValidationError('Incorrect Password')
is not shown if the statement above it is correctly printed to terminal.
I am thinking that I have something missing in else statement of the views.py script.
Thanks for any suggestions.
You redefined form instance if form is not valid. just remove else block to fix it:
def details(request):
form = TactForm(request.POST or None)
if request.method == 'POST':
form = TactForm(request.POST)
if form.is_valid():
print('here1')
current_tact = form.cleaned_data['tacttime']
password = form.cleaned_data['password']
return render(request, 'linedetails/index.html',{'form':form})
Also you actually dont need if request.method == 'POST' validation since form will be populated with post data automatically here form = TactForm(request.POST or None). So you can simply rewrite your view to this:
def details(request):
form = TactForm(request.POST or None)
if form.is_valid():
print('here1')
current_tact = form.cleaned_data['tacttime']
password = form.cleaned_data['password']
return render(request, 'linedetails/index.html',{'form':form})

How can I transmit session in Django?

login.html
`<h2>Login</h2>
<form method="post" action="">
{% csrf_token %}
{{ form.as_p }}
</form>
<input type="submit" value="login" />`
loggedin.html
`<h2>login success</h2>`
views.py
`def signin(request):
if request.method == "POST":
form = LoginForm(request.POST) #form = email, password
email_input = str(request.POST['email'])
password_input = str(request.POST['password'])
user_Qset = Profile.objects.filter(email = email_input)
if user_Qset is not None:
password_saved = str(user_Qset.values('password')[0]['password'])
if password_input == password_saved:
response = render(request, 'registration/login.html',)
request.session.modified = True
request.session['name'] = user_Qset.values('name')[0]['name']
request.session['email'] = user_Qset.values('email')[0]['email']
request.session['password'] = user_Qset.values('password')[0]['password']
return response
def loggedin(request):
if request.session.has_key('name'):
return HttpResponse("transmission success")
else:
return HttpResponse("transmission failed")`
I have a result 'transmission failed'. How can I transmit sessions I added?
When I push the login button, page url and templates should be changed and session be transmitted
When user log in, I want give user session keys(name, email, password)
I want to check session keys I gave is maintained well in another page

400 Bad Request: KeyError: 'username'

When testing this code i get the error "400 Bad Request: KeyError: 'username'" and i cant figure out why
Here is the code, i am using flask to do this
#app.route('/')
def index():
if 'username' in session:
username = session['username']
return 'Logged in as ' + username + '<br>' + \
"<b><a href = '/logout'>click here to log out</a></b>"
return "You are not logged in <br><a href = '/login'></b>" + \
"click here to log in</b></a>"
#app.route('/login', methods = ['GET', 'POST'])
def login():
if request.method == 'POST':
session['username'] = request.form['username']
return redirect(url_for('index'))
return '''
<form action = "" method = "post">
<p><input type = text name = username/></p>
<p><input type = submit value = Login /></p>
</form>
'''
#app.route('/logout')
def logout():
#remove the session from username if it is there
session.pop('username', None)
return redirect(url_for('index'))
You're getting an error because there's no key username, most likely in the request.form object inside the if request.method == 'POST' block. This may be because of the way you're creating the form in HTML. You should put quotes around the field attributes, like:
<form action="" method="post">
<p><input type="text" name="username" /></p>
<p><input type="submit" value="Login"/></p>
</form>

django 1.10 render template html class

After a user fills out a form on my site, I user render(request, html, context). I'd like to return the user to the same part of the page after they register. I am not using any front end frameworks (like angular - thats my next project). How would I go about doing this?
views.py:
def homepage(request):
countries = Country.objects.count()
cities = City.objects.count()
start_trip_date = date(xxxx, x, x)
today = date.today()
total_days = today - start_trip_date
queryset_list = Post.objects.active()[:6]
query = request.GET.get("q")
if query:
queryset_list = queryset_list.filter(
Q(title__icontains=query) |
Q(content__icontains=query) |
Q(user__first_name__icontains=query) |
Q(user__last_name__icontains=query)
).distinct()
contact_form = EmailUpdatesForm(request.POST or None)
if contact_form.is_valid():
contact = contact_form.save(commit=False)
contact.email = request.POST['email']
contact.first_name = request.POST['first_name']
contact.save()
profile_data = {
'email': contact.email,
'first_name': contact.first_name,
}
plaintext = get_template('email/frontpage_registered_email/email_text.txt')
htmly = get_template('email/frontpage_registered_email/email_template.html')
text_content = plaintext.render(profile_data)
html_content = htmly.render(profile_data)
subject = "{0}, thank you for registering with xx!".format(contact.first_name)
from_email = 'xx#gmail.com'
to_email = contact.email
msg = EmailMultiAlternatives(subject, text_content, from_email, [to_email])
msg.attach_alternative(html_content, "text/html")
msg.send()
return render(request, "homepage/homepage.html", {})
else:
print contact_form.errors,
context = {
'object_list': queryset_list,
'countries': countries,
'cities': cities,
'days_traveling': total_days.days,
'contact_form': contact_form,
}
return render(request, "homepage/homepage.html", context)
and a made up html to show what I mean:
<body>
<div class="first">content</div>
<div class="second">
<form id="contact_form" method="POST" action="." enctype="multipart/form-data" novalidate>
<fieldset>
{% csrf_toke %}
{{ contact_form|crispy }}
<input class="btn..." type="submit" name="submit" value="Register" />
</fieldset>
</form>
</div>
</body>
In the above I want to return the user to the div class="second".
Thanks you.
To do this, you need to differentiate the default GET request to access the page and the POST of the form.
E.g. You could do:
contact_form = EmailUpdatesForm()
if request.method == 'POST':
contact_form = EmailUpdatesForm(request.POST)
if contact_form.is_valid():
contact = contact_form.save(commit=False)
contact.email = request.POST['email']
....
....
form_submit = True
and pass form_submit in the context.
Then, in HTML:
{% if form_submit %}
<div class="second"></div>
{% else %}
<div class="first"></div>
{% endif %}

Categories

Resources