After creating a UserProfile model. I started to create login but I'm stuck because of get_user() error.
EXCEPTION
AttributeError: 'LoginForm' object has no attribute 'get_user'
Here are my codes:
UPDATE
class LoginView(FormView):
form_class = LoginForm
redirect_field_name = REDIRECT_FIELD_NAME
template_name = 'login.html'
success_url = '/'
def form_valid(self, form):
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(self.request, user)
return HttpResponseRedirect(self.get_success_url())
else:
return self.form_invalid()
def form_invalid(self):
return HttpResponseRedirect(reverse('accounts:login'))
def get_success_url(self):
if self.success_url:
redirect_to = self.success_url
else:
redirect_to = self.request.REQUEST.get(self.redirect_field_name, '')
netloc = urlparse.urlparse(redirect_to)[1]
if not redirect_to:
redirect_to = settings.LOGIN_REDIRECT_URL
elif netloc and netloc != self.request.get_host():
redirect_to = settings.LOGIN_REDIRECT_URL
return redirect_to
def post(self, request, *args, **kwargs):
form_class = self.get_form_class()
form = self.get_form(form_class)
if form.is_valid():
return self.form_valid(form)
else:
return self.form_invalid()
How to fix this? Any help would be appreciated. I'm really new on Django 1.5. Need help.
[update]
In the original code, the author is doing the authenticate stuff inside a form method called get_user. You are doing it outside the form already, so just replace form.get_user()with user.
I use a login view that is not class based, and I don't even care into using a Django form instance, but it should be easy to adapt:
def signin(request):
if request.method == 'POST':
user = authenticate(
email=request.POST.get('username', '').lower().strip(),
password= request.POST.get('password', ''),
)
if user is None:
messages.error(request, u'Invalid credentials')
else:
if user.is_active:
login(request, user)
return HttpResponseRedirect(request.GET.get('next', '/'))
else:
messages.error(request, u'User is not active.')
return render_to_response('login.html', locals(),
context_instance=RequestContext(request))
[old answer]
Define a get_user method for your form.
Untested (but should get you in the right path):
def get_user(self):
from django.contrib.auth import authenticate
return authenticate(
email=self.cleaned_data.get('username', '').lower().strip(),
password=self.cleaned_data.get('password', ''),
)
Related
Why when i desactive user on Django admin site in my class in post method
requirement return negative first if requirement user is not None ?
Probably if user desative true Django don`t look him in user table ?
class LoginView(View):
template_name = 'login.html'
def get(self, request):
form = LoginForm()
return render(request, self.template_name, locals())
def post(self, request):
form = LoginForm(request.POST)
if form.is_valid():
username = form.cleaned_data.get('username')
password = form.cleaned_data.get('password')
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
return redirect('home')
else:
alert = messages.error(request, 'Twoje konto zostało zablokowane!')
return render(request, self.template_name, locals())
else:
alert = messages.error(request, 'Błędna nazwa użytkownika!')
return render(request, self.template_name, locals())
In authenticate function, django call authenticate on your AUTHENTICATION_BACKENDS in settings.py.
ModelBackend is a default authentication backend that has been provided by Django, and if you are using it, it checks if user is acive or not. It's sth like this:
def user_can_authenticate(self, user):
"""
Reject users with is_active=False. Custom user models that don't have
that attribute are allowed.
"""
is_active = getattr(user, 'is_active', None)
return is_active or is_active is None
I am create a application where admin and customer login same browser.
I read many blog not able not fix my problem. As Django use session based login.
I am facing issue while logout my admin then my customer automatic logout. maybe session based functionally
My admin LoginView and Logoutview:
class AdminLoginView(SuccessMessageMixin,LoginView):
authentication_form = LoginForm
template_name = 'login.html'
redirect_field_name = reverse_lazy('admin_panel:dashboard')
redirect_authenticated_user = False
success_message = '%(username)s login Successfully !'
def dispatch(self, *args, **kwargs):
if self.request.user.is_authenticated:
# messages.info(self.request, f"{self.request.user.firstname} is already Logged In")
return redirect('/admin/dashboard/')
return super().dispatch(*args, **kwargs)
def get_success_url(self):
url = self.get_redirect_url()
LOGIN_REDIRECT_URL = reverse_lazy('admin_panel:dashboard')
return url or resolve_url(LOGIN_REDIRECT_URL)
class LogoutView(LogoutView):
"""
Log out the user and display the 'You are logged out' message.
"""
next_page = "/admin/login"
def dispatch(self, request, *args, **kwargs):
response = super().dispatch(request, *args, **kwargs)
messages.add_message(request, messages.INFO,'Successfully logged out.')
return response
I have implemented customer based login & logout
def LoginView(request):
form = LoginForm(request.POST or None)
if form.is_valid():
username = form.cleaned_data["username"]
password = form.cleaned_data["password"]
remember_me = form.cleaned_data["remember_me"]
user = User.objects.get(email=username)
if user and user.check_password(password):
if user.is_active:
if remember_me == False:
request.session.set_expiry(0)
request.session['user_id'] = user.id
request.session['username'] = user.email
return HttpResponseRedirect('/')
else:
context = {'auth_error': "You're account is disabled"}
return render(request, 'forntend-signin.html', context )
else:
context = {
'auth_error': 'username and password incorrect'
}
return render(request, 'forntend-signin.html', context)
else:
context = {
"form": form
}
return render(request, 'forntend-signin.html', context)
def customer_logout(request):
try:
if request.session['username']:
del request.session['user_id']
del request.session['username']
else:
del request.session['user_id']
except KeyError:
HttpResponseRedirect("/")
return HttpResponseRedirect("/")
Please suggest me how to fix this issue.
If there any documentation available the please share.
As the title explains, although I'm successfully logged in, I can't prevent the application from going back to the login page if I entered the path to the page in URL bar.
NOTE:I'm not using the built-in user or authentication classes.
Here is the code below:
class user_login_view(View):
form_class = LoginForm
template_name = 'main/login.html'
def get(self, request):
form = self.form_class(None)
return render(request, self.template_name, {'form': form})
def post(self, request):
form = self.form_class(request.POST)
username = request.POST['username']
password = request.POST['password']
if form.is_valid:
try:
member = user.objects.filter(username=username).first()
except user.DoesNotExist:
member = None
if member != None and member and member.password == password:
request.session['username'] = username
return redirect('main:index')
else:
messages.error(request,'account does not exist')
return render(request, self.template_name,{'form': form})
else:
messages.error(request, 'account does not exist')
return render(request, self.template_name,{'form': form})
def index(request):
template_name = 'main/loggedin.html'
if request.session.has_key('username'):
username = request.session['username']
return render(request, template_name, {"username" : username})
else:
return HttpResponseRedirect(reverse('main:login'))
def logout(request):
try:
del request.session['username']
except:
pass
return HttpResponseRedirect(reverse('main:login'))
I create models,forms and views for registrarion and i want to create a login view so that after registration user can login.
models.py
from django.contrib.auth.models import AbstractUser
from django_countries.fields import CountryField
g_CHOICES = (('male','male'),('female','female'))
class User(AbstractUser):
gender = models.CharField(max_length=100,choices=g_CHOICES,default="male")
country = CountryField()
location = models.CharField(max_length=30, blank=True)
forms.py
g_CHOICES = (('male','male'),('female','female'))
class UserRegisterForm(UserCreationForm):
email = forms.EmailField()
gender = forms.ChoiceField(choices=g_CHOICES)
country = CountryField().formfield()
location = forms.CharField(max_length=30,)
class Meta:
model = User
fields = ['first_name','last_name','username','email',
'password1','password2','gender',
'country','location']
views.py
def register(request):
if request.method == 'POST':
rform = UserRegisterForm(request.POST)
if rform.is_valid():
rform.save()
username = rform.cleaned_data.get('username')
messages.success(request,('Account created for '+str(username)))
return redirect('/')
else:
rform = UserRegisterForm()
return render(request,'reg.html',{'rform':rform})
Now i want to create a view for login please someone help
You need a view that takes the user's username and password from the POST request, then authenticates them and logs them in using 'authenticate' and 'login' from django.contrib.auth package.
from django.contrib.auth import login, authenticate
from django.views import View
class HandleLogin(View):
def get(self, request):
return render(request, "login.html", {})
def post(self, request):
username= request.POST.get("username")
password = request.POST.get("password")
user = authenticate(username, password)
if user is not None:
if user.is_active:
login(request, user)
# Do something for succesfull logged in
else:
# Do something else because user is not active
else:
# Do something about user not existing
For more information: https://docs.djangoproject.com/en/2.2/topics/auth/default/
You can use something like below one:
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)
messages.success(request, 'You are now logged in')
return redirect('dashboard')
else:
messages.error(request, 'Invalid credentials')
return redirect('login')
else:
return render(request, 'accounts/login.html')
Or if you are using a django form you can do this way too and this is more preferred way:
def user_login(request):
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
user = authenticate(request,
username=cd['username'],
password=cd['password'])
if user is not None:
login(request, user)
return HttpResponse('Authenticated '\
'successfully')
else:
return HttpResponse('Invalid login')
else:
form = LoginForm()
return render(request, 'account/login.html', {'form': form})
So I am working on user authentication, login, logout. I am getting the error when I am opening the registration portal.
AttributeError at /profile/
'User' object has no attribute 'get_profile'
Following is my views.py
def Registration(request):
if request.user.is_authenticated:
return HttpResponseRedirect('/profile/')
if request.method == 'POST':
form = UserRegistrationForm(request.POST)
if form.is_valid():
user = User.objects.create_user(username = form.cleaned_data['username'],email = form.cleaned_data['email'] , password = form.cleaned_data['password'])
user.save()
UserProfile= UserProfile(user=user, birth_date=form.cleaned_data['birth_date',])
UserProfile.save()
return HttpResponseRedirect('/profile/')
else:
return render('visit/registration/register.html', {'form': form},)
else:
form= LoginForm()
context = {'form': form}
return render(request, 'visit/registration/register.html', context )
#login_required
def Profile(request):
if not request.user.is_authenticated:
return HttpResponseRedirect('/login/')
UserProfile = request.user.get_profile()
context ={'UserProfile': UserProfile}
return render(request,'visit/profile.html', context)
def LoginRequest(request):
if request.user.is_authenticated:
return HttpResponseRedirect('/profile')
if request.method == 'POST':
form = LoginRequest(request.POST)
if form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['password']
UserProfile = authenticate(username=username, password=password)
if UserProfile is not None:
login(request, UserProfile)
return HttpResponseRedirect('/profile/')
else:
return render(request,'visit/registration/login.html',{'form':form})
else:
return render(request, 'visit/registration/login.html', {'form': form})
else:
form= LoginForm()
context = {'form': form}
return render(request, 'visit/registration/login.html', context, )
def logoutRequest(request):
logout(request)
return render(request, 'visit/login.html')
def index(request):
return render(request, 'visit/index.html', context=None)
I am not sure what/where the error is. I am using the Django 2.0.2.
I know there are similar questions but I am not getting the proper solution.
Help would be appricated. Following is my settings.py
#provides our get_profile
AUTH_PROFILE_MODULE = 'visit.model.UserProfile'
# URL for #login required
LOGIN_URL = '/login/'
#redirect authenticated user
LOGIN_REDIRECT_URL = '/profile/'
As per #neverwalker comment, this method is deprecated 1.7. please refer below code
user_profile = UserProfile.objects.get(activation_key='some_key')
user = user_profile.user