I can't render form username on the template. like I want to to render the form fields automatically which I defined in forms.py file but it's not working. here you go below for my detailed files
forms.py
class CreateUserForm(UserCreationForm):
class Meta:
model = User
fields = ['username', 'email', 'password1', 'password2']
views.py
from django.shortcuts import render
from django.contrib.auth.forms import UserCreationForm
My views
from .forms import CreateUserForm
Registration
def regPage(request):
form = CreateUserForm()
if request.method == 'POST':
form = CreateUserForm(request.POST)
if form.is_valid():
form.save()
context = {'form':form}
return render(request, 'web/car-finder-home.html')
html
<form class="needs-validation" method="POST" action="">
{% csrf_token %}
<div class="mb-4">
<label class="form-label text-light" for="signup-name">Username</label>
{{ form.username }}
</div>
<div class="mb-4">
<label class="form-label text-light" for="signup-email">Email address</label>
<input class="form-control form-control-light" type="email" id="signup-email" placeholder="Enter your email" required />
</div>
<div class="mb-4">
<label class="form-label text-light" for="signup-password">Password <span class="fs-sm opacity-50">min. 8 char</span></label>
<div class="password-toggle">
<input class="form-control form-control-light" type="password" id="signup-password" minlength="8" required />
<label class="password-toggle-btn" aria-label="Show/hide password"> <input class="password-toggle-check" type="checkbox" /><span class="password-toggle-indicator"></span> </label>
</div>
</div>
<div class="mb-4">
<label class="form-label text-light" for="signup-password-confirm">Confirm password</label>
<div class="password-toggle">
<input class="form-control form-control-light" type="password" id="signup-password-confirm" minlength="8" required />
<label class="password-toggle-btn" aria-label="Show/hide password"> <input class="password-toggle-check" type="checkbox" /><span class="password-toggle-indicator"></span> </label>
</div>
</div>
<div class="form-check form-check-light mb-4">
<input class="form-check-input" type="checkbox" id="agree-to-terms" required />
<label class="form-check-label" for="agree-to-terms">
<span class="opacity-70">By joining, I agree to the</span> Terms of use <span class="opacity-70">and</span> Privacy policy
</label>
</div>
<button class="btn btn-primary btn-lg w-100" type="submit">Sign up</button>
</form>
views.py
from django.shortcuts import render
from django.contrib.auth.forms import UserCreationForm
from .forms import CreateUserForm
def regPage(request):
form = CreateUserForm()
if request.method == 'POST':
form = CreateUserForm(request.POST)
if form.is_valid():
form.save()
# consider adding a redirect page here this is a good approach
else:
context = {'form':form}
return render(request, 'web/car-finder-home.html',context) # your forgot to add context
Now inside your template you can access the form...
I didn't add in core urls.py
from my_app_name import urls
urlpatterns = [
path('cars/', views.regPage, name="register"),
]
xD
Related
I have tried to add a book in to the database using an HTML form. After the submission, the page redirect to a page where all the books are listed .Then whenever I refresh the page , the data is became duplicated. How do I resolve this problem?
urls.py
from django.urls import path
from . import views
app_name='library'
urlpatterns =[
path('', views.home, name='home'),
path('book/',views.book,name='book'),
path('book_details/<int:book_id>',views.book_details,name='book_details'),
path('book_edit/<int:book_id>',views.book_edit,name='book_edit'),
path('book_delete/<int:book_id>',views.book_delete,name='book_delete'),
path('update/<int:book_id>',views.update,name='update'),
path('author/',views.author_view,name='author_view'),
path('addbook/',views.add_book,name='add_book'),
path('books/',views.add_submit,name='add_submit'),
]
views.py
def add_submit(request):
if request.method =='POST':
title=request.POST.get('t_title')
print(title)
author_name=request.POST.get('a_author')
author, created=Author.objects.get_or_create(Name=author_name)
summary=request.POST.get('s_summary')
date=request.POST.get('d_date')
book=Book(Title=title,Author=author,Summary=summary,Published_date=date)
book.save()
books=Book.objects.all()
return render(request,'books.html',{'books':books})
Template file:
<form action="{% url 'library:add_submit' %}" method="POST">
{% csrf_token %}
<div class="form-outline mb-4">
<input type="text" id="bname" name="t_title" class="form-control" />
<label class="form-label" for="bname">Title</label>
</div>
<div class="form-outline mb-4">
<input type="text" id="bauthor" name="a_author" class="form-control" />
<label class="form-label" for="bauthor">Author</label>
</div>
<div class="form-outline mb-4">
<textarea rows="5" cols="33" id="bsummary" name="s_summary" class="form-control"></textarea>
<label class="form-label" for="bsummary">Summary</label>
</div>
<div class="form-outline mb-4">
<input type="date" placeholder="" id="pdate" name="d_date" class="form-control" />
<label class="form-label" for="pdate">Published_Date</label>
</div>
<!-- Submit button -->
<button type="submit" class="btn btn-primary btn-block">SUBMIT</button>
</form>
This is most common problem, the thing is that after dealing with POST data you should always return an HttpResponseRedirect, the tip is not specific to Django, but it's a good web practice in general so:
urls.py:
urlpatterns =[
...
path("success/", views.success, name="success"
]
views.py:
def add_submit(request):
if request.method =='POST':
title=request.POST.get('t_title')
print(title)
author_name=request.POST.get('a_author')
author, created=Author.objects.get_or_create(Name=author_name)
summary=request.POST.get('s_summary')
date=request.POST.get('d_date')
book=Book(Title=title,Author=author,Summary=summary,Published_date=date)
book.save()
return redirect("library:success")
else:
books=Book.objects.all()
return render(request,'books.html',{'books':books})
def success(request):
return render("success.html")
success.html
<h2> The form has been successfully submitted.</h2>
Go back to form
I have a form which registers a new user, I used Bootstrap 5 to make it look nice. However, when I press the submit button the form does not validate. The error it shows when I write print(form.errors) says that every field is required, which means it didn't recieve anything. Why does this happen? This is my code:
HTML
<div class="card" id='signup_card'>
<div class='card-header'>
<h2 class='card-title'>Sign Up</h2>
</div>
<div class='card-body'>
<form method='POST' action="" id='create_user_form' style="color: #fff;">
{% csrf_token %}
<label for='usernameInput' class="form-label">{{form.username.label}}:</label>
<input type="text" id='usernameInput' style="margin-bottom: 20px;">
<label for='phoneNumberInput' class="form-label">{{form.phone_number.label}}:</label>
<input type="text" id='phoneNumberInput' style="margin-bottom: 20px;">
<label for='emailInput' class="form-label">{{form.email.label}}:</label>
<input type="text" id='emailInput' style="margin-bottom: 20px;">
<label for='password1Input' class="form-label">{{form.password1.label}}:</label>
<input type="text" id='password1Input' style="margin-bottom: 20px;">
<label for='password2Input' class="form-label">{{form.password2.label}}:</label>
<input type="text" id='password2Input' style="margin-bottom: 20px;">
<button class="btn btn-primary" type='submit'>Submit</button>
</form>
</div>
models.py
class Account(User):
phone_number = BigIntegerField()
forms.py
class CreateAccountForm(UserCreationForm):
class Meta:
model = Account
fields = ['username', 'email', 'phone_number', 'password1', 'password2']
views.py
def signup(request):
if request.method == 'GET':
form = CreateAccountForm()
ctx = {
'form':form
}
return render(request, 'signup.html', ctx)
if request.method == 'POST':
form = CreateAccountForm(request.POST)
if form.is_valid():
form.save()
else:
print(form.errors)
return render(request, 'index.html')
Your input elements need to specify a name="…" attribute to specify for which name they will associate a value:
<form method='POST' action="" id='create_user_form' style="color: #fff;">
<label for='usernameInput' class="form-label">{{form.username.label}}:</label>
<input type="text"name="username" id='usernameInput' style="margin-bottom: 20px;">
<label for='phoneNumberInput' class="form-label">{{form.phone_number.label}}:</label>
<input type="text" name="phone_number" id='phoneNumberInput' style="margin-bottom: 20px;">
<label for='emailInput' class="form-label">{{form.email.label}}:</label>
<input type="text" name="email" id='emailInput' style="margin-bottom: 20px;">
<label for='password1Input' class="form-label">{{form.password1.label}}:</label>
<input type="text" name="password1" id='password1Input' style="margin-bottom: 20px;">
<label for='password2Input' class="form-label">{{form.password2.label}}:</label>
<input type="text" name="password2" id='password2Input' style="margin-bottom: 20px;">
<button class="btn btn-primary" type='submit'>Submit</button>
</form>
Your error is normal because you need add a name attribute to input field :
<label for='usernameInput' class="form-label">{{form.username.label}}:</label>
<input type="text" id='usernameInput' name='username' style="margin-bottom: 20px;">
You can also use full Django form like this :
<label for='usernameInput' class="form-label">{{form.username.label}}:</label>
{{ form.username }}
Now, if you want add some boostrap class name to have nice look, you can override the Form class __init__ method like this :
class CreateAccountForm(UserCreationForm):
class Meta:
model = Account
fields = ['username', 'email', 'phone_number', 'password1', 'password2']
# Here we override the form elements attributes to add boostrap class
def __init__(self, *args, **kwargs):
super(RegistrationForm, self).__init__(*args, **kwargs)
# Add some placeholder to username input field
self.fields['username'].widget.attrs['placeholder'] = 'Your username'
# add an id to username input field
self.fields['username'].widget.attrs['id'] = 'usernameInput'
# add the same class to all the fields (commom attribute value for all)
for field in self.fields:
self.fields[field].widget.attrs['class'] = 'form-control'
More about Django model form here
I am trying to use a html form from the internet with Django. However, after watching crazy amount of videos on youtube and reading through https://docs.djangoproject.com/en/1.10/topics/forms/ , I can't manage to make it work. When I click the submit button, Chrome tells me the "The form has submitted", but nothing else happens. It should log the user in and redirects to the index page.
registration_form.html
<div class="panel panel-info mt10 br-n bg-gradient-1 mw500 mauto">
<form id="contact" method="post" action="{% url 'feed:connection' %}">
{% csrf_token %}
{{ form.non_field_errors }}
<div class="panel-body text-center p50 text-center">
<div class="section">
<p class="text-uppercase text-white ls100 fw700">Username</p>
{{ form.username.errors }}
<label for="username" class="field prepend-icon">
<input id="username" type="text" name="username" placeholder="Enter username" class="gui-input">
</label>
</div>
<div class="section">
<p class="text-uppercase text-white ls100 fw700">Password</p>
{{ form.password.errors }}
<label for="password" class="field prepend-icon">
<input id="password" type="password" name="password" placeholder="Enter password" class="gui-input">
</label>
</div>
<div class="panel-footer clearfix p10 ph15">
<button type="submit" class="button btn-primary mr10 pull-right text-uppercase text-white ls100 fw700">Sign In</button>
<!--<label class="switch ib switch-primary pull-left input-align mt10">
<input id="remember" type="checkbox" name="remember" checked="">
<label for="remember" data-on="YES" data-off="NO"></label> <span>Remember me</span>
</label> -->
</div>
<div class="section text-left pt20 pb10">Forget password?
<p><span class="text-white">Haven't yet registration? Sign up here</span></p>
</div>
<div class="section row">
<div class="col-md-6">Facebook</div>
<div class="col-md-6">Google +</div>
</div>
</div>
</form>
</div>
views.py
from django.views.generic.base import TemplateView
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login
from django.views.generic import View
from .forms import LoginForm
# Pour faire afficher la page index
class IndexView(TemplateView):
template_name = 'feed/index.html'
# Pour se logger
class UserFormView(View):
form_class = LoginForm
template_name = 'feed/registration_form.html'
# display blank form
def get(self, request):
form = self.form_class(None)
return render(request, self.template_name, {'form': form})
# process form data
def post(self, request):
form = self.form_class(request.POST)
if form.is_valid():
user = form.save(commit=False)
# cleaned (normalized) data
username = form.cleaned_data['username']
password = form.cleaned_data['password']
user.set_password(password)
user.username = username
user.save()
# returns User objects if credentials are correct
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
return redirect('feed:index')
return render(request, self.template_name, {'form': form})
urls.py
from django.conf.urls import url, include
from . import views
app_name = "feed"
urlpatterns = [
# /feed/
url(r'^$', views.IndexView.as_view(), name='index'),
# /register/
url(r'^connection/$', views.UserFormView.as_view(), name='connection'),
]
forms.py
from django import forms
class LoginForm(forms.Form):
user = forms.CharField(max_length=100)
password = forms.CharField(widget=forms.PasswordInput, min_length=8)
What is wrong with the code? Thank you for your time.
I have created an HTML form trying to do simple registration.
The problem is that after clicking submit button no error appears but when I chech database the data from fields is not there.
signup.html
<form action="\polls\Registration" method="POST">
<div class="form-group mb15">
<input type="text" class="form-control" name="userName" placeholder="Enter Your Username" required>
</div>
<div class="form-group mb15">
<input type="password" class="form-control" name="password" placeholder="Enter Your Password">
</div>
<div class="form-group mb15">
<input type="text" class="form-control" name="fullName" placeholder="Enter Your Full Name">
</div>
<div class="form-group mb20">
<label class="ckbox">
<input type="checkbox" name="checkbox">
<span>Accept terms and conditions</span>
</label>
</div>
<div class="form-group">
<button class="btn btn-success btn-quirk btn-block">Create Account</button>
<br>
Already a member? Sign In Now!
</div>
</form>
forms.py
class RegistrationForm(forms.Form):
userName= forms.CharField(label='Username',max_length=100)
password = forms.CharField(label='Password', max_length=100)
fullName= forms.CharField(label='Full Name', max_length=100)
myview.py
def reg(request):
if request.method == 'POST':
the request:
form = forms.RegistrationForm(request.POST)
if form.is_valid():
return HttpResponseRedirect('/polls/signin')
else:
form = forms.RegistrationForm()
return render(request, 'signup.html', {'form': form})
urls.py
urlpatterns = [
url(r'^Registration', myview.reg,name='Registration'),
]
[SOLVED]
What I did is that I created a model to handle form processing.I also used modelForm instead of forms. For anyone having same issue check this
When i click submit it is showing csrf verification failed eventhough i used {% csrftoken %}
here my view.py:
#csrf_protect
def register(request):
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
user = User.objects.create_user(
username=form.cleaned_data['username'],
password=form.cleaned_data['password1'],
email=form.cleaned_data['email']
)
return HttpResponseRedirect('/login/')
else:
form = RegistrationForm()
catagories = Company_Profile.objects.all()
variables = RequestContext(request, {
'form': form,'catagories' : catagories
})
return render_to_response(
'index1.html',
variables
)
my html page index1.html s:
<div id="connect_signup_box" class="connect_box_form clearfix">{% csrf_token %}
<form enctype="application/x-www-form-urlencoded" class="global_form" action="" method="POST">{% csrf_token %}<div><div><h3>Create Account</h3>
<div class="form-elements" >
<div id="name-wrapper" class="form-wrapper"><div id="name-label" class="form-label"><label for="name" class="optional">Name</label></div>
<div id="name-element" class="form-element">
<input type="text" name="name" id="name" value="" class="signup-name"></div> </div>
<div id="username-wrapper" class="form-wrapper"><div id="username-label" class="form-label"><label for="id_username">Username:</label></div>
<div id="username-element" class="form-element">
<input id="id_username" max_length="30" name="username" required="True" type="text">
<div id="uJTtr4FGLy-wrapper" class="form-wrapper"><div id="uJTtr4FGLy-label" class="form-label"><label for="id_email">Email Id:</label></div>
<div id="uJTtr4FGLy-element" class="form-element">
<input id="id_email" max_length="30" name="email" required="True" type="text">
<p class="description">You will use your email address to login.</p></div> </div>
<div id="password-wrapper" class="form-wrapper"><div id="password-label" class="form-label"><label for="id_password1">Password:</label></div>
<div id="password-element" class="form-element">
<input id="id_password1" name="password1" type="password">
<p class="description">Passwords must be at least 6 characters in length. </p></div></div>
<div id="passconf-wrapper" class="form-wrapper"><div id="passconf-label" class="form-label"><label for="id_password2">Password (Confirm):</label></div>
<div id="passconf-element" class="form-element">
<input id="id_password2" max_length="30" name="password2" render_value="False" required="True" type="password">
<p class="description">Enter your password again for confirmation.</p></div> </div>
<p class="description">This will be the end of your profile link, for example: <br> </p></div></div>
</div></div>
<div id="terms-wrapper" class="form-wrapper"><div id="terms-label" class="form-label"> </div><div id="terms-element" class="form-element">
<input type="hidden" name="terms" value=""><input type="checkbox" name="terms" id="terms" value="1" tabindex="7">
<label class="null" for="terms">I have read and agree to the <a target="_blank" href="help/terms.html">terms of service</a>.</label></div></div>
<div id="submit-wrapper" class="form-wrapper"><div id="submit-label" class="form-label"> </div><div id="submit-element" class="form-element">
<input type="hidden" name="csrfmiddlewaretoken" value="vmGTjibc4wzzsrVshrElFs8J0T24UECG">
<input type="submit" class="btn btn-success" value="submit">
<input type="reset" class="btn" value="cancel">
</div></div></div></form> </div>
</div>
i am not using form.as_p since i need it individually to apply css..
please help me
edit:
i got the answer
the actual problem is i have hardcoded csrf i.e
so removed it and it works fine. thanks to # Daniel Roseman who noticed me that and thanks to all for helping me.
You should pass the RequestContext as the third argument of the render_to_response():
return render_to_response('index1.html',
{'form': form, 'catagories': catagories},
RequestContext(request))
Or, as a better option, use the render() function instead of the render_to_response():
from django.shortcuts import render
return render(request, 'index1.html', variables)
You need to move the {% csrf_token %} tag - put it within the form. Also, if you are using django.middleware.csrf.CsrfViewMiddleware, you do not have to manually csrf_protect your view.
And for the context instance, try doing it like this:
def register(request):
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
user = User.objects.create_user(
username=form.cleaned_data['username'],
password=form.cleaned_data['password1'],
email=form.cleaned_data['email']
)
return HttpResponseRedirect('/login/')
else:
form = RegistrationForm()
catagories = Company_Profile.objects.all()
variables = {'form': form,'catagories' : catagories}
return render_to_response('index1.html', variables, context_instance=RequestContext(request))