In my app I am getting an error when trying to update a user info.
my code is the following:
def CandidateSignIn(request, uidb64, token):
try:
uid = force_text(urlsafe_base64_decode(uidb64))
user = MyUser.objects.get(pk=uid)
except(TypeError, ValueError, OverflowError, User.DoesNotExist):
user = None
if user is not None and account_activation_token.check_token(user, token):
user.is_active = True
user.save()
login(request, user)
registered = False
if request.method == "POST":
form = TeamMembersFormUpdate(data=request.POST, instance=request.user)
if form.is_valid():
user = form.save()
user.set_password(user.password)
user.save()
#registered = True
return HttpResponseRedirect(reverse('registration:HRlogin'))
else:
print("Error!")
else:
form = TeamMembersFormUpdate()
return render(request,'candidateSignIn.html',
{'form':form,
'registered':registered})
and apparently I am getting the error from the line
form = TeamMembersFormUpdate(data=request.POST, instance=request.user)
do you have any idea on how to solve this ?
You are logging the user in at line
11: login(request, user)
but the middleware will not be updated unless you return from the view you are in so you are getting the same anonymous user instance
so you just replace the request.user with 'user' that you got in the line 4
It will do thing right
...
if request.method == "POST" and user:
form = TeamMembersFormUpdate(data=request.POST, instance=user)
#rest here
#if you have no such user
else:
form = TeamMembersFormUpdate()
return render(request,'candidateSignIn.html',
{'form':form,
'registered':registered})
Related
I want to show user validation error but seems that this is not working in my login form here is the code
my forms.py
class LoginForm(forms.Form):
username = forms.CharField(widget=forms.TextInput())
password = forms.CharField(widget=forms.PasswordInput())
remember_me = forms.BooleanField(required=False, label='Remember Me',help_text='Keep me logged in.',widget=forms.CheckboxInput())
def clean(self, *args, **kwargs):
username = self.cleaned_data.get("username")
password = self.cleaned_data.get("password")
if username and password:
user = authenticate(username=username, password=password)
if not user:
raise forms.ValidationError("This user doesn't exist")
if not user.check_password(password):
raise forms.ValidationError("Incorrect Password")
if not user.is_active:
raise forms.ValidationError("User no longer Active")
return super(LoginForm,self).clean(*args,**kwargs)
my views.py for login
def my_login(request):
if 'next' in request.GET:
messages.add_message(request, messages.WARNING, 'To Continue, Please login here!')
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
username = form.cleaned_data["username"]
password = form.cleaned_data["password"]
remember_me = form.cleaned_data['remember_me']
user = authenticate(username=username, password=password)
if user:
login(request, user)
if not remember_me:
request.session.set_expiry(0)
return redirect('accounts:home')
else:
request.session.set_expiry(1209600)
return redirect('accounts:home')
else:
messages.info(request, 'Please check your credentials.')
return redirect('accounts:login')
else:
form = LoginForm()
return render(request, "login.html", {'form': form})
i know i am redirecting the form if form credential is wrong but if i don't i will throw error didn't return a httpresponse it return none instead also want to what is the best way to redirect or show exact validation error of which credential is wrong
i don't want user have to see this message without any error i load page this come automatically here is my views.py
def my_login(request):
form = LoginForm(request.POST)
if form.is_valid():
username = form.cleaned_data["username"]
password = form.cleaned_data["password"]
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
return redirect('accounts:home')
else:
return HttpResponse('<h1>Page was found</h1>')
else:
return render(request, "login.html", {'form': form})
my forms.py
class LoginForm(forms.Form):
username = forms.CharField()
password = forms.CharField(widget=forms.PasswordInput)
def clean(self, *args, **kwargs):
username = self.cleaned_data.get("username")
password = self.cleaned_data.get("password")
if username and password:
user = authenticate(username=username, password=password)
if not user:
raise forms.ValidationError("User does not exist.")
if not user.is_active:
raise forms.ValidationError("User is no longer active.")
return super(LoginForm, self).clean(*args, **kwargs)
You need to submit your form only when you receive a POST request.
def my_login(request):
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
# process form here
else:
form = LoginForm()
# send form to template
You will find more info about this in the documentation.
I know this question have been asked alot and most of the time its due to render or HttpResponse in the views.py, i double checked mine but the code looks good to me, dont know where the problem is.
This is a views.py file for a very basic django form but i can't get it to work
def register(request):
registered = False
if request.method == 'POST':
user_form = UserForm(data = request.POST)
profile_form = UserProfileInfoForm(data = request.POST)
if user_form.is_valid() and profile_form.is_valid():
user = user_from.save()
user.set_password(user.password)
user.save()
profile = profile_form.save(commit = False)
profile.user = user
if 'profile_pic' in request.FILES:
profile.profile_pic = request.FILES['profile_pic']
profile.save()
registered = True
else:
return (user_form.errors,profile_form.errors)
else:
user_form = UserForm()
profile_form = UserProfileInfoForm()
return render(request,'basic_app/register.html',{'user_form': user_form,
'profile_form':profile_form,
'registered':registered})
You can not return (user_form.errors, profile_form.errors), since that is not a HttpResponse object. What response should the server return in that case.
Usually in case the form is invalid, the server will rerender the content. The form will, if you render it properly display the errors.
Note that in case the POST request was successful, you usually should redirect to implement the Post/Redirect/Get pattern [wiki]. You furthermore probably want to use a UserCreationForm [Django-doc]. This will set the password of the user in the correct way (with .set_password(..)), and run a password validator if you configured this.
You thus can rewrite your view as follows, but you probably should replace UserForm with UserCreationForm:
from django.shortcuts import redirect
def register(request):
if request.method == 'POST':
user_form = UserForm(data=request.POST)
profile_form = UserProfileInfoForm(data=request.POST)
if user_form.is_valid() and profile_form.is_valid():
user = user_from.save(commit=False)
user.set_password(user.password)
user.save()
profile = profile_form.save(commit=False)
profile.user = user
if 'profile_pic' in request.FILES:
profile.profile_pic = request.FILES['profile_pic']
profile.save()
return redirect('name-of-view')
else:
user_form = UserForm()
profile_form = UserProfileInfoForm()
return render(
request,
'basic_app/register.html',
{'user_form': user_form, 'profile_form':profile_form })
I'm new to django. I created a signup from from which data will be saved in the database at the time of login. It shows:
Please enter a correct username and password.
Note that both fields may be case-sensitive.
views.py:
def register(request):
registered = False
if request.method == 'POST':
form = signupform(request.POST,request.FILES)
if form.is_valid():
form.save()
if 'photo' in request.FILES:
form.picture = request.FILES['photo']
form.save()
return redirect("/accounts/login")
registered = True
else:
print(form.errors)
else:
form=signupform()
return render(request,'testApp/singup.html',{'registered':
registered,'form':form})
def user_login(request):
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user:
if user.is_active:
login(request, user)
return HttpResponseRedirect('/home/')
else:
return HttpResponse("Your 3010 account is disabled.")
else:
print("Invalid login details: {0}, {1}".format(username,password))
return HttpResponse("Invalid login details supplied.")
else:
return render(request, 'testapp/login.html', {})
To be able to manipulate your form instance, you need to "false save" your form before you make any changes to it.
You can do this via form = form.save(commit=False), that way you create a mutable instance of your form, which you can use to save your form data later after doing other manipulations or updating.
Also, you save the form instance after you have done all the manipulations.
def register(request):
registered = False
if request.method == 'POST':
form = signupform(request.POST,request.FILES)
signup_form = form.save(commit=False)
if signup_form.is_valid():
if 'photo' in request.FILES:
signup_form.picture = request.FILES['photo']
signup_form.save()
return redirect("/accounts/login")
registered = True
else:
print(form.errors)
else:
form=signupform()
return render(request,'testApp/singup.html',{'registered':
registered,'form':form})
I am trying to sigin my user in, the error I keep getting is an AttributeError: AnonymousUser' object has no attribute '_meta'.
I am following the documentation from Django on how to log a user in, have tried that but I keep getting the error.
https://docs.djangoproject.com/en/2.2/topics/auth/default/#django.contrib.auth.login
view.py
def signin(request):
if request.method == 'GET':
return render(request, 'auth/signin.html', { })
if request.method == 'POST':
form = SigninForm(request.POST)
if form.is_valid():
username = request.POST["username"]
password = request.POST["password"]
user = authenticate(request, username=username, password=password)
if user is None:
login(request, user)
return HttpResponseRedirect('/')
else:
return HttpResponse('Invalid Credientials', status=401 )
else:
return HttpResponse("Form is not valid", status=401)
What I want is the user to signin but I keep getting the attribute error.
I think the problem is here:
if user is None: # <--
login(request, user)
It should be:
if user is not None:
login(request, user)