Why am I getting this error in django project ?` - django

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

Related

How to prevent going to login page while loggedin in django

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'))

ValueError: The view accounts.views.register didn't return an HttpResponse object. It returned None instead. When attempting to register user

When attempting to register a user (after changing my project from default user model to custom user model) I get this value error. The following is my View.
def register(request):
if request.method =='POST':
form = RegisterForm(request.POST)
if form.is_valid():
form.save()
email= request.POST.get('email')
password = request.POST.get('password1')
user = authenticate(
request,
email=email,
password=password,
)
login(request, user)
return redirect(reverse('accounts:view_profile'))
else:
form = RegisterForm()
args = {'form': form}
return render(request, 'accounts/reg_form.html', args)
Try it like this:
def register(request):
form = RegisterForm(request.POST or None)
if request.method =='POST':
if form.is_valid():
form.save()
email= request.POST.get('email')
password = request.POST.get('password1')
user = authenticate(
request,
email=email,
password=password,
)
login(request, user)
return redirect(reverse('accounts:view_profile'))
args = {'form': form}
return render(request, 'accounts/reg_form.html', args)

Login not working in Django

I'm trying to login but Django is not allowing the navigation to the profile.html
This is what I have so far
views.py
def login(request):
if request.method == 'POST':
form = UserLoginForm(request.POST)
if form.is_valid():
userObj = form.cleaned_data
print(userObj)
username = userObj['username']
password = userObj['password']
user = authenticate(username=username, password=password)
if user is not None:
print("in login")
login(request)
return render(request, 'profiles.html', {'form': form})
else:
return render(request, 'login_form.html', {'form': form})
else:
return render(request, 'login_form.html')
forms.py
class UserLoginForm(forms.Form):
username = forms.CharField(
required=True,
label='Username',
max_length=32
)
password = forms.CharField(
required=True,
label='Password',
max_length=32,
widget=forms.PasswordInput()
)
Check This Code I have done login Register
https://github.com/gowthamand/django-1.11.5-crud-ajax-login-register
I used Inbuilt Login
I think that you need to pass the user to login function
from django.contrib.auth import authenticate, login as f_login
def login(request):
if request.method == 'POST':
form = UserLoginForm(request.POST)
if form.is_valid():
userObj = form.cleaned_data
print(userObj)
username = userObj['username']
password = userObj['password']
user = authenticate(username=username, password=password)
if user is not None:
print("in login")
f_login(request, user)
return render(request, 'profiles.html', {'form': form})
else:
return render(request, 'login_form.html', {'form': form})
else:
return render(request, 'login_form.html', {'form': form})

Redirect to home as a logged in user after successful registration

I have a custom User model (MyUser), and a registering form (UserCreationForm) for that model. After registering the user I want it to redirect to the homepage. It is however redirecting to the homepage, but the problem is that the user is not logged in even after login() function is used in the register view, and so it is redirected back to the login page.
views.py:
#login_required(login_url='/account/login/')
def home(request):
return render(request, 'home.html')
def login_view(request):
form = LoginForm(request.POST or None)
if request.POST and form.is_valid():
user = form.login(request)
if user:
login(request, user)
return redirect("/")# Redirect to a success page.
return render(request, 'login.html', {'form': form })
def register(request):
if request.method == "POST":
form = UserCreationForm(request.POST)
if form.is_valid():
user = form.save()
login(request, user)
return redirect("/")
else:
form = UserCreationForm()
return render(request, 'register.html', {
'form': form
})
Its giving me an error:
AttributeError at /account/register/
'MyUser' object has no attribute 'backend'
What am I doing wrong here? Please help me how to solve this. Thank you.
Maybe, this can solve your problem.
This will authenticate and login the user after registration.
def register(request):
if request.method == "POST":
form = UserCreationForm(request.POST)
if form.is_valid():
user = form.save()
password = self.request.POST.get('password', None)
authenticated = authenticate(
username=user.username,
password=password
)
if authenticated:
login(request, authenticated)
return redirect("/")
else:
form = UserCreationForm()
return render(request, 'register.html', {
'form': form
})

views.log_in didn't return an HttpResponse object

Whenever a user enters a blank password (or username) and login, it shows this error:
ValueError at /
The view views.log_in didn't return an HttpResponse object.
code:
def log_in(request):
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
user = form.cleaned_data['username']
pword = form.cleaned_data['password']
user = authenticate(username=user, password=pword)
if user is not None:
login(request, user)
if request.GET.get('next') is not None:
return HttpResponseRedirect(request.GET.get('next'))
else:
return HttpResponseRedirect('/home/')
else:
return render(request, 'login.html', { 'logform': form, 'error': True})
else:
if request.user.is_authenticated():
return HttpResponseRedirect('/home/')
else:
form = LoginForm()
return render(request, 'login.html', { 'logform': form, })
How would I fix this error? Thanks.
You have no return value when the form is invalid. The usual choice is to de-indent the return render(... line so that executes any time none of your redirects are triggered, rendering the invalid form with its errors:
def log_in(request):
if request.method == 'POST':
# as above
else:
if request.user.is_authenticated():
return HttpResponseRedirect('/home/')
else:
form = LoginForm()
return render(request, 'login.html', { 'logform': form, })