In my app I want to check an input field e.g username if it's exists or not before continue my in form.
I'm using Flask jinja2 for templating. Here is a piece of my code:
<form method="POST" action="">
<div class="row">
<div class="form-group col-lg-9 col-md-9 col-sm-9">
<label for="inputUsername">User Name</label>
{{ render_field(form.username, class="form-control rounded" onkeyup="checkUserName()") }}
</div>
Of course the onkeyup attribut does not work, my question how to perform it ?
Thanks
Using WTForms for custom validation in my case, it's the good option
Related
I want to prefill a form with already existing database entries but can't access the correct ones.
A user can create a task and pass information on when creating it. When he wants to update it later, the already saved information should be used to prefill the form.
My problem is, that I'm inside a for-loop and it seems that I can't access the elements of the loop.
Here is what I'm doing:
I'm in a template inside a for-loop. The loop lists all tasks with an update button for every task. This button calls a form via the bootstrap data-target. Here's an example:
{% for task in tasks %}
<button class="btn-primary btn-block btn-lg" data-toggle="modal" data-target="#updateTask">Update Task</button> {% endfor %}
In my upcoming form I can't use the variables from the task element. For example the task.taskname. However, I can use all other variables like the user.first_name which exists outside the loop.
<div class="modal-body">
<form method="POST" action="{% url 'update_task' %}">
{% csrf_token %}
<div class="form-row">
<div class="form-group col-md-6">
<label for="name" class="col-form-label">Task:</label>
<input type="text" id="taskID" name="task" class="form-control" value="{{ user.first_name }}" required> -> this works
<input type="text" id="taskID2" name="task2" class="form-control" value="{{ task.taskname }}" required> -> this doesn't
</div>
<input type="submit" value="Send" class="btn btn-block custom-button">
</div>
I know I could do this with opening a completely new page but I want to try to use the data-target calling my view instead of calling the view directly.
Is there any way to pass my currently looped element to the form?
Thanks in advance!
Pascal
I'm trying to add a category field to my blog posts model in Django. When I make a post with the admin panel it shows the choices in a drop down list, however I wish to display choices in html.
Here is the form in my HTML file:
<div class="container">
<div class="row">
<div class="col-lg-7 offset-lg-1">
<form class="create-form" method="POST" enctype="multipart/form-data">{% csrf_token %}
<!-- title -->
<div class="form-group">
<label for="id_title">Title</label>
<input class="form-control" type="text" name="title" id="id_title" placeholder="Title" required autofocus>
</div>
<!-- Body -->
<div class="form-group">
<label for="id_body">Content</label>
<textarea class="form-control" rows="10" type="text" name="body" id="id_body" placeholder="Put the description of your post here..." required></textarea>
</div>
<div class="form-group">
<label for="id_category">Category</label>
<select class="form-control" name="category" id="id_category" required></select>
</div>
<!-- Image -->
<div class="form-group">
<label for="id_image">Image</label>
<input type="file" name="image" id="id_image" accept="image/*" required>
</div>
I also asked these types of questions about Django in StackOverflow. However, it is really hard to explain your questions as a newbie to experienced people so I will not just answer your question but also I want to show you the path to do it.
I think there are multiple parts to your question. It is not just to create a dropdown list with choices in HTML but also, you want to pass the data from your blog posts model in Django.
Firstly, let's say that the name of the HTML file is posts.html. In posts.html, to create a dropdown in an HTML is like this; (assume that your categories are zero, one and two and you can see these on dropdown list in the admin panel)
<select name="post_categories" class="filter-selectbox">
<option value="zero">"Zero"</option>
<option value="one">"One"</option>
<option value="two">"Two"</option></select>
However, if you want to create a dropdown list using your model's field, you should do similar like this: (I assumed that you can be able to create a dropdown list with your post model's field named category.)
<select name="post_categories" class="filter-selectbox">
{% for post in posts %}
<option value="{{ post.category }}">{{ post.category }}</option>
{% endfor %} </select>
So now you can pass and use the object to HTML and can be able to use its fields.
However, I assumed that you can be able to pass objects to the template. If you do not know how, there is another question that how to pass data to an HTML file? You should search more about "passing objects to template".
In views.py, when you render the template, you can be able to pass parameters or objects to use them in your template. Please look at this for that: Django: Passing object from template to views
So in your case, it should be something like this;
def get_posts(request):
posts = Post.objects.all() # In this case, I assume that I can reach category as post.category in the template
context = {"posts": posts}
return render(request, "posts.html", context)
I hope for a newbie in Django, I could explain it as simple. Keep learning.
Good Luck!
I want to use input field for authentication but if I search for authentication tutorial they are using built-in Django forms which I can't design it using html
You can customize how forms are rendered or you can pretty much write any HTML that you want just make sure your input name attributes match whatever you are accepting on backend.
Here's an example using Bootstrap 4 for styling. Start out by creating a view that subclasses LoginView. In the html file, instead of using {{ form }} or {{ form.username }} & {{ form.password }}, you can supply your own html for the fields. Just make sure your inputs are named the same as in {{ form }}.
views.py:
from django.contrib.auth.views import LoginView
class MyLoginView(LoginView):
template_name = 'login.html'
login.html:
{% block content %}
...
<div id="login-row" class="row justify-content-center align-items-center">
<div id="login-column" class="col-md-6">
<div id="login-box" class="col-md-12">
<form id="login-form" class="form" action="" method="post">
{% csrf_token %}
<div class="form-group">
<label for="username" class="text-white">Username:</label><br>
<input type="text" name="username" id="username" class="form-control" required>
</div>
<div class="form-group">
<label for="password" class="text-white">Password:</label><br>
<input type="password" name="password" id="password" class="form-control" required>
</div>
<div class="form-group">
<input type="submit" name="login" class="btn btn-light btn-md btn-block mt-5"
value="log in">
</div>
</form>
</div>
</div>
</div>
...
{% endblock content %}
i have a html template which i want to use for authentication in django. I am using pymongo to connect to remote mongodb and fetch_data. The remote mongodb has a collection which has username & password for a demo user. I read that django has a inbuilt authentication module but i dont want to use that.
My template :
<form action="/index.html">
<div class="form-group">
<div class="input-group">
<div class="input-group-addon"><i class="fa fa-user"></i></div>
<input type="text" class="form-control" placeholder="Username">
</div>
</div>
<div class="form-group">
<div class="input-group">
<div class="input-group-addon"><i class="fa fa-asterisk"></i></div>
<input type="password" class="form-control" placeholder="Password">
</div>
</div>
<div class="row">
<div class="col-xs-8 text-left checkbox">
<label class="form-checkbox form-icon">
<input type="checkbox"> Remember me
</label>
</div>
<div class="col-xs-4">
<div class="form-group text-right">
<button class="btn btn-success text-uppercase" type="submit">Sign In</button>
</div>
</div>
</div>
</form>
How can i pass data from my template to my views.py file? Currently I am not using any authentication.
my views.py:
from django.shortcuts import render
from django.http import HttpResponse
def login(request):
return render(request, 'login/login.html')
In Pymongo, I can use command db.getCollection('users').find({'email':'%s'}) {{email}} to pass email and verify.
PS: Most tutorial i read were about django's inbuilt authentication.
The generic way is to write custom authentication backend which handles authentication for you. Then it is recommended to create custom form which is rendered in your template.
Authentication backend
class YourBackend(object):
def authenticate(self, username=None, password=None):
# Check the username/password and return a User.
def get_user(self, user_id):
# return user by given user_id
Settings
When you have implemented your own authentication backend you should define it inside django settings.py. The first one is django's default authentication backend.
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
'your.own.authentication.backed',
)
Form
from django import forms
class YourLoginForm(forms.Form):
username = forms.CharField(max_length=254)
password = forms.CharField(label=_("Password"), widget=forms.PasswordInput)
View
from django.shortcuts import render
from django.http import HttpResponse
from django.contrib.auth import authenticate, get_backends
def login(request):
form = YourLoginForm(request.POST or None)
if form.method == 'POST':
if form.is_valid():
user = authenticate(username=form.cleaned_data['username'], password=form.cleaned_data['password'])
if user:
# redirect user to somewhere
return render(request, 'login/login.html')
Template
<form action="{% url 'your-login' %}" method="POST">
{{ form.non_field_errors }}
<div class="form-group">
<div class="input-group">
{{ form.username.errors }}
<div class="input-group-addon"><i class="fa fa-user"></i></div>
{{ form.username }}
</div>
</div>
<div class="form-group">
<div class="input-group">
{{ form.username.errors }}
<div class="input-group-addon"><i class="fa fa-asterisk"></i></div>
{{ form.password }}
</div>
</div>
<div class="row">
<div class="col-xs-4">
<div class="form-group text-right">
<button class="btn btn-success text-uppercase" type="submit">Sign In</button>
</div>
</div>
</div>
</form>
Urls
url(r'^login$', 'views.login', name='your-login'),
I suggest you to use external libraries for authentication and profiling. As I remember they have got options for mongodb. But if you want to reinvent the wheel, then you should use following.
1) Create class that extends form.ModelForm to handle registration and authentication process. You could read documentation how to do it. If will help you to handle validation of the data. You'll able to validate unique email fields and other stuff.
2) Create HTML form. You could use existing and just connect it with your ModelClass.
3) If you're using forms you could get data just with following command in yor controller:
form = MyForm(request.POST or None)
Then you'll be able to pass data to this form. If you don't want to use and form classes then you could retrieve if in such way in your controller:
if request.method == 'POST':
login = request.POST.get('login', None)
password = request.POST.get('password', None)
Assign controller with the form you could using urls.py, just the same way:
url(r'^login$', 'views.login', name='login'),
So using forms class you'll be able to pass empty form when GET request arrived and if it's POST request then you could collect data. Also, add to your HTML form following:
<form action="/login" method="post">
4) When you receive data from your login form you should authenticate. This could be done using custom authentication backend. You could find info here or just Google how to do it. I've never done it before, but it's pretty simple.
This is my first time using Flask and I have created the form for the visitors to fill out, but I want to use the bootstrap formatting so its looks similar to another form I am using in the website. Im not sure how I can link the form together. Here is my code for the contact.html page:
{% extends "index.html" %}
{% block content %}
<div class="content fixed-height">
<h3> {{ title }} </h3>
<!--<form action="http://127.0.0.1:5000/static/contact.php" method="post">
<div class="form-group">
<label>Your Name *</label>
<input type="text" name="cf_name" class="form-control" placeholder="Enter Name" required autofocus/>
</div>
<div class="controls-group">
<label class="control-label"> Your e-mail *</label>
<div class="controls">
<input type="email" name="cf_email" class="form-control" placeholder="Enter Email" required/>
</div>
</div>
<div class="form-group">
<label>Message *</label>
<textarea name="cf_message" class="form-control" placeholder="Enter Message" rows="6" required></textarea>
</div>
<input type="submit" value="Send" class="btn btn-primary">
<input type="reset" value="Clear" class="btn btn-primary">
</form> -->
<form action="{{ url_for('contact') }}" method=post
{{ form.hidden_tag() }}
{{ form.name.label }}
{{ form.name }}
{{ form.email.label }}
{{ form.email }}
{{ form.subject.label }}
{{ form.subject }}
{{ form.message.label }}
{{ form.message }}
{{ form.submit }}
</form>
</div>
{% endblock %}
The first part of the contact.html page is an old form that I was using and is in comment tags. Any help would be much appreciated
I'm guessing you're using the WTF Flask extension for working with forms?
Flask also has a Bootstrap extension that you can install using pip:
pip install flask-bootstrap
You can then import it and into the module that your Flask application instance has been created in:
from flask.ext.bootstrap import Bootstrap
app = Flask(__name__)
bootstrap = Bootstrap(app)
This will provide you with some great functionality including a helper method that you can use to quickly generate forms in your HTML templates.
Go to the page where you want to generate the form and after your extends statement do the following:
{% import "bootstrap/wtf.html" as wtf %} # imports the form template elements
# where you want your form to be
{{ wtf.quick_form(form) }} #the method takes the form argument from your view function
This will generate a form for you. You can read more about the Bootstrap extension here. Go to the Templates page and look for the section of Forms. Good luck!