I am trying to implement a forgot password functionality in my django application. I have given a seperate forgottenPassword.html, where user can give his email id ; and if that email is registered(found in database) , corresponding password of that email is fetched and sent to his email id.This is what i am trying to achieve. Being a Django newbie i am stuck with the implementation. This is my forgottenPassword.html
<form name="forgotPassword" method="POST" id="myFormid" action="http://10.1.0.90:8080/forgotPassword/">
<div style="float:center;width:100%;">
Enter your E-mail ID</label><br/> <input type="text" name="email" size="25" />
<input type="submit" value="Submit" />
</div>
</form >
my method in views.py is
def forgotPassword(request):
if request.POST:
email=request.POST.get("email")
print email
user = UniversityDetails.objects.filter(email=email)
print user
if(not user):
print "No user"
return render_to_response("forgotPassword.html")
else:
???????????????
return render_to_response("passwordRecovery.html")
return render_to_response('forgotPassword.html')
Here, what i try to achieve is to pass the email id entered in forgottenPassword.html and save it in a variable 'email'. After that fetch all the objects with that email from database. and to filter password from it. I guess the part where i put ???? should be filled with a query to fetch the password corresponding to that email id. Can somebody help me to do this.
There is (by design) no way to do this. You cannot get the password for a user, because it is only stored in the database as a secure hash, and there is no way of reversing that hash.
However, Django does provide a built-in reset password implementation in contrib.auth - see the documentation.
rv_k, I just want to say I've recommended you look at the django.contrib.auth instead of your current system because you are storing passwords as plaintext.
That said, to answer your question, you've already pulled your UniversityDetails query matching the email. Assuming there's only 1 email per "user", use a get query instead.
user = UniversityDetails.objects.get(email=email)
send_mail("Your PW", user.password, "admin#example.com", [email])
Related
I'm using Django 1.8 to create an application and I'm using django_comments application to handle commenting system. I want only authenticated users to be able to write a new comment. So I've excluded name, email and url fields in forms.py since I want them to be hidden and retrieve these info automatically from logged in users:
class CommentDetailsForm(CommentSecurityForm):
exclude = ('name', 'email', 'url')
comment = forms.CharField(...)
But there's a function in CommentDetailsForm class to save these info in a dictionary to show them in Admin area:
def get_comment_create_data(self):
return dict(
content_type=ContentType.objects.get_for_model(self.target_object),
object_pk=force_text(self.target_object._get_pk_val()),
user_name=self.cleaned_data["name"],
user_email=self.cleaned_data["email"],
user_url=self.cleaned_data["url"],
comment=self.cleaned_data["comment"],
submit_date=timezone.now(),
site_id=settings.SITE_ID,
is_public=True,
is_removed=False,
)
My question is: How can I fill user_name, user_email and user_url in this function automatically when a logged in user post a new comment.
I guess one solution may be put something like <input type="hidden" name="user_name" value="{{ request.user.username }}" /> in template, but I'm not sure how to do it.
I'm working on an application where users can log in into my application using their Twitter account credentials which I implemented using the python-social-auth. Now, Django's authentication system provides User objects, with five primary attributes of username, password, email, first_name and last_name as given in the documentation: https://docs.djangoproject.com/en/1.7/topics/auth/default/#user-objects
Now, after the user successfully logs in using his/her Twitter account, I want certain fields of my form, like the user's full name, email address, Twitter account username, etc to be pre-filled. For that purpose, I used something like this for pre-filling user's full name form field:
{% if user and not user.is_anonymous %}
Full Name: <input type = "text" name = "name" value = "{{user.get_full_name}}"">
{% endif %}
This is what the above form field looks like after a user successfully logs in through his/her Twitter account:
Perfect! Works just as intended. Similarly, attributes such as username, last_name, first_name works just fine for the currently logged in User object.
However, when I try to pre-fill the email address field in my form using:
Email Address: <input type = "text" name = "email" value = "{{user.email}}"">
However, the value of {{user.email}} doesn't return anything, and my form field looks something like this:
Why is the email attribute of the User object not returning the email address through which the user logged in using his Twitter credentials? All other User attributes seem to be working just fine. Any reasoning behind this?
EDIT 1:
This is what my database at the admin looks like:
So the email field is empty, hence the User object returns nothing for that attribute value. But why is the email address not stored in the database every time a new user logs in using their Twitter accounts?
The email is stored elsewhere when using python-social-auth. They create a SocialUser table and likely the data you seek is stored in JSON format in the extra_data field - look at the model created by PSA
Pulling the additional info may not be as trivial as before, but you can add functionality that will save the email address to your user's table when the social user is created. See Pipeline
In admin if user_email is not showing probably there is no email added with perticular user.
Just make sure this by checking database again.
It's happening probably because you have nothing in your register process that actually stores the email in the database for the form, so in your view have something like
p = #user object from form.
p.email = request.POST['email']
p.save()
I'm creating a webapp in Django. I already run through Django tutorials from https://docs.djangoproject.com/en/dev/intro/ and part of documentation
I have a question how to store additional data between requests on the server-side.
Django does it really cool with users as follows:
in views.py:
def login_user(request):
if request.POST:
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
return HttpResponseRedirect(settings.LOGIN_REDIRECT_URL)
now in another function you can use the information stored in back-end which is associated via csrf token like this:
in views.py
#login_required
def myappformmethod(request):
user = request.user
msg = 'hello '+user.username
the generated html file does not contain any direct information about the user which is logged, but it keeps the csrf token as a form field:
<form name="myform" action="/myapp/myappformmethod" method="post" onsubmit="prepare()">
<div style='display:none'><input type='hidden' name='csrfmiddlewaretoken' value='NwKW2lFWSkkNEasdd3ExHe1l5ltzQi' /></div>
I would like to store some session-related data (e.g. favourite color) that will not be visible in html, but will be stored on server side and will be available using something like:
if request.favourite_color:
color = request.favourite_color
and not using
if request.POST.get('favourite_color'):
request.POST.get('favourite_color')
which is vulnerable to manual form element manipulation (if passed using form fields [type:hidden does not help, since you can edit them as well])
The aproriate approach would be adding field to request and producing something like "login" method mentioned earlier ... but how to do it?
Thanks!
The feature you're looking for is called "sessions" and is supported by Django directly:
https://docs.djangoproject.com/en/dev/topics/http/sessions/
... and here are two examples from that page:
request.session['fav_color'] = 'blue'
fav_color = request.session['fav_color']
Currently I have the
from django.contrib.auth.models import User
but I'm confused as to how you can use this to create a form for users to create themselves in the database and then login.
I found this link https://docs.djangoproject.com/en/1.2/topics/auth/#the-login-required-decorator in a similar question asked on here. But I really confused on how the user thing works. So any examples of possible templates variable to represent the login would be excellent. also any explanation of what's going on. I find it hard to understand when there isn't hadlry any documentation that's written like a user will be using it and not code that it written to be executed inside a shell.
To create a user form you can manually create a form with the fields you would like to save for the user, requiring at least a username and password
<form action="/signup/" method="POST">
Username: <input type="text" name="username" />
Password: <input type="text" name="password" />
</form>
then in the view this points towards you can capture the input like:
def signup(request):
username = request.POST['username']
password = request.POST['password']
User.objects.create_user(username=username, email='', password=password)
Django provides a shortcut to do this though, so you don't have to worry about creating your own html forms or validating forms! It will do everything for you! They are called Modelforms.
https://doc.djangoproject.com/en/dev/topics/forms/modelforms/#model-formsets
Regarding the login_required decorator, it makes sure that the user is logged before being allowed to access that particular view. If they are not, they are redirected to the page in your LOGIN_URL in your settings.py file.
The first step to learning how users work is to read https://docs.djangoproject.com/en/1.2/topics/auth/#the-login-required-decorator from top to bottom and do the code tutorials.
Make sure to include a CSRF token on your manually created forms as well
you can overwrite the login form like:
class MyLoginForm(AuthenticationForm):
'''Extend login form'''
username = forms.CharField(
label=_("username"),
max_length=30,
widget=forms.TextInput(attrs={
'title': '请输入您的域名!',
'id': 'id_username',
'name': 'username'
}))
password = forms.CharField(
label=_("password"),
widget=forms.PasswordInput(attrs={
'title':'请输入域密码!',
'id':'id_password',
'name':'password'
}))
here you can have you own validations for the login form.
and then in the urls.py:
(r'^accounts/login/$',
'django.contrib.auth.views.login',
{'template_name': 'login.html','authentication_form':MyLoginForm,}),
How would you implement simple password protection on a Google App Engine application? No users authentication, just simple requirement to enter a password in order to open specific page. The other requirement is that the target page should not be displayed if its URL is entered directly.
I'm looking for a solution using Python.
If you're protecting a single page and need no session persistence.
class MainPage(webapp.RequestHandler):
def post(self):
if self.request.get('user') == 'admin' and self.request.get('pass') == 'soopersecure':
self.response.out.write('authorized');
else:
self.response.out.write("""
<form method="post">
<input type="text" name="user"/>
<input type="password" name="pass"/>
<input type="submit" value="login"/>
</form>""")
Otherwise you could hash the username + salt and hand it to user as a session ID in a cookie and store that session ID into the datastore. Much simpler to use Google accounts though.
http://code.google.com/appengine/docs/python/gettingstarted/usingusers.html
If you want to restrict access for the entire app, use URL handler with "login" setting
Check - User and Administrator Login