I'm having some trouble creating a new account and then logging in. I enter all the credentials in (first_name, last_name, username, password), and select "Create new account", and it successfully redirects me back to the login page. However, when I try to login with this new account, it says that my username doesn't exist.
The problem is most likely in my views.py file:
def create_account(request):
if request.method == 'POST':
new_user = User(username = request.POST["username"],
password = request.POST["password"])
new_user.save()
Student.objects.create(user=new_user,
first_name=str(request.POST.get("first_name")),
last_name=str(request.POST.get("last_name")))
new_user.is_active = True
return redirect('../')
else:
return render(request, 'polls/create_account.html')
Let me know if you guys need any more code or information. Thanks!
The password field needs to be encrypted. If you are going to set the password, you need to use set_password() method that will deal with encryption.
new_user = User(username = request.POST["username"])
new_user.set_password(request.POST["password"])
new_user.save()
this another option if you work in form with cleaned_data:
def create_account(self, request):
if request.method == 'POST':
form = RegisterForm(request.POST) #registration form
if form.is_valid():
cd = form.cleaned_data
username = cd['username']
password = cd['password']
new_user = User.objects.create_user(
username = cd['username'],
password = cd['password']
)
new_user.save()
#... do stuff
Related
I am using django contrip auth for authenticate user. Signup function always working and register and login user successfully but after that I m logged out and try to login again but this time login function doesnt work.
I add this codes my settings file
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
)
AUTH_USER_MODEL = 'app.User'
My User model seems like that in models.py
class User(AbstractUser):
pass
My Login and Register function
def dlogin(request):
if request.method=='GET':
return render(request, "login.html")
if request.method == "POST":
username = request.POST['username']
password = request.POST['password']
# Attempt to sign user in
user = authenticate(request, username=username, password=password)
print(user)
# Check if authentication successful
if user is not None:
login(request, user)
cur_user = request.user
return render(request,'index.html',{
'success':'login successful',
'user':cur_user
})
else:
return render(request,'login.html',{
'error':'Invalid username and/or password.'
})
#csrf_exempt
def signup(request):
if request.method != "POST":
return render(request, 'signup.html')
# Get form information
username = request.POST["username"]
password = request.POST["password"]
confirmation = request.POST["confirmation"]
# Ensure password matches confirmation
if password != confirmation:
return render(request,'register.html',{
'message':'Passwords dont match'
})
# Attempt to create new user
user = User.objects.create_user(username,password)
user.save()
login(request, user)
return redirect('index')
I did some research and couldn't find any problem in my code. Does anyone can help me?
I fixed it
I change this in signup function
user = User.objects.create_user(username,password)
to this
user = User.objects.create_user(username=username,password=password)
and it works but i dont know why
In my django account app I want to check if inputed email exist in database (basic django db.sqlite3).
forms.py:
from django import forms
from django.contrib.auth.models import User
class UserRegistrationForm(forms.ModelForm):
password = forms.CharField(label='Hasło', widget=forms.PasswordInput)
password2 = forms.CharField(label='Powtórz hasło', widget=forms.PasswordInput)
class Meta:
model = User
fields = ('username', 'first_name', 'email')
def clean_password2(self):
cd = self.cleaned_data
if cd['password'] != cd['password2']:
raise forms.ValidationError('Hasła nie są identyczne.')
return cd['password2']
views.py:
def register(request):
if request.method == "POST":
user_form = UserRegistrationForm(request.POST)
if user_form.is_valid():
# Creating new user object, without saving in database
new_user = user_form.save(commit=False)
# Setting new password
new_user.set_password(
user_form.cleaned_data['password'])
# Saving user object
new_user.save()
return render(request,
'account/register_done.html',
{'new_user': new_user})
else:
user_form = UserRegistrationForm()
return render(request,
'account/register.html',
{'user_form': user_form})
Now when i enter the same email for another user, form creates that user.
I think is it possible to make this in that way?
1). make email as variable like password and password2
2). remove email from meta
3). create method clean_email() with checking if email exist in db if not raise error
I don't know how to get to emails in db
Thanks for all help!
Below is_valid(): in your views.py do this
if user_form.is_valid():
new_user = user_form.save(commit=False)
email=user_form.cleaned_data['email']
if not User.objects.filter(email=email).exists():
//the rest of your code
else:
//some error message
This ensures that a new user is only created if they do not already exist.
If you working on an app that requires a username, email, and password length of x(in this case 8), then do this.
if not User.objects.filter(username=username).exists():
if not User.objects.filter(email=email).exists():
if len(password) < 8:
// some error message alert
return('register') // the same page
//continue with the rest of your code
.....
return ('login-page')
return('register') the same page
If this solves your issue please don't forget to accept this as the correct answer.
I building an password reset system for my users. An password reset code sending to user mail and now I want to authenticate user by this code. If user enter the right code then password will be change otherwise not.
I am also storing the verification code in my models fields.
models.py:
class UserProfile(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,related_name="userprofile")
forget_password_token = models.CharField(max_length=100,blank=True,null=True)
views.py I am sending the code to user mail and also storing the same code in my models fields
def ForgetPasswordSendCode(request):
if request.method == "POST":
email = request.POST["email"]
User = get_user_model()
if not User.objects.filter(email=email).first():
messages.success(request, "Invalid mail")
return redirect('members:reset-password')
user_obj = User.objects.get(email=email)
reset_code = str(rand_number_mail()) #generating random code
profile_obj = UserProfile.objects.get(user=user_obj)
profile_obj.forget_password_token = reset_code
profile_obj.save()
current_site = get_current_site(request)
subject = 'Verification Code'
context = {
'user_first_name': user_obj.first_name ,
'user_last_name': user_obj.last_name ,
'domain': current_site.domain,
'reset_code': reset_code
}
html_body = render_to_string('mail/resetpassword-mail.html', context)
to_email = request.POST["email"]
email = EmailMultiAlternatives(subject=subject,from_email='noreply#farhyn.com',to=[to_email])
email.attach_alternative(html_body, "text/html")
email.send(fail_silently=False)
messages.success(request, "An password reset code sent to your email")
return redirect('members:change-password') #redirecting user to password reset page after submitting mail.
return render(request, 'members/password_reset_form.html')
Now I am stuck in password reset view where user insert the code and change his password. I am not undersealing how to authenticate user by verification code.
def ChangePassWordPage(request):
return render(request,'members/password_change.html')
This might helps
Step1: Send user your code and code must have a reference of your user so it will be easy to cross check
Step2: if your code match with your user (this case act as a authentication )
Step3: update your user model with new password (make_password)
UPDATE
def ChangePassWordPage(request):
if request.method == "POST":
email = request.POST["email"]
user_token = request.POST["token"]
User = get_user_model()
if not User.objects.filter(email=email).first():
messages.success(request, "Invalid mail")
return redirect('members:reset-password')
user_obj = User.objects.get(email=email)
token = UserProfile.objects.filter(user = user_obj).first().forget_password_token
if token == user_token:
#update your user password
else:
return redirect('members:reset-password')
return render(request,'members/password_change.html')
In step 2, your token will act as authentication means, token will just verify the user and token to match and if that matches then you just update the password.
And this will authorized you to update your password
Yes Same as it is!!
You don't authenticate the user by the verification code. You get the matching user object by the code and chance the password. –
Klaus D.
I have problem about auth system. It only work by username and password, but I need use email rather than username
def login_view(request):
if request.user.is_authenticated or request.user.is_staff or request.user.is_superuser:
return redirect('/account/')
elif request.method == "POST":
email = request.POST['email']
# username = request.POST['username'] # it work
password = request.POST['password']
user = authenticate(request, email=email, username=username, password=password)
if not grecaptcha_verify(request):
context = {'message_bad':'...'}
elif user is not None:
login(request, user)
return redirect('/account/')
else:
context = {'message_bad':'...'}
else:
context = {}
return render(request, "login.html", context)
Please help me or how can I change login() codes at auth lib .
if what you have said about not having models is accurate then you will need to create a custom user model that has a custom backend where you can use the email instead of a username
id recommend following this tutorial for that
https://rahmanfadhil.com/django-login-with-email/
I am trying to make a custom registration form in Django, using HTML and CSS and not Django's form.as_p and Bootstrap. I have the following code in views.py:
def signUp(request):
if request.POST:
username = request.POST['username']
email = request.POST['email']
password = request.POST['password']
password_confirm = request.POST['password-confirm']
if(valid_form(username, email, password, password_confirm)) {
#create the new user
} else {
#send some error message
}
return render(request, 'index.html')
I have my own function valid_form to check if the form fields entered by the user are valid. However, I am not sure how I can create the new user using Django's User Model. In all of the code examples regarding registration forms I have seen something like this:
def register(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
return redirect('main-page')
else:
form = UserCreationForm()
return render(request, 'users/register.html', {'form': form})
Where they use form.save() to create the new user. Since I am not using Django's form model, how can I create a new user after validating form data? Any insights are appreciated.
You can create new Users in your web app by modifying your views.py as below:
from django.contrib.auth import get_user_model
def signUp(request):
if request.POST:
username = request.POST['username']
email = request.POST['email']
password = request.POST['password']
password_confirm = request.POST['password-confirm']
if(valid_form(username, email, password, password_confirm)) {
user = get_user_model().objects.create(
username=username,
email=email,
)
user.set_password(password)
user.save()
} else {
#send some error message
}
return render(request, 'index.html')