I'm using different forms (POST and GET) in my Django web application and Bootstrap modal to do that.
In my template, user can choose some documents, submit the list of documents which is picked up to a Django form (CustomerForm) in my modal. This CustomerForm lets to send an email with user informations previously filled.
My CustomerForm looks like this :
class CustomerForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(CustomerForm, self).__init__(*args, **kwargs)
self.fields['country'].empty_label = _('Select a country')
self.fields['country'].queryset = self.fields['country'].queryset.order_by('name')
self.fields['email'].required = True
self.fields['first_name'].required = True
self.fields['last_name'].required = True
self.fields['country'].required = True
self.fields['institution'].required = False
class Meta:
model = Customer
fields = ['email', 'first_name', 'last_name', 'country', 'institution']
widgets = {
'email': forms.TextInput(attrs={'placeholder': _('name#example.com')}),
'first_name': forms.TextInput(attrs={'placeholder': _('First Name')}),
'last_name': forms.TextInput(attrs={'placeholder': _('Last Name')}),
'institution': forms.TextInput(attrs={'placeholder': _('Agency, company, academic or other affiliation')}),
}
I have views.py file :
class HomeView(CreateView, FormView):
""" Render the home page """
template_name = 'index.html'
form_class = CustomerForm
def get_context_data(self, **kwargs):
# display some things
# ...
if "DocumentSelected" in self.request.GET:
checkbox_list = self.request.GET.getlist('DocumentChoice')
document = Document.objects.filter(id__in=checkbox_list)
kwargs['selected_document'] = document
return super(HomeView, self).get_context_data(**kwargs)
def form_valid(self, form):
email = form.cleaned_data['email']
country = form.cleaned_data['country']
for checkbox in self.request.GET.getlist('DocumentChoice'):
document = Document.objects.get(id=checkbox)
token = self.gen_token(email)
now = timezone.now()
expiration = now + settings.DOWNLOAD_VALIDITY
Download.objects.create(email=email, country=country, doc_id=checkbox, token=token,
expiration_date=expiration)
self.send_email(email, document.upload, document.publication.title, token)
return super(HomeView, self).form_valid(form)
And finally in my HTML template you can find something which looks like this :
<form method="GET" action="">
<!-- Table with checkboxes - User has to check wanted objects -->
<div class="row">
<div class="col-md-offset-3 col-md-4">
<input type="submit" class="btn btn-default" name="DocumentSelected" value="{% trans 'Save document(s)' %}"/>
<input type="button" class="btn btn-default" data-toggle="modal" data-target="#myModal" value="{% trans 'Send document(s)' %}"/>
</div>
</div>
</form>
<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">{% trans 'Your informations' %}</h4>
</div>
<form method="post" action="" novalidate>
{% csrf_token %}
<div class="modal-body">
<div class="row">
<div class="col-md-12">
{{ form.email|as_crispy_field }}
</div>
</div>
<div class="row">
<div class="col-md-6">
{{ form.first_name|as_crispy_field }}
</div>
<div class="col-md-6">
{{ form.last_name|as_crispy_field }}
</div>
</div>
<div class="row">
<div class="col-md-6">
{{ form.country|as_crispy_field }}
</div>
<div class="col-md-6">
{{ form.institution|as_crispy_field }}
</div>
</div>
</div>
<div class="modal-header">
<h4 class="modal-title">{% trans 'Your cart' %}</h4>
</div>
<div class="model-body">
{% for element in selected_document|dictsort:'format' %}
<!-- Display wanted objects -->
{% endfor %}
</div>
<div class="modal-footer">
<input type="submit" class="btn btn-default" data-dismiss="modal" value="{% trans 'Send' %}"/>
</div>
</form>
</div>
</div>
</div>
Process :
This is the needed way :
User has to check one or multiple documents
User submits the choice and a modal containing CustomerForm is opening.
User fills CustomerForm fields and see in Cart part his document(s)
User submits the CustomerForm and an email is sent with previous informations/documents.
I think my method could work, but I don't overcome to call form_valid function and I would like to write correctly this class.
There is certainly ugly issues and I apologize by advance. But this is not the best way to improve myself and doesn't reproduce these issues ? ;)
Thanks !
EDIT :
I made something which seems to work. I removed data-dismiss="modal" from my modal submit button. I read that this attribute closed my modal and didn't post any form !
Finally, is it a good way to do what I did ?
Is it possible to replace both buttons Save documents and Send documents by an unique button which get documents and open the modal ?
I made something which seems to work. I removed data-dismiss="modal" from my modal submit button.
Previously :
<input type="submit" class="btn btn-default" data-dismiss="modal" value="{% trans 'Send' %}"/>
Now :
<input type="submit" class="btn btn-default" value="{% trans 'Send' %}"/>
It works now !
It was because data-dismiss="modal" closed the modal and I didn't know that.
Related
Created a website with products. I need to make a window for editing them on the site in order to change the manufacturer and other characteristics. This must be done in a pop-up window. I have data displayed, I change it, but nothing changes when I save it. How can this problem be solved.
My vievs:
def parts(request):
added = ''
error = ''
PartAllView = Part.objects.order_by('-id')
if request.method == 'POST' and 'parts_add' in request.POST:
form = PartForm(request.POST, request.FILES)
if form.is_valid():
form.save()
added = 'Добавлено'
else:
error = 'Данная запчасть уже добавлена'
if request.method == 'POST' and 'parts_edit' in request.POST:
PartPost = int(request.POST['parts_edit'])
PartID = Part.objects.get(id=PartPost)
if PartID:
PartID.save()
added = 'Запчасть успешно отредактирована'
else:
error = 'Ошибка редактирования'
form = PartForm()
data = {
'added': added,
'error': error,
'form': form,
'PartAllView': PartAllView,
}
return render(request, 'kross/parts.html', data)
My HTML:
{% if PartAllView %}
{% for el in PartAllView %}
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<div class="modal fade" id="partEdit{{ el.id }}">
<div class="modal-dialog modal-dialog-centered text-center" role="document">
<div class="modal-content modal-content-demo">
<div class="modal-header">
<h6 class="modal-title">Добавление запчасти</h6><button aria-label="Close" class="btn-close"
data-bs-dismiss="modal"><span aria-hidden="true">×</span></button>
</div>
<div class="modal-body">
<div class="row row-sm">
<div class="col-lg-6">
<div class="form-group">
<input type="text" class="form-control" name="brand" value="{{ el.brand }}">
</div>
</div>
<div class="col-lg-6">
<div class="form-group">
<input type="text" class="form-control" value="{{ el.number }}">
</div>
</div>
<div class="col-lg-12">
<div class="form-group">
<input type="text" class="form-control" value="{{ el.name }}"><br>
<input type="textarea" class="form-control" rows="2" value="{{ el.description }}">
</div>
</div>
</div>
{{ el.analog }}
...
You can use updateView to edit an existing data in your website by simply:
from django.views.generic.edit import UpdateView
From MyApp models import #Model
class editview(UpdateView):
model = #Your Model You want to edit
fields = [#Add the fields you want to edit]
template_name = 'edit.html'
success_url = ('Home')
In your edit Template add:
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Update">
I hope it help.
Info: i have sales_item QuerySet in view. i want to approve, decline and add some comments on specific sales_items. i also include html code were add sales list and form is inside of a dropdown menu. Where the menu pops up and we fill out the form.
Problem: The code below of views file is getting error Sale matching query does not exist.
models.py
class Authorize(models.Model):
APPROVED = 'AP'
DECLINED = 'DL'
STATUS_CHOICES = [
(APPROVED, 'Approved'),
(DECLINED, 'Declined'),
]
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
sales_item = models.ForeignKey(Sale, on_delete=models.CASCADE, null=True, blank=True)
comments = models.TextField(max_length=1000, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
status = models.CharField(choices=STATUS_CHOICES, default=APPROVED, max_length=2)
forms.py
class AuthorizeForm(forms.ModelForm):
class Meta:
model = Authorize
fields = [
'comments',
'status'
]
views.py
def SalesListView(request):
queryset = Sale.objects.all()
auth_form = AuthorizeForm(data=request.POST)
if request.method == 'POST':
pk = request.POST.get('pk')
sales = Sale.objects.get(id=pk)
if auth_form.is_valid():
approved = auth_form.save(commit=False)
approved.sales_item = sales
approved.save()
context = {
'sales': queryset,
'form': auth_form
}
return render(request, 'pending_sale.html', context)
index.html
{% for object in sales %}
<div class="col-lg-6">
<div class="hpanel hblue">
<div class="panel-body">
<div class="row">
<div class="col-sm-8">
<h4> {{ object.customers }}</h4>
<p>
{{ object.content }}
</p>
<div class="row">
<div class="col-sm-3">
<div class="project-label">Saler</div>
<small>{{ object.saler }}</small>
</div>
<div class="col-sm-4">
<div class="project-label">Timestamp</div>
<small>{{ object.created_on|naturalday }}</small>
</div>
<div class="col-sm-4">
<div class="project-label">Product</div>
<small>{{ object.created_on|naturalday }}</small>
</div>
</div>
</div>
<div class="col-sm-4 project-info">
<div class="project-action">
<div class="dropdown">
<div class="btn-group">
<button class="btn btn-xs btn-default"> View</button>
<button class="btn btn-xs btn-default dropdown-toggle" data-toggle="dropdown">
Edit
</button>
<div class="dropdown-menu auth-form-dropdown dropdown-menu-sw " style="width:352px;">
<a class="Link">
<i class="pe-7s-help1" style="font-style: 150px;"></i>
</a>
<div style="font-weight: bold;">
Approvels
</div>
<div style="margin-top: 10px;">
<form action="." method="POST"> {% csrf_token %}
<div class="form-group">
<textarea name="comments" id="id_comments" cols="30" rows="2" required
class="form-control" placeholder="comments..."></textarea>
</div>
<div class=" float-right">
<div id="id_status">
<input type="radio" name="status" value="AP" required
id="id_status_0">
<label for="id_status_0" class="waves-effect waves-themed"
required>Approved</label>
<input type="radio" name="status" value="DL" required
id="id_status_1">
<label for="id_status_1" class="waves-effect waves-themed"
required>Declined</label>
</div>
</div>
<button type="submit" class="btn btn-sm btn-default"
style="font-size: 13px; padding: 3px; font-weight: 400;">submit</button>
</form>
</div>
</div>
</div>
</div>
</div>
<div class="project-value">
<h2 class="text-info">
${{ object.products.price }}
</h2>
<p id="stores"></p>
</div>
</div>
</div>
</div>
</div>
</div>
{% endfor %}
The primary key('pk') you are passing is not valid.Try fetching some id i.e primary key using a simple print statement
q=Sale.objects.all().values('id')
print(q)
Try these two commands to know what are the available id options you have and then try working on the queryset.
Anyways there is another ways to do this task instead of using a form you can pass the id directly into the url section .Here is a nice tutorial explaining how to pass id through url.
You get his exception while trying to get object by:
sales = Sale.objects.get(id=pk)
You can catch this error by this example
try:
sales = Sale.objects.get(id=pk)
except Sale.DoesNotExist:
return ValidationError(f'No sale by id {pk}')
Try to check, what primary key you passed into query, does it exists in database, and return error if not.
Maybe you nees to create Sale if it doesn't exist
show Reply button should be specific for different comments . When I press show reply button it opens different replies which dosen't belong to that comment.
views.py
from django.shortcuts import render, HttpResponse, redirect,reverse
from fitness.models import Post, BlogComment
from django.contrib.auth.models import User
from fitness.templatetags import extras
# Create your views here.
def fitness(request):
everypost=Post.objects.all()
context={"everypost":everypost}
return render(request, "fitness/fit.html", context)
def blogfit(request, slug):
post=Post.objects.filter(slug=slug).first()
comments= BlogComment.objects.filter(post=post, parent=None)
replies= BlogComment.objects.filter(post=post).exclude(parent=None)
replyDict={}
for reply in replies:
if reply.parent.sno not in replyDict.keys():
replyDict[reply.parent.sno]=[reply]
else:
replyDict[reply.parent.sno].append(reply)
context={"post":post, 'comments': comments, 'user': request.user, 'replyDict': replyDict}
return render(request, "fitness/blogfit.html", context)
def postComment(request):
if request.method == "POST":
comment=request.POST.get('comment')
user=request.user
postSno =request.POST.get('postSno')
post= Post.objects.get(sno=postSno)
parentSno= request.POST.get('parentSno')
if parentSno=="":
comment=BlogComment(comment= comment, user=user, post=post)
comment.save()
else:
parent= BlogComment.objects.get(sno=parentSno)
comment=BlogComment(comment= comment, user=user, post=post , parent=parent)
comment.save()
return HttpResponse(reverse('fitness:fitness'))
Models.py
from django.db import models
from ckeditor.fields import RichTextField
from django.contrib.auth.models import User
from django.utils.timezone import now
# Create your models here.
class Post(models.Model):
sno=models.AutoField(primary_key=True)
title=models.CharField(max_length=255)
author=models.CharField(max_length=14)
slug=models.CharField(max_length=130)
timeStamp=models.DateTimeField(blank=True)
content=RichTextField(blank=True, null=True)
def __str__(self):
return self.title + " by " + self.author
class BlogComment(models.Model):
sno= models.AutoField(primary_key=True)
comment=models.TextField()
user=models.ForeignKey(User, on_delete=models.CASCADE)
post=models.ForeignKey(Post, on_delete=models.CASCADE)
parent=models.ForeignKey('self',on_delete=models.CASCADE, null=True )
timestamp= models.DateTimeField(default=now)
def __str__(self):
return self.comment[0:13] + "..." + "by" + " " + self.user.username
Html page
<h2 class="blog-post-title">{{post.title}}</h2>
<p class="blog-post-meta">{{post.timeStamp}} by {{post.author}}</p>
<p>{{post.content|safe}}</p>
<hr>
</div>
</div>
</div>
{% if user.is_authenticated %}
<form action="{% url 'fitness:postComment' %}" method="post">
{% csrf_token %}
<div class="form-group">
<label for="exampleInputEmail1">Post Comment </label>
<input type="text" class="form-control" name="comment" placeholder="Enter comment here">
</div>
<input type="hidden" name="postSno" value="{{post.sno}}">
<input type="hidden" name="parentSno" value="">
<button type="submit" class="btn btn-primary">Submit</button>
</form>
{% else %}
Please login to post a comment
{% endif %}
</div>
{% for comment in comments %}
<div class="row my-3">
<div class="col-md-1 ">
<img class="rounded mx-auto d-block w-100 border border-dark p-2" src="http://i9.photobucket.com/albums/a88/creaticode/avatar_1_zps8e1c80cd.jpg" alt="user">
</div>
<div class="col-md-11 ">
<h6 class="comment-name by-author"> {{comment.user.username}} </h6> <span class="badge badge-secondary "></span>
<b> {{comment.comment}} </b> <span class="badge badge-secondary "></span><br>
<button class="btn btn-sm btn-primary" type="button" data-toggle="collapse" data-target="#replyBox{{comment.sno}}" aria-expanded="false" aria-controls="replyBox{{comment.sno}}">
Reply
</button>
<button class="btn btn-sm btn-primary" type="button" onClick="myFunction()" id= "show-hide" >
Show Replies
</button>
<div class="reply mx-0" >
<div class="collapse" id="replyBox{{comment.sno}}">
<div class="card card-body my-2" >
<form action="{% url 'fitness:postComment' %}" method="post">
{% csrf_token %}
<div class="form-group" >
<label for="comment">Post a reply </label>
<input type="text" class="form-control" name="comment" placeholder="Enter comment here">
<input type="hidden" name="parentSno" value="{{comment.sno}}">
</div>
<input type="hidden" name="postSno" value="{{post.sno}}">
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</div>
<div class="replies bg-danger my-2" id = "replies" >
{% for reply in replyDict|get_val:comment.sno %}
<div class="replies">{{reply}}</div>
<br>
{% endfor %}
</div>
</div>
</div>
</div>
{% endfor %}
<!-- Contenedor Principal -->
<script>
function myFunction(){
var x = document.getElementById("replies");
if(x.style.display === "none"){
x.style.display = "block";
}
else{
x.style.display = "none";
}
}
</script>
I think it is a logical error. Can someone help me to find out this error? While everything is working fine but my reply button not working fine.
Change in models.py. update parent in BlogComment (add related_name)
parent=models.ForeignKey('self', on_delete=models.CASCADE, null=True, related_name='replies' )
Change in views.py where you are getting comments
comments= BlogComment.objects.filter(post=post, parent=None).prefetch_related('replies')
You don't need separate query for replies.
In html (Only for replies. Please change as per your requirement)
{% for comment in comments %}
{% for reply in comment.replies.all %}
{{ reply.comment }}
{% endfor %}
{% endfor %}
This will work. Remember related_name=replies
(Sorry for unclear answer. It's closing time in office and I am leaving. Good luck)
I am new to programming. I found nice bootstrap modal for registration, so i put it to my html code and it looks nice but nothing can be pressed or post.
Before i was using django and UserCreationForm without modals. So help me to concatenate these two things:
so this is my bootstrap modal that i found
<!-- Modal -->
<div class="modal fade" id="elegantModalForm" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"
aria-hidden="true">
<div class="modal-dialog" role="document">
<!--Content-->
<div class="modal-content form-elegant">
<!--Header-->
<div class="modal-header text-center">
<h3 class="modal-title w-100 dark-grey-text font-weight-bold my-3" id="myModalLabel"><strong>Войти</strong></h3>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<!--Body-->
<form type="post" action="{% url 'common:login' %}">
<div class="modal-body mx-4">
<!--Body-->
<div class="md-form mb-5">
<input type="email" name="useremail" id="Form-email1" class="form-control validate">
<label data-error="wrong" data-success="right" for="Form-email1">Ваша почта</label>
</div>
<div class="md-form pb-3">
<input type="password" id="Form-pass1" class="form-control validate">
<label data-error="wrong" data-success="right" for="Form-pass1">Пароль</label>
<p class="font-small blue-text d-flex justify-content-end">Забыли <a href="#" class="blue-text ml-1">
пароль?</a></p>
</div>
<div class="text-center mb-3">
<button type="button" class="btn blue-gradient btn-block btn-rounded">ок</button>
</div>
<p class="font-small dark-grey-text text-right d-flex justify-content-center mb-3 pt-2"> или войти
с помощью:</p>
<div class="row my-3 d-flex justify-content-center">
<!--Facebook-->
<button type="button" class="btn btn-white btn-rounded mr-md-3 z-depth-1a"><i class="fab fa-facebook-f text-center"></i></button>
<!--Twitter-->
<button type="button" class="btn btn-white btn-rounded mr-md-3 z-depth-1a"><i class="fab fa-twitter"></i></button>
<!--Google +-->
<button type="button" class="btn btn-white btn-rounded z-depth-1a"><i class="fab fa-google-plus-g"></i></button>
</div>
</div>
</form>
<!--Footer-->
<div class="modal-footer mx-5 pt-3 mb-1">
<p class="font-small grey-text d-flex justify-content-end">Первый раз? <a href="{% url 'common:signup' %}" class="blue-text ml-1">
Зарегистрируйся</a></p>
</div>
</div>
<!--/.Content-->
</div>
</div>
<!-- Modal -->
and this is my views.py before using modal:
def signup(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
return redirect('index')
else:
form = UserCreationForm()
return render(request, 'registration/signup.html', {'form': form})
So help me to show how it should work. Actually i used to use {{form.as_p}} but how should i do in this case?
I think what you are looking for is Django Forms
official doc- https://docs.djangoproject.com/en/2.2/topics/forms/
other- ( https://www.tutorialspoint.com/django/django_form_processing)
First, you need to create a form model and define the fields which you are taking as input.
Here is a sample-
from django import forms
class LoginForm(forms.Form):
user = forms.CharField(max_length = 100)
password = forms.CharField(max_length =100)
Then, you need to modify the view according to form. Here is a sample-
def login(request):
username = "not logged in"
if request.method == "POST":
#Get the posted form
MyLoginForm = LoginForm(request.POST)
if MyLoginForm.is_valid():
username = MyLoginForm.cleaned_data['username']
else:
MyLoginForm = Loginform()
return render(request, 'loggedin.html', {"username" : username})
and if you are sending data through POST, don't forget to add csrf token just in Html file.
form type="post" action="{% url 'common:login' %}">
{% csrf_token %}
I am trying to pass data from my website's login page as a POST request to Flask. However, Flask fails to obtain any data. Here's a code snippet of my test.py file that runs the Flask app. I realised that the code isn't entering the method itself.Can anyone help me understand where am I going wrong?
#app.route('/', methods=['POST'])
def my_form_post():
text = request.form['text']
processed_text = text.upper()
print "Processed text is..."
print processed_text
return processed_text
Here's the snippet of my login form:
div class="modal fade" id="direct-login-form" tabindex="-1" role="dialog" aria-labelledby="direct-login-form-label" aria-hidden="true">
<div class="vertical-alignment-helper">
<div class="modal-dialog vertical-align-center">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span>
</button>
<h4 class="modal-title" id="direct-login-form-label">Login</h4>
</div>
<div class="modal-body">
<div class="wrap-login-form wrap-reviews">
<form id="direct-login" form action="." method="POST" class="form-horizontal">
<div class="form-group">
<label class="col-sm-3" for="direct_username">Username</label>
<div class="col-sm-9">
<input type="text" name="text" class="form-control" id="direct_username" placeholder="Username">
</div>
</div>
<div class="form-group">
<label class="col-sm-3" for="direct_password">Password</label>
<div class="col-sm-9">
<input type="password" class="form-control" id="direct_password" placeholder="Password">
</div>
</div>
<div class="wrap-slidecheck clearfix">
<div class="col-sm-3"></div>
<div class="col-sm-9">
<div class="slidecheck">
<input type="checkbox" id="direct_remember_me" name="check" />
<label for="direct_remember_me"></label>
</div>
<span>Remember me</span>
</div>
</div>
<div class="form-group">
<label class="col-sm-3"></label>
<div class="col-sm-9">
<button type="submit" name="my-form" class="btn btn-default" value="Send">Submit</button>
</div>
</div>
<div class="form-group">
<label class="col-sm-3"></label>
<div class="col-sm-9">
<p class="help-block">Lost your password?<span> or </span>Register an Account</p>
</div>
</div>
<input type="hidden" id="direct_security" name="direct_security" value="f0abedaf74" /><input type="hidden" name="_wp_http_referer" value="/directory-category/coffee-lounge/" /> </form>
</div>
</div>
</div>
</div>
</div>
</div>
I simulated your problem on my machine it worked !
I made the following changes.
for view
#app.route("/")
def hello():
return render_template('register.html')
#app.route("/register", methods=['POST'])
def register():
text = request.form['text']
passwd = request.form['passwd']
processed_text = text.upper()
print "Processed text is...", processed_text, passwd
#do your further processing like saving to Database...
return render_template('register.html') #send to the profile/dashboard page
for html file
<form id="direct-login" form action="{{ url_for('register') }}" method="POST" class="form-horizontal">
<input type="password" class="form-control" id="direct_password" name='passwd' placeholder="Password">
However you should use WTF forms you will have a clean and reusable code with that.
an example forms.py
class RegistrationForm(Form):
email = StringField('Email', validators=[Required(), Email(), Length(1, 64)])
username = StringField('Username', validators=[Required(), Length(1, 64), Regexp('^[A-Za-z][A-za-z0-9._]*$', 0,'Username must have only letters, dots, digitsm or underscores')])
password = PasswordField('Password', validators=[Required(), EqualTo('password2', message='Password must match.')])
password2 = PasswordField('Confirm Password', validators=[Required()])
submit = SubmitField('Register')
'''
Custome validator for email validate_*
'''
def validate_email(self, field):
if(User.query.filter_by(email= field.data)).first():
raise ValidationError('Email already registered.')
'''
Custome validator for email validate_*
'''
def validate_username(self, field):
if(User.query.filter_by(username = field.data)).first():
raise ValidationError('Username already registered.')
then your html becomes
{% extends "base.html" %}
{% import "bootstrap/wtf.html" as wtf %}
{% block title %} - Register{% endblock %}
{% block page_content %}
<div class="page-header">
<h1>Register</h1>
</div>
<div class="col-md-5">
{{ wtf.quick_form(form) }}
</div>
{% endblock %}
The line containing the opening tag for your form seems like the suspect here:
<form id="direct-login" form action="." method="POST" class="form-horizontal">
While I'm not sure if the floating form attribute is causing any issues, I'm certain that it isn't doing anything useful so you should get rid of that.
Also, by specifying action=".", you are saying that the submission of the form should be directed to the same route that you got the form from. In your Flask code, you wrote
#app.route('/', methods=["POST"])
so in your form tag, you should specify action="/" for the submission to go to the my_form_post method in Flask.