I am new to django and have not found a question corresponding to my entry level. And I just can't figure out how to work with sessions. I want to make a checkbox on login to remember me. After I registered in settings SESSION_EXPIRE_AT_BROWSER_CLOSE = True, you need to enter your username and password after closing the browser. How do I change this parameter using the "remember me" checkbox? Thank you
views.py
def login(request):
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
user = auth.authenticate(username=username, password=password)
if user is not None:
auth.login(request, user)
return redirect('/')
else:
messages.info(request, 'invalid credentials')
return redirect('login')
else:
return render(request, 'prof/login.html')
login.html
<body>
<div class="text-center mt-5">
<form style="max-width: 480px; margin: auto" method="post">
{% csrf_token %}
<img
src="https://logodix.com/logo/1713894.jpg"
alt=""
width="120"
height="90"
class="d-inline-block mt-4 mb-4"
/>
<p class="hint-text mb-3">Please sign in</p>
<label class="sr-only" for="username"></label>
<input
type="login"
name="username"
class="form-control"
placeholder="username"
required
autofocus
/>
<label for="password" class="sr-only"></label>
<input
type="password"
name="password"
class="form-control mt-2"
placeholder="password"
/>
<div class="checkbox">
<label for="checkbox">
<input type="checkbox" name="checkbox" value="remember-me" /> remember
me
</label>
</div>
<div class="d-grid gap-2 mt-4">
<input type="Submit" class="btn btn-primary" value="sign in" />
</div>
</form>
<div class="messages">
{% for message in messages %}
<h3>{{message}}</h3>
{% endfor %}
</div>
https://docs.djangoproject.com/en/3.1/topics/http/sessions/#browser-length-sessions-vs-persistent-sessions
you need to set request.session.set_expiry(value) when a user logs on and the checkbox is clicked.
the value in this function is filled out using the following datatypes and values: https://docs.djangoproject.com/en/3.1/topics/http/sessions/#django.contrib.sessions.backends.base.SessionBase.set_expiry
for you this will mean the following:
def login(request):
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
user = auth.authenticate(username=username, password=password)
if user is not None:
auth.login(request, user)
if request.cleaned_data['remember_me'] == True:
request.session.set_expiry(value)
# ^^^^^^
# insert something here
return redirect('/')
else:
messages.info(request, 'invalid credentials')
return redirect('login')
else:
return render(request, 'prof/login.html')
def login(request):
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
user = auth.authenticate(username=username, password=password)
try:
remember = request.POST['remember_me']
if remember:
settings.SESSION_EXPIRE_AT_BROWSER_CLOSE = False
except:
is_private = False
settings.SESSION_EXPIRE_AT_BROWSER_CLOSE = True
if user is not None:
auth.login(request, user)
return redirect('/')
else:
messages.info(request, 'invalid credentials')
return redirect('login')
else:
return render(request, 'prof/login.html')
Related
I have made a form and set method=post and while taking request.post['name'] to a variable MultiValueDictKeyError is Coming why is that ?
<form action="verify_user" method="post">
{% csrf_token %}
<input required type="text" placeholder="Name" name="name"><br><br>
<input required type="password" placeholder="Password" name="password"><br><br>
<input required type="passord" placeholder="Confirm password" name="confirm_password" id=""> <br><br>
<br><br><h1>{{ messages }}</h1>
<button type="submit">Create</button>
</form>
this is my form ------
def verify_user(request):
inputname = request.POST['name']
inputpass = request.POST['password']
inputconfirmpass = request.POST['confirm_password']
if not inputpass == inputconfirmpass:
messages.info(request,"Passwords don't match")
else:
messages.info(request,"Passwords match")
return redirect('/verify_user')
this is my function in views.py -------------
MultiValueDictKeyError at /verify_user
'name'
Request Method: GET
Request URL: http://127.0.0.1:8000/verify_user
Django Version: 4.1.2
Exception Type: MultiValueDictKeyError
Exception Value: 'name'
this is the error --------
Try to provide another name as name for e.g. person_name something like that, also I'd recommend you to use .get() so that you can also provide some other default value.
views.py:
def verify_user(request):
if request.method=="POST":
inputname = request.POST.get('person_name', False)
inputpass = request.POST.get('password', False)
inputconfirmpass = request.POST.get('confirm_password', False)
if not inputpass == inputconfirmpass:
messages.info(request,"Passwords don't match")
else:
messages.info(request,"Passwords match")
return redirect('/verify_user')
else: # GET request
return render(request, "some_folder_name/your_template.html")
Template file:
<form method="POST">
{% csrf_token %}
<input required type="text" placeholder="Name" name="person_name"><br><br>
<input required type="password" placeholder="Password" name="password"><br><br>
<input required type="passord" placeholder="Confirm password" name="confirm_password" id=""> <br><br>
<br><br><h1>{{ messages }}</h1>
<button type="submit">Create</button>
</form>
Basically, from and to both page have parameters so how can I redirect to page with parameters?
html page:
{% for vr in adduser.adduser.all %}
<form method="POST" action="{% url 'edituser' id=vr.id bid=adduser.id %}">
{% csrf_token %}
<label for="FirstName">First Name<span style="color:#ff0000">*</span></label>
<input type="text" class="form-control" name="firstname" placeholder="Type FirstName here...." value="{{vr.f_name}}">
<label for="LastName">Last Name<span style="color:#ff0000">*</span></label>
<input type="text" class="form-control" name="lastname" placeholder="Type LastName here...." value="{{vr.l_name}}">
{% endfor %}
<button type="submit" class="btn btn-primary">Add</button>
urls.py
path('edituser/<uid>/<bid>', views.edituser, name="edituser"),
views.py
def edituser(request, uid, bid):
if request.method == "POST":
if request.POST.get('firstname') and request.POST.get('lastname'):
saverecord = AddContact()
saverecord.id = uid
saverecord.f_name = request.POST.get('firstname')
saverecord.l_name = request.POST.get('lastname')
saverecord.save()
viewRecords = AddContact.objects.filter(subscribe='subscribe')
return HttpResponseRedirect(reverse('adduser',bid))
else:
viewRecords = AddContact.objects.filter(subscribe='subscribe')
messages.error(request, "Error During Editing of Contact")
return redirect(request, 'broadcastlist.html')
else:
viewRecords = AddContact.objects.filter(subscribe='subscribe')
messages.error(request, "Error During Editing of Contact")
return redirect(request, 'broadcastlist.html')
To clarify more uid is userid which is for edit the user and bid is broadcast id which is to redirect to the broadcast list.
To redirect to another page in Django with parameters use this
return HttpResponseRedirect(reverse(viewname='the view to which it should redirect', args=(parameters to be passed)))
Use redirect, it's easier than invoking reverse and HttpResponseRedirect directly. (Doc)
from django.shortcuts import redirect
...
return redirect( 'myapp:url_name', urlparam=value, ...)
which is the same as
return HttpResponseRedirect(
reverse( 'myapp:url_name',
kwargs={ 'urlparam': value, ... }
)
I have two forms:
auth.html
<form class="form-signin pt-5" action="/auth/" method="post" >
{% if error_msg: %}
{{ error_msg }}
{% endif %}
<div class="mt-5 form-label-group">
<p class="text-muted">email</p>
<input type="email" id="inputEmail" class="form-control" name = "email" required autofocus>
</div>
<div class="form-label-group">
<p class="text-muted"> password</p>
<input type="password" id="inputPassword" name="password" class="form-control" required>
<label for="inputPassword"></label>
</div>
<div class="checkbox mb-3"></div>
<button class="btn btn-lg btn-danger btn-block" type="submit">Enter</button>
</form>
success form.html
Success
code in flask is:
app = Flask(__name__)
app.secret_key = "randomstring"
app.config["SECRET_KEY"] = "secret_key"
app.config["EMAIL"] = "test#test.ru"
app.config["PASSWORD"] = "test"
#app.route("/auth/", methods=["GET", "POST"])
def auth_open():
error_msg = "" # Пока ошибок нет
if request.method == "POST":
email = request.form.get("username")
password = request.form.get("password")
if ((email and password) and email == app.config["EMAIL"] and password == app.config["PASSWORD"]):
session["is_auth"] = True
return render_template("/")
else:
error_msg = "Error login or password"
return render_template("auth.html", error_msg=error_msg)
When I input password and login it shows me error message instead of success form.How should I solve this problem?
email = request.form.get("email")
I'm trying to signup user but getting some weird error.
please help me to solve it
This is my view file with the function named signup
def signup(request):
if request.method=='POST':
username = request.POST['username']
email = request.POST['email']
password1 = request.POST['password1']
password11 = request.POST['password11']
if password1==password11:
if User.objects.filter(username=username).exists():
messages.info(request,'Username Taken')
return redirect('/account')
elif User.objects.filter(email=email).exists():
messages.info(request,'Email Taken')
return redirect('/account')
else:
user=User.objects.create_user(username=username, password=password1, email=email)
user.save();
auth.login(request,user)
print('user created')
else:
messages.info(request,'Password not Matching')
return redirect('/account')
return redirect('/')
else:
return render(request,'account.html')
And this is my signup file. I've save file with the name account.html.
<form id="regform" style="margin-top: -40px;" action="/signup/" method="post">
{% csrf_token %}
<input type="text" placeholder="Username" name="username">
<input type="email" placeholder="Email" name="email">
<input type="password" placeholder="Password" name="password1">
<input type="password" placeholder="Confirm Password" name="Password11">
<button type="submit" id="btn2">Register</button>
<div>
{% for message in messages %}
<h6>{{message}}</h6>
{% endfor %}
</div>
</form>
I am getting Invalid captcha response for below set up. Contact form worked perfectly fine, I added rule that verifies captcha, I checked secret keys and still getting Invalid Captcha even after solving it. Below is my setup:
views.py
def get_client_ip(request):
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
if x_forwarded_for:
ip = x_forwarded_for.split(',')[0]
else:
ip = request.META.get('REMOTE_ADDR')
return ip
def grecaptcha_verify(request):
response = {}
data = request.POST
captcha_rs = data.get('g-recaptcha-response')
url = "https://www.google.com/recaptcha/api/siteverify"
params = {
'secret': settings.RECAPTCHA_SECRET_KEY,
'response': captcha_rs,
'remoteip': get_client_ip(request)
}
verify_rs = requests.get(url, params=params, verify=True)
verify_rs = verify_rs.json()
response["status"] = verify_rs.get("success", False)
response['message'] = verify_rs.get('error-codes', None) or "Unspecified error."
return response
def contact(request):
if request.method == 'POST':
if grecaptcha_verify(request) == "success":
subject = request.POST.get('subject')
message = request.POST.get('message')
email = request.POST.get('email')
if subject and message and email:
try:
send_mail(subject, message, email, ['myemail#gmail.com'],fail_silently= True)
except BadHeaderError:
return HttpResponse('{Bad Header}')
return greatsuccess(request)
else:
return HttpResponse('{Invalid Form}')
else:
return HttpResponse('Invalid Captcha')
return render(request, 'personal/contact.html')
My template:
<div class="form-area">
<form role="form" method="POST">
{% csrf_token %}
<input type="text" class="form-control" id="subject" name="subject" placeholder="Subject" maxlength="70" required>
</div>
<br>
<div class="form-group">
<input type="email" class="form-control" id="email" name="email" placeholder="Email" required>
</div>
<div class="form-group">
<textarea class="form-control" type="textarea" id="message" name="message" placeholder="Message" maxlength="300" rows="7"></textarea>
</div>
<button type="submit" name="submit" class="btn btn-m btn-secondary">Submit</button>
<script src='https://www.google.com/recaptcha/api.js'></script>
<div class="g-recaptcha" data-sitekey="MYKEY"></div>
</form>
I am quite new to Python, how to check what is happening in the background and at which point verification fails?
You are making get request for verification, but you need to make post request to it. That is why captcha verification failing. So try like this:
url = "https://www.google.com/recaptcha/api/siteverify"
headers = {'User-Agent': 'DebuguearApi-Browser',}
params = {'secret': settings.RECAPTCHA_SECRET_KEY, 'response': captcha_rs}
verify_rs = requests.post(url, data=params, headers=headers) # <-- Update Here
... # rest of your code
Please see the documentation on how to verify recaptcha.
Ok.
I got it working. Thanks Ruddra for all the help.
I deleted first </div> as I've noticed this was unnecessary. This allowed g-recaptcha-response to be included in POST data. Apparently it's important to make sure your form is correct and google likes it.
Secondly I did some modifications to main views.py as per advice I received+ some improvements.
def greatsuccess(request):
messages.success(request, "Email sent!")
return render(request, 'personal/contact.html')
def greatfail(request):
messages.error(request, "Invalid Captcha!")
return render(request, 'personal/contact.html')
def grecaptcha_verify(request):
data = request.POST
captcha_rs = data.get('g-recaptcha-response')
url = "https://www.google.com/recaptcha/api/siteverify"
headers = {'User-Agent': 'DebuguearApi-Browser',}
params = {'secret': settings.RECAPTCHA_SECRET_KEY, 'response': captcha_rs}
verify_rs = requests.post(url,params, headers=headers)
verify_rs = verify_rs.json()
response = verify_rs.get("success", False)
return response
def contact(request):
if request.method == 'POST':
response=grecaptcha_verify(request)
if response == True :
subject = request.POST.get('subject')
message = request.POST.get('message')
email = request.POST.get('email')
if subject and message and email:
try:
send_mail('Sent from mywebsite '+subject, message, email, ['email#gmail.com'],fail_silently= True)
except BadHeaderError:
return HttpResponse('{Bad Header}')
return greatsuccess(request)
else:
return HttpResponse('{Invalid Form}')
else:
greatfail(request)
return render(request, 'personal/contact.html')
My template:
<form method="POST">
{% csrf_token %}
<input type="text" class="form-control" id="subject" name="subject" placeholder="Subject" maxlength="70" required>
<br>
<div class="form-group">
<input type="email" class="form-control" id="email" name="email" placeholder="Email" required>
</div>
<div class="form-group">
<textarea class="form-control" type="textarea" id="message" name="message" placeholder="Message" maxlength="300" rows="7"></textarea>
</div>
<div class="g-recaptcha" data-sitekey="key"></div>
<button type="submit" name="submit" class="btn btn-m btn-secondary">Submit</button>
</form>
{% for message in messages %}
{{ message }}
{% endfor %}