Django login form not keeping input after bad submit - html

I have a login form and if a user enters an invalid username or password, the page refreshes and removes the Username value they entered. I would like it so that the username field doesn't empty on failed submit.
views.py
def login_page(request):
if request.user.is_authenticated:
return redirect('dashboard:dashboard')
elif request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return redirect('dashboard:dashboard')
else:
messages.info(request, 'Username or Password is invalid.')
return render(request, 'main/login.html', {})
login.html:
<form id="login-form" action="" method="post" role="form">
{% csrf_token %}
<div class="form-group">
<input type="text" name="username" id="username" tabindex="1" class="form-control" placeholder="Username" value="">
</div>
<div class="form-group">
<input type="password" name="password" id="password" tabindex="2" class="form-control" placeholder="Password">
</div>
<div class="form-group">
<div class="row">
<div class="col-sm-6 center" style="border-radius: 16px;">
<input type="submit" name="login-submit" id="login-submit" tabindex="5" class="form-control btn btn-login" value="Login">
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-lg-12">
<div class="center">
Forgot Password?
</div>
</div>
</div>
</div>
</form>

It's all about passing the username in the context.
try this:
views.py
def login_page(request):
context = {}
if request.user.is_authenticated:
return redirect('dashboard:dashboard')
elif request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return redirect('dashboard:dashboard')
else:
context["username"] = username
messages.info(request, 'Username or Password is invalid.')
return render(request, 'main/login.html', context)
login.html:
...
<input type="text" name="username" id="username" tabindex="1" class="form-control" placeholder="Username" value="{{ username }}">
...

Related

Post method is not working in my HTML forms

my form is like this
<h1>Signup below</h1>
<form action="result" method="post">
{% csrf_token %}
<h3>Username</h3>
<input type="text" name="username" />
<h3>Email</h3>
<input type="email" name="email">
<h3>Password</h3>
<input type="password" name="password">
<h3>Rententer your password</h3>
<input type="password" name="password2">
<input type="button" />
</form>
and in my view folder code for this url is this
def register(request):
username=request.POST['username']
email=request.POST['username']
password=request.POST['username']
verify_password=request.POST['verify_password']
return render(request,'result.html')
but whenever I run this code it shows
screenshot of the error message
you should add in def
def register(request):
if request.method == 'POST':
.....
also when you want to return a response check this valid response form django
finally make sure you are using a valid URL in urls.py
<h1>Signup below</h1>
<form action="/result/" method="post">
{% csrf_token %}
<h3>Username</h3>
<input type="text" name="username" value="{{form.username}}" />
<h3>Email</h3>
<input type="email" name="email" value="{{form.email}}">
<h3>Password</h3>
<input type="password" name="password" value="{{form.password}}">
<h3>Rententer your password</h3>
<input type="password" name="password2" value="{{form.password2}}">
<input type="button" />
</form>
Note: form is context name from view so that's why I have written
{{form.username}}
And in views.py:
try this:
def register(request):
if request.method == 'POST':
form = RegisterForm(request.POST)
if form.is_valid:
form.save()
username = form.cleaned_data.get('username')
# messages.success(request,f'Welcome { username }')
return HttpResponseRedirect('/users/')
else:
form = RegisterForm()
return render(request,'users/register.html',{'form':form})

after submit the views functions do nothing

hello this my html formulaire
<div id="Admin" class="tabcontent">
<form method="POST" action="">
{% csrf_token %}
<h2> Vous ètes un Admin ?</h2>
<div class="container" action >
<input type="hidden" name="user_type" value="1">
<label for ="id_email"><b>Votre Email</b></label>
<input id="id_email" type="text" placeholder="Entrer Votre Email" name="email" required>
<label for ="id_password" ><b>Mot de Passe</b></label>
<input id="id_password" type="password" placeholder="Entrer Votre Mot de passe" name="password" required>
<button type="submit" >Login</button>
<label>
<input type="checkbox" checked="checked" name="remember"> souviens de moi
</label>
</div>
and this the views function called login
def login(request):
context = {}
user = request.user
if user.is_authenticated:
return render(request, "login.html")
if request.POST:
form = LoginForm(request.POST)
if form.is_valid():
email = form.cleaned_data.POST['email']
password = form.cleaned_data.POST['password']
user = authenticate(request, email=email, password=password)
if user:
login(request, user)
if user.user_type == '1':
return render(request, "administrateur.html")
elif user.user_type == '2':
return render(request, "entrepreneur.html")
else:
print("errors")
form = AuthenticationForm()
context['login_form'] = form
return render(request, "entrepreneur", context)
and i create in form files this class
class LoginForm(forms.ModelForm):
email = forms.EmailField()
password = forms.PasswordInput()
this my 3 user class in model:
class CustomUser(AbstractUser):
user_type=((1,"admin"),(2,"entrepreneur"))
user_type=models.IntegerField(default=1,choices=user_type)
email=models.EmailField(unique=True,blank=True)
objects = UserManager()
def __str__(self):
return self.first_name
#admin-----------------------------------------------------------------------
class Admin(models.Model):
user = models.OneToOneField(CustomUser, on_delete=models.CASCADE,primary_key=True)
date_naissance = models.DateField(default=timezone.now)
adresse = models.CharField(max_length=20, blank=True)
def __str__(self):
return self.user.first_name
# Entrepreneur----------------------------------------------------------------
class Entrepreneur(models.Model):
user= models.OneToOneField(CustomUser,on_delete=models.CASCADE,primary_key=True)
date_naissance=models.DateField()
adresse_entr=models.CharField(max_length=20,blank=True)
telephone=models.IntegerField()
occupation=models.CharField(max_length=50)
annnee_exp=models.IntegerField()
def __str__(self):
return self.user.first_name
when i submit it stay in the login.html and dont redirect to any other html's page
i did not find where is my problem
maybe i have a problem on passing data from htm to views??
maybe in my models class???
or in form or views
what is my errors!!!!!????? plesae help me
thank you
try to put this
<form method="POST" action="{% url 'login' %}">
Also I am not sure if you have properly closed your form with a <\form>.
Please check it.

Fetching data from template to send email

please this is the html file i am trying to fetch the data to be able to send it to my settings email
<form action="{% url 'send'%}" method="post" role="form" class="contactForm">
{% csrf_token %}
<div class="form-group">
<input type="text" name="name" class="form-control" id="name" placeholder="Your Name" data-rule="minlen:4" data-msg="Please enter at least 4 chars" />
<div class="validation"></div>
</div>
<div class="form-group">
<input type="email" class="form-control" name="email" id="email" placeholder="Your Email" data-rule="email" data-msg="Please enter a valid email" />
<div class="validation"></div>
</div>
<div class="form-group">
<input type="text" class="form-control" name="subject" id="subject" placeholder="Subject" data-rule="minlen:4" data-msg="Please enter at least 8 chars of subject" />
<div class="validation"></div>
</div>
<div class="form-group">
<textarea class="form-control" name="message" rows="5" data-rule="required" data-msg="Please write something for us" placeholder="Message"></textarea>
<div class="validation"></div>
</div>
<div class="text-center"><button type="submit">Send Message</button></div>
</form>
and this is my views.py which i collected the data from the html file
def sendEmail(request):
if request.method == 'POST':
name = request.POST['name']
email = request.POST['email']
subject = request.POST['subject']
message = request.POST['message']
send_mail(
"Contact Form",
message,
email,
settings.EMAIL_HOST_USER,
fail_silently=False
)
return render(request, 'app/index.html')
and my settings for the email which i am using gmail
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = '*****#gmail.com'
EMAIL_HOST_PASSWORD = '******'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
and my urls.py is which i sent it to my url to the views
urlpatterns = [
path('',views.index,name='index'),
path('sendmail/', views.sendEmail, name='send'),
]

checking radio button on Django view from template

I am creating a custom sign up form and this is the view I created:
def signup(request):
if request.user.is_authenticated:
return render(request, 'listings/index.html', {})
if request.method == 'POST':
if 'cr-1' in request.POST:
newuser = User.objects.create_user(username=request.POST.get('email'), email=request.POST.get('email'), password=request.POST.get('password'))
newpatient = Patient.objects.create(user=newuser)
user = authenticate(request, username=username, password=password)
if user is not None:
auth_login(request, user)
return redirect('dashboard')
elif 'cr-2' in request.POST:
newuser = User.objects.create_user(username=request.POST.get('email'), email=request.POST.get('email'), password=request.POST.get('password'))
newdoctor = Doctor.objects.create(user=newuser)
user = authenticate(request, username=username, password=password)
if user is not None:
auth_login(request, user)
return redirect('dashboard')
else:
print("##################### NOTHING HAPPENED #####################")
return render(request, 'dashboard/signup.html', {})
I purposely added an else statement printing NOTHING HAPPENED on the console because nothing happens when I click on submit.
Here is the template:
<form class="form-type-material" method="POST" action="{% url 'signup' %}">
{% csrf_token %}
<div class="custom-control custom-radio">
<input type="radio" id="cr-1" name="rg-1" class="custom-control-input" checked>
<label class="custom-control-label" for="cr-1">Patient/Visiteur</label>
</div>
<div class="custom-control custom-radio">
<input type="radio" id="cr-2" name="rg-1" class="custom-control-input">
<label class="custom-control-label" for="cr-2">Médecin/Praticien</label>
</div>
<div class="form-group">
<input type="text" class="form-control" id="id_email" name="email" required>
<label for="email">Adresse email</label>
</div>
<div class="form-group">
<input type="password" class="form-control" id="id_password" name="password" required>
<label for="password">Mot de passe</label>
</div>
<div class="form-group">
<input type="password" class="form-control" id="id_password-conf" name="password-conf" required>
<label for="password-conf">Confirmation du mot de passe</label>
</div>
<div class="form-group">
<div class="custom-control custom-checkbox">
<input type="checkbox" class="custom-control-input" required>
<label class="custom-control-label">I agree to all <a class="text-primary" href="#">terms</a></label>
</div>
</div>
<br>
<button class="btn btn-bold btn-block btn-primary" type="submit">Créer et accéder au tableau de bord</button>
</form>
What seems to be the issue?
PS: In a previous attempt I did if 'cr-1'.checked in request.POST because I saw it in another stackoverflow thread but it gave me the error: str .... has no checked method.
Here in your template you have 'cr-1' and 'cr-2' as ids, but while submitting the form the name will be sent. i.e here you have name name="rg-1"
So, you need to check
if 'rg-1' in request.POST:

Pass form data from one html page to another html page and datase in flask

I am willing to fill a form(HTML) and pass that data into another HTML page and also insert that data into a database.
app.py
#app.route('/signup')
def signup():
return render_template("client_signup.html")
#app.route('/registered')
def registered():
userName = request.form['userName']
userEmail = request.form['userEmail']
userPassword = request.form['userPassword']
conn = mysql.connect()
cursor = conn.cursor()
cursor.execute("INSERT INTO emp(userName, userEmail, userPassword) VALUES (%s,%s,%s)", (userName, userEmail, userPassword))
return render_template("client_signin.html")
client_signup.html
<form id="msform" action="registered">
<!-- progressbar -->
<ul id="progressbar">
<li class="active">Account Setup</li>
</ul>
<!-- fieldsets -->
<fieldset>
<h2 class="fs-title">Create your account</h2>
<h3 class="fs-subtitle">This is step 1</h3>
<input type="text" name="userName" placeholder="Your Name" />
<input type="text" name="UserEmail" placeholder="Email" />
<input type="password" name="userPassword" placeholder="Password" />
<input type="password" name="cUserPassword" placeholder="Confirm Password" />
<input type="submit" name="submit" class="submit action-button" value="Submit" />
</fieldset>
</form>
I am not having to knowledge of FLASK (just a beginner)
First, if you want to make a POST method, you need method to #app.route:
#app.route('/registered', methods=['GET', 'POST'])
Then, for your question, you can try the code:
#app.route('/signup')
def signup():
return render_template("client_signup.html")
#app.route('/registered', methods=['GET', 'POST'])
def registered():
userName = request.form['userName']
userEmail = request.form['userEmail']
userPassword = request.form['userPassword']
conn = mysql.connect()
cursor = conn.cursor()
cursor.execute("INSERT INTO emp(userName, userEmail, userPassword) VALUES (%s,%s,%s)", (userName, userEmail, userPassword))
return redirect("/signup")
The small change is return redirect("/signup")
You can pass the form data through the render_template function and render them use Jinja syntax in template file. For example:
#app.route("/registered")
def registered():
// get form data and insert
return render_template("client_signin.html", username=username, password=password)
<form>
<input name="username" value="{{ username }}" />
<input name="password" value="{{ password }}" />
<input type="submit" value="submit />
</form>