Flask Form fields not refreshing and flash messages not working - python

I've looked everywhere and the examples aren't working for me code below:
I'm facing 2 problems with my code I'd be happy with a simple fix for each and go into an the advanced problem I'mm trying to solve
Problem 1: When I submit the form when the page refreshes the form fields still contain the information and are not blank. (Advanced problem) I'd like it to lock the fields and show a success message under the form like the original bootstrap form functioned this is a startbootstrap template i'm using the free portfolio I believe for the framework
Problem 2: I can not retrieve the successful flashed message I can only display the flashed message if an error occurs and the messages only display when I go to validate the form the success message DOES NOT display no matter what even after the form validates, (advanced) I'd like error messages to appear when the focus leaves the field like the original startbootstrap form
main.py
from flask import Flask, render_template, redirect, url_for, flash, request, abort
from flask_bootstrap import Bootstrap
from forms import ContactForm
from datetime import date
app = Flask(__name__)
app.config['SECRET_KEY'] = 'SomethingSecret'
Bootstrap(app)
current_year = date.today().year
#app.route('/', methods=['GET', 'POST'])
def home_page():
form = ContactForm()
if request.method == 'POST' and form.validate_on_submit():
flash(u'Successfully sent your message')
return redirect(url_for('home_page', form=form))
return render_template('index.html', year=current_year, form=form)
if __name__ == "__main__":
app.run(debug=True)
Here is my layout.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
<meta name="description" content="" />
<meta name="author" content="" />
<title>Online Portfolio</title>
<!-- Favicon-->
<link rel="icon" type="image/x-icon" href="{{url_for('static', filename='assets/favicon.ico')}}" />
<!-- Font Awesome icons (free version)-->
<script src="https://use.fontawesome.com/releases/v5.15.4/js/all.js" crossorigin="anonymous"></script>
<!-- Google fonts-->
<link href="https://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css" />
<link href="https://fonts.googleapis.com/css?family=Lato:400,700,400italic,700italic" rel="stylesheet" type="text/css" />
<!-- Core theme CSS (includes Bootstrap)-->
<link href="{{ url_for('static', filename='css/styles.css') }}" rel="stylesheet">
</head>
<body id="page-top">
<!-- Navigation-->
<nav class="navbar navbar-expand-lg bg-secondary text-uppercase fixed-top" id="mainNav">
<div class="container">
<a class="navbar-brand" href="#page-top">I Will Develop Your Dreams Online</a>
<button class="navbar-toggler text-uppercase font-weight-bold bg-primary text-white rounded" type="button" data-bs-toggle="collapse" data-bs-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">
Menu
<i class="fas fa-bars"></i>
</button>
<div class="collapse navbar-collapse" id="navbarResponsive">
<ul class="navbar-nav ms-auto">
<li class="nav-item mx-0 mx-lg-1"><a class="nav-link py-3 px-0 px-lg-3 rounded" href="#portfolio">Portfolio</a></li>
<li class="nav-item mx-0 mx-lg-1"><a class="nav-link py-3 px-0 px-lg-3 rounded" href="#about">About</a></li>
<li class="nav-item mx-0 mx-lg-1"><a class="nav-link py-3 px-0 px-lg-3 rounded" href="#contact">Contact</a></li>
</ul>
</div>
</div>
</nav>
{% with messages=get_flashed_messages() %}
{% for category, message in messages %}
<div class='alert text-center alert-dismissible fade show m-auto'>
{{ message }}
</div>
{% endfor %}
{% endwith %}
{% block body %}{% endblock %}
index.html
{% block body %}
<form id="contactForm" method="POST" data-sb-form-api-token="API_TOKEN">
<!-- Name input-->
<div class="form-floating mb-3">
{{ form.name(class_='form-control test', type='text', placeholder='Enter your name...') }}
{% with messages = get_flashed_messages() %}
{% if messages %}
<div>
{% for message in messages %}
{{ message }}
{% endfor %}
</div>
{% endif %}
{% endwith %}
<label for="name">Full name</label>
</div>
{% endblock %}

Related

Why is my create button not redirecting to the form? (For django)

I am new to Django and am trying to make an online journal, and the server runs fine, but when I press the create button, it does not redirect to the form even though a POST request is being sent. screenshot of the create page. I'm not sure why.
This is the code:
views.py:
from django.shortcuts import render, redirect, get_object_or_404
from ejournal.models import Journal
from ejournal.forms import JournalForm
def make_entry(request):
if request.method == "POST":
entry = JournalForm(request.POST, request.FILES)
if entry.is_valid():
entry.save()
return redirect('list_journals')
else:
entry = JournalForm()
context = {
'entry':entry
}
return render(request, 'ejournal/create.html', context)
def delete_entry(request, id):
entry = get_object_or_404(Journal, id=id)
if request.method == "POST":
entry.delete()
return redirect('list_journals')
context = {
'object':object
}
return render(request, 'journal/delete.html',context)
def list_journals(request):
entries = Journal.objects.all()
context = {
'entries': entries
}
return render(request, 'ejournal/list_journals.html',context)
def journal_detail(request, id):
journal = Journal.objects.get(id=id)
context = {
'journal':journal
}
return render(request, 'journal/journal_detail.html', context)
forms.py
from ejournal.models import Journal
from django.forms import ModelForm
class JournalForm(ModelForm):
class Meta:
model = Journal
fields = ['name','title','text','image']
models.py
from django.db import models
class Journal(models.Model):
name = models.CharField(max_length=20)
title = models.CharField(max_length=50)
text = models.TextField(max_length=1000)
date = models.DateField(auto_now_add=True)
image = models.FileField(upload_to='')
archived = models.BooleanField(default=False)
def __str__(self):
return self.name
base.html
{% load static %}<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>My Online Journal</title>
<!-- Bootstrap core CSS -->
<link href="{% static 'css/bootstrap.min.css' %}" rel="stylesheet">
<link href="{% static 'css/style.css' %}" rel="stylesheet">
</head>
<body>
<!-- Navigation -->
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<div class="container">
<a class="navbar-brand" href="{% url 'list_journals' %}">Smart Journal</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarResponsive">
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<a class="btn btn-outline-info btn-md" href="{% url 'list_journals' %}">LIST ALL</a>
</li>
</ul>
</div>
<div class="collapse navbar-collapse" id="navbarResponsive">
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<a class="btn btn-outline-info btn-md" href="{% url 'make_entry' %}">+ New Journal Entry </a>
</li>
</ul>
</div>
</div>
</nav>
<!-- Page Content -->
<div class="container" id="app">
{% block content %}
{% endblock %}
</div>
<!-- /.container -->
<!-- Bootstrap core JavaScript -->
<script src="{% static 'js/jquery.min.js' %}"></script>
<script src="{% static 'js/bootstrap.min.js' %}"></script>
</body>
</html>
create.html
{% extends 'ejournal/base.html' %}
{% block content %}
<div class="center_journal">
<h1> Create Journal Entry </h1>
</div>
<div class="center_journal">
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
<p>{{ form.as_p }}</p>
<button class="btn btn-primary" type="submit">CREATE</button>
</form>
</div>
{% endblock content %}
urls.py
from django.urls import path
from ejournal.views import make_entry, delete_entry, list_journals, journal_detail
urlpatterns = [
path('create', make_entry, name="make_entry"),
path('list_journals', list_journals, name="list_journals"),
path('delete/<int:id>/', delete_entry, name="delete_entry"),
path('journal_detail/<int:id>',journal_detail, name="journal_detail"),
]
You pass the form as the variable entry to your template ejournal/create.html.
Inside this template you use {{ form.as_p }}, but form is undefined. You need to use the variable entry because thats where the form is assigned to.
So your create.html becomes this:
{% extends 'ejournal/base.html' %}
{% block content %}
<div class="center_journal">
<h1> Create Journal Entry </h1>
</div>
<div class="center_journal">
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
<p>{{ entry.as_p }}</p>
<button class="btn btn-primary" type="submit">CREATE</button>
</form>
</div>
{% endblock content %}
You're checking if your form is valid by using entry.is_valid(), but your form will always be invalid because you didn't pass the correct form in your template, as described above.
Check with form's action='' attribute like this...
<form method="POST" action="{% url 'make_entry' %}" enctype="multipart/form-data">
{% csrf_token %}
<p>{{ form.as_p }}</p>
<button class="btn btn-primary" type="submit">CREATE</button>
</form>

Flask Jinja2 not rendering bootstrap carousel

I'm wanting to render bootstrap carousel and other nested html elements. im newer to Jinja2 and didn't see anything on the internet talking about this particular issue.
here is my python
#app.route("/")
def index():
r = requests.get(os.environ['AWS_Product_URL'])
prods = list(json.loads(r.text))
return render_template("index.html", my_products=prods)
this works
{% for key in my_products %}
<p><strong>{{ key["name"] }}</strong><span>{{ key["price"] }}</span></p>
{% endfor %}
but this doesn't
{% for key in my_products %}
<div class="carousel-item">
<p><strong>{{ key["name"] }}</strong><span>{{ key["price"] }}</span></p>
</div>
{% endfor %}
I took an existing template and trying to make this dynamic. the class exists. I'm confused why Jinja2 is having trouble with a nested item in html.
Why??
You're probably just missing to add class active to the carousel item
bootstrap carousel items requires at least one active element, all the others will be hidden.
so try out adding something like
{% for key in my_products %}
<div class="carousel-item {% if loop.index == 1 %}active{% endif %}">
<p><strong>{{ key["name"] }}</strong><span>{{ key["price"] }}</span></p>
</div>
{% endfor %}
Just in case, here's template that I've tested with and it should be working fine assuming my_products is not empty.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
</head>
<body>
<div class="container">
<div class="row">
<div class="col">
<div id="carouselExampleControls" class="carousel slide" data-bs-ride="carousel">
<div class="carousel-inner text-center">
{% for key in my_products %}
<div class="carousel-item {% if loop.index == 1 %}active{% endif %}">
<p><strong>{{ key["name"] }}</strong><span>{{ key["price"] }}</span></p>
</div>
{% endfor %}
</div>
<button class="carousel-control-prev bg-dark" type="button" data-bs-target="#carouselExampleControls" data-bs-slide="prev">
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="visually-hidden">Previous</span>
</button>
<button class="carousel-control-next bg-dark" type="button" data-bs-target="#carouselExampleControls" data-bs-slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="visually-hidden">Next</span>
</button>
</div>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
</body>
</html>

Hi, I have a problem with a django app. I want do make personalized pages for users with this url: url/user/id. But something doesn't work

I'm quite new in the programming world and that's my firs real project. Usually I solve my problems just sitting and thinking till my brain burns. But this time I'm really stacked. Maybe is easy but I really didn't find solutions
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('profilo/<int:my_id>/', views.profilo, name='profilo')
]
views.py
def profilo(request, my_id):
users = User.objects.get(id=my_id)
contex = {
"user": users
}
return render(request, 'profilo/profilo.html', contex)
base.html
{% load static %}
<html>
<head>
<title>Django Boyz blog</title>
<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 href='//fonts.googleapis.com/css?family=Lobster&subset=latin,latin-ext' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="{% static 'css/blog.css' %}">
</head>
<body>
<div class="page-header">
{% if user.is_authenticated %}
<span class="glyphicon glyphicon-plus"></span>
<p class="top-menu">Ciao {{ user.username }} <small>(Log out)</small></p>
<span class="glyphicon glyphicon-user"></span>
{% if user.is_superuser %}
<span class="glyphicon glyphicon-inbox"></span>
{% endif %}
{% else %}
<span class="glyphicon glyphicon-lock"></span>
{% endif %}
<h1>Django Boyz Blog</h1>
</div>
<div class="content container">
<div class="row">
<div class="col-md-8">
{% block content %}
{% endblock %}
</div>
</div>
</div>
</body>
</html>
The error is this: NoReverseMatch at /
Reverse for 'profilo' with arguments '('',)' not found. 1 pattern(s) tried: ['profilo/(?P<my_id>[0-9]+)/$']
Thanks
In this line:
<span class="glyphicon glyphicon-user"></span>
The u should be small in User.id:
<span class="glyphicon glyphicon-user"></span>

How do I reset my HTML form with Python Flask?

I'm building a very simple web app (using Python Flask) that will display some images to the user and get some response from the user.
Below is my code (ignoring the other parts of my code not related to this question):
#app.route('/gallery',methods=['GET','POST'])
def get_gallery():
image_names = os.listdir(r'C:\Users\xxxvn\images')
b=[str(i)+"|"+str(request.form.get(i)) for i in image_names]
print (b)
return render_template("gallery.html", image_names=image_names)
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"
integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-lg-12">
<h1 class="page-header">Gallery</h1>
</div>
{{image_names}}
<hr>
<form method="POST">
{% for image_name in image_names %}
<div class="col-lg-3 col-md-4 col-xs-6 thumb">
<img class="img-responsive" src=" {{url_for('send_image', filename=image_name)}}">
<input type="radio" name={{image_name}} id="radio1" value="YES" />YES<br>
<input type="radio" name={{image_name}} id="radio2" value="NO"/>NO<br>
<hr>
</div>
{% endfor %}
<input type="submit" name="submit_button" value="SUBMIT"/>
</form>
</div>
</div>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"
integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS"
crossorigin="anonymous"></script>
</body>
</html>
My current app
Question:
I want to reset the form as soon as the user hits submit and capture the output in list "B". The form should not be resubmitted with old values if the user hits refresh.
Do a request method check and put in your capture login in it.
from flask import request
#app.route('/gallery',methods=['GET','POST'])
def get_gallery():
image_names = os.listdir(r'C:\Users\xxxvn\images')
if request.method == "POST":
b=[str(i)+"|"+str(request.form.get(i)) for i in image_names]
print (b)
return render_template("gallery.html", image_names=image_names)

Sign up django with cbv and AbstractUser model image error

i tried using class based views for signup but when i try to add images to the form fields, i keep getting this field is required the problem is with the image file
this is the forms.py file
`
from django import forms
from .models import User
class USerForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput())
class Meta:
model = User
fields = ['username', 'email', 'password', 'company', 'description', 'logo']
`
and the views.py file
from django.shortcuts import render, redirect
from django.views.generic import View, TemplateView
from .forms import USerForm
from django.contrib.auth import authenticate, login, logout
from django.http import HttpResponseRedirect
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.views.generic.edit import UpdateView
# Create your views here.
#login_required(login_url="/jembe/login/")
def index(request):
return render(request, 'base.html')
class SignUp(View):
form_class = USerForm
template_name = 'signup.html'
def get(self, request):
form = self.form_class(None)
return render(request, self.template_name, {'form': form})
def post(self, request):
form = self.form_class(request.POST, request.FILES)
if form.is_valid():
user = form.save(commit=False)
username = form.cleaned_data['username']
password = form.cleaned_data['password']
user.set_password(password)
user.save()
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
return redirect('invoice:index')
return render(request, self.template_name, {'form': form})
class LogoutView(View):
def get(self, request):
logout(request)
return HttpResponseRedirect('/jembe/login')
class AboutView(TemplateView):
template_name = "about.html"
models.py file
`from django.db import models
from django.contrib.auth.models import AbstractUser
# Create your models here.
class User(AbstractUser):
company = models.CharField(max_length=300)
description = models.TextField(blank=True)
website = models.URLField()
logo = models.ImageField(upload_to='../media/')
`
register.html
{% load staticfiles %}
{% load i18n widget_tweaks %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<link rel="shortcut icon" href="img/favicon_1.ico">
<title>{% block title %} Signup {% endblock %} |Jims</title>
""
<!-- Bootstrap core CSS -->
<link href="{% static 'login/css/bootstrap.min.css' %}" rel="stylesheet">
<link href="{% static 'login/css/bootstrap-reset.css' %}" rel="stylesheet">
<!--Animation css-->
<link href="{% static 'login/css/animate.css' %}" rel="stylesheet">
<!--Icon-fonts css-->
<link href="{% static 'login/assets/font-awesome/css/font-awesome.css' %}" rel="stylesheet" />
<link href="{% static 'login/assets/ionicon/css/ionicons.min.css' %}" rel="stylesheet" />
<!--Morris Chart CSS -->
<link rel="stylesheet" href="{% static 'login/assets/morris/morris.css">
<!-- Custom styles for this template -->
<link href="{% static 'login/css/style.css' %}" rel="stylesheet">
<link href="{% static 'login/css/helper.css' %}" rel="stylesheet">
<link href="{% static 'css/style.css' %}" rel="stylesheet">
<link href="{% static 'css/bootstrap.css' %}" rel="stylesheet">
<link href="{% static 'css/main.css' %}" rel="stylesheet">
<link rel='stylesheet prefetch' href='http://fonts.googleapis.com/css?family=Roboto:400,100,300,500,700,900|RobotoDraft:400,100,300,500,700,900'>
<link rel='stylesheet prefetch' href='http://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css'>
<!-- HTML5 shim and Respond.js IE8 support of HTML5 tooltipss and media queries -->
<!--[if lt IE 9]>
<script src="js/html5shiv.js"></script>
<script src="js/respond.min.js"></script>
<![endif]-->
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','../../../www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-62751496-1', 'auto');
ga('send', 'pageview');
</script>
</head>
<body>
<div class="navbar navbar-default navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href=""><div class="logo">
<a href="" class="logo-expanded">
<i class="ion-compose"></i>
<span class="nav-label">Jigs</span>
</a>
</div></a>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav navbar-right">
<li><strong>About</strong></li>
<li><strong>Login</strong></li>
<li><strong>Register</strong></li>
</ul>
</div><!--/.nav-collapse -->
</div>
</div>
<div class="wrapper-page animated fadeInDown">
<div class="panel panel-color panel-primary">
<div class="panel-heading">
<h3 class="text-center m-t-10"> Create a new Account </h3>
</div>
{# error logic #}
{% if form.errors %}
{% for field in form %}
{% for error in field.errors %}
<div class="alert alert-danger">
<strong>{{ error | escape }}</strong>
</div>
{% endfor %}
{% for error in form.non_field_errors %}
<div class="alert alert-danger">
<strong> {{ error | escape }}</strong>
</div>
{% endfor %}
{% endfor %}
{% endif %}
{# end error logic #}
<form class="form-horizontal m-t-40" action="" method="post">
{% csrf_token %}
{% for field in form %}
<div class="form-group">
<div class="col-xs-12">
<label> {{ field.label }} </label>
{{ field|attr:"class:form-control" }}
</div>
</div>
{% endfor %}
<div class="form-group ">
<div class="col-xs-12">
<label class="cr-styled">
<input type="checkbox" checked>
<i class="fa"></i>
I accept <strong>Terms and Conditions</strong>
</label>
</div>
</div>
<div class="form-group text-right">
<div class="col-xs-12">
<button class="btn btn-purple w-md" type="submit">Register</button>
</div>
</div>
<div class="form-group m-t-30">
<div class="col-sm-12 text-center">
Already have account?
</div>
</div>
</form>
</div>
</div>
<!-- js placed at the end of the document so the pages load faster -->
<script src="{% static 'login/js/jquery.js' %}"></script>
<script src="{% static 'login/js/bootstrap.min.js' %}"></script>
<script src="{% static 'login/js/pace.min.js' %}"></script>
<script src="{% static 'login/js/wow.min.js' %}"></script>
<script src="{% static 'login/js/jquery.nicescroll.js' %}" type="text/javascript"></script>
<!--common script for all pages-->
<script src="{% static 'login/js/jquery.app.js' %}"></script>
<hr/>
<center><h3 class="text text-success"> Jembe™ © 2017</h3></center>
</body>
</html>
You have forgotten to set enctype in your form. It should be:
<form class="form-horizontal m-t-40" action="" method="post" enctype="multipart/form-data">
See the Django docs on file uploads for more info.

Categories