password dont change in views.py on django - django

I'm trying to change a user's password on my views.py and whenever I change the password, I lose my connection and access to my account
my view.py:
user = User.objects.get(id=request.user.id)
user.password = make_password(request.POST.get("password"))
user.save()

A User object normally has a .set_password(…) method [Django-doc], so you can update that password with:
request.user.set_password(request.POST['password'])
request.user.save()
You can omit fetching the user object, since request.user aleady does that. Using user = User.objects.get(id=request.user.id) is thus an extra query that only is equivalent to request.user.

try using set_password instead of make_password like that
user = User.objects.get(id=request.user.id)
user.password = set_password(request.POST.get("password"))
user.save()
The following is an explanation provided by the Django documentation https://docs.djangoproject.com/en/3.2/topics/auth/default/#changing-passwords

Related

How do I retrieve the name of superuser in Django?

users = User.objects.all()
post.author = users.name
Considering that User is where superuser's info is stored in the database. It throws an error as:
'Query Set' object has no attribute 'name'
from django.contrib.auth.models import User
superusers = User.objects.filter(is_superuser=True)
superuser_names = [user.username for user in superusers]
If you are on a view that superuser is logged in you can check username by:
if request.user.is_superuser:
name = request.user.username
else:
name = None
user = User.objects.all() returns a queryset containing all the user in the db, therefore you can't use .name on it.
As far as I understood your problem you want the username of user therefore you should use user.username if want first name use user.first_name, this will work only on single object NOT on the queryset. You can user user.is_superuser to find if user is superuser or not.
This will help -> Read More in Docs

How to use check_password function in django

I'm a beginner in Django. I have a signup form with only 2 fields. Username and Password. The password is encrypted using the pbkdf2_sha256 algorithm.
I want to login using the username and password.so the password that I'm inputting in the login page must be checked with the encrypted password. How to do that?. Also, please explain what authenticate and check_password function does?
def save(request):
if request.method == 'POST':
name = request.POST.get('name')
password = request.POST.get('pass')
enc_pass = pbkdf2_sha256.encrypt(password,rounds=12000,salt_size = 32)
a = signup(username = name, password = enc_pass)
a.save()
return render(request,'save.html')
def login(request):
if request.method == 'POST':
username = request.POST.get('user')
password1 = request.POST.get('password1')
p = check_password(password=password1)
if signup.objects.filter(username__exact=username).exists() and p is True:
return HttpResponse("Success")
else:
return HttpResponse("Invalid Credentials")
return render(request, 'login.html')
You can do:
if check_password(password_user_entered, request.user.password):
# You can authenticate
Here, password_user_entered is password that came from the request(or, pw to be checked). And, request.user.password which is the password with which we want to compare.
check_password does not work like this. To make it work, you need to use Django's own authentication system. If you are concerned about using pbkdf2_sha256, Django provides this hasher. To use this with you own auth system, add it to settings:
PASSWORD_HASHERS = [
'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
'django.contrib.auth.hashers.PBKDF2PasswordHasher',
'django.contrib.auth.hashers.Argon2PasswordHasher',
]
And in django authentication, you do not need to hash it manually, django will take care of it itself. All you need to do is save the user like this:
from django.contrib.auth.models import User
user = User.objects.create_user(username=username, email=email, password=password, #.. other required fields)
And to check password:
user = User.objects.get(username=username)
user.check_password(password)
More information can be found in documentation

authenticate of django doesnt work

I am working on a password reset for django, but whatever I try the reset doesn't work. So i checked what my form handled on data which i knew had to be true. It still didn't work. So alst i tried to authenticate in the django shell. and this is what happened.
shell:
In [11]: user = User.objects.first()
In [12]: password = "bier"
In [13]: user.set_password(password)
In [14]: i = authenticate(username=user.username, password=password)
In [15]: i
i returns None
Someone any clue about what is causing this?
You should save your user object,
user.save()
According to the docs, user object is not saved:
"Sets the user’s password to the given raw string, taking care of the password hashing. Doesn’t save the User object."
https://docs.djangoproject.com/en/1.8/ref/contrib/auth/#django.contrib.auth.models.User.set_password
from django.contrib.auth.models import User
u = User.objects.get(username='john')
u.set_password('new password')
u.save()
https://docs.djangoproject.com/en/dev/topics/auth/default/#changing-passwords
https://docs.djangoproject.com/en/dev/topics/auth/default/#authenticating-users

Django Authenticate returns None

I have the following code snippet:
user = User(username='h#h.com',email='h#h.com')
user.set_password('pass')
user.save()
u = authenticate(username='h#h.com', password='pass') #this always returns None!!!
The problem is, u is always None. I've followed code samples on other stack overflow posts and have narrowed it down to the above lines.
Any ideas as to what might be happening?
Put something like this in your settings
#Authentication backends
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
)
or if you are using userena for your accounts
#Authentication backends
AUTHENTICATION_BACKENDS = (
'userena.backends.UserenaAuthenticationBackend',
'guardian.backends.ObjectPermissionBackend',
'django.contrib.auth.backends.ModelBackend',
)
Interestingly enough, check_password returns True in the following:
eml = "4#a.com"
pw = "pass"
uname = 'w2'
user = User.objects.create_user(uname,eml,pw)
user.save()
log.debug("Password check passes?")
log.debug(user.check_password(pw)) # Logs True!!!
user = authenticate(username=uname, password=pw)
Why don't you create a user like this:
user = User.objects.create_user( username="whatever", email="whatever#some.com", password="password")
user = authenticate( username="whatever",password="password")
In settings.py, add
AUTH_USER_MODEL = your custom user class
e.g if django app name is office and custom user class is Account then
AUTH_USER_MODEL = 'office.Account'
set_password is a misleading method, it doesn't save the password on the user table. You need to call user.save() in order for it to work on your flow
You have to check whether user is active? If not, you only set active for user in admin panel, or set when creating user by adding the following line to user model:
is_active = models.BooleanField(default=True)
Also check that you have the right username/password combo. sometimes the one that is created from the createsuperuser command is different than a username you would typically use.
As most of them suggested if we create the user's using User.objects.create_user(**validated_data) this will hash the raw password and store the hashed password. In-case if you you are using User model serializers to validate and create users, it is required to override the serializer method like this
class UserSerializers(serializers.ModelSerializer):
class Meta:
model = User
fields = "__all__"
# this is the method responsible for insertion of data with hashed password
def create(self, validated_data):
return User.objects.create_user(**validated_data)
I puzzled with this problem for four days, and the above answers didn't help.
The problem was that I, as you, was using the user.save() and I could not see what the problem was, but then I looked at it with debug eyes, and it turns out that if you use user.save() it messes with the hashing of the password somehow, don't ask me how I don't know. So I worked around it by using the user.create() method that Django provides, worked like a charm:
#api_view(['POST'])
def create_user(request):
new_user = UserSerializer(data=request.data)
if new_user.is_valid():
user_saved = new_user.create(request.data)
return Response('User {} created'.format(user_saved.username),
status=status.HTTP_200_OK)
else:
return Response('User not created', status=status.HTTP_200_OK)
I used something like this, but you can do as you wish just use the user.create().

How to create users in Django 1.5

I have extended my UserManager with a new method create_inactive_user. But how do I use UserCreationForm?
class UserManager(UserManager):
def create_inactive_user(self, username, email, password):
user = self.create_user(username, email, password)
user.is_active = False
salt = hashlib.sha1(str(random.random())).hexdigest()[:5]
activation_key = hashlib.sha1(salt+user.username).hexdigest()
user.activation_key = activation_key
user.save()
return user
I can see in https://github.com/django/django/blob/master/django/contrib/auth/forms.py that UserCreationForm is a ModelForm which saves the object, so how can I be sure to sign up the users though create_inactive_user() in my FormView?
Is it something like this:
class SignupView(FormView):
form_class = UserCreationForm
template_name = 'signup.html'
def form_valid(self, form):
User.objects.create_inative_user(form.cleaned_data['username'], form.cleaned_data['email'], form.cleaned_data['password'])
return super(SignupView, self).form_valid(form)
Looks like django-registration does exactly what you're trying to do, with all views and forms included. Looks like their approach is to use a generic form, not a model one. From the quickstart doc:
A user signs up for an account by supplying a username, email address and password.
From this information, a new User object is created, with its is_active field set to False. Additionally, an activation key is
generated and stored, and an email is sent to the user containing a
link to click to activate the account.
Upon clicking the activation link, the new account is made active (the is_active field is set to True); after this, the user can log in.