How to fix AssertionError 200!=302 - django

I got a registration view that registers new users, logs them in and then redirects them to home page. When I am testing this view using unittest I am getting an AssertionError 200!=302
views.py :
def register(request):
if request.method =='POST':
form = RegistrationForm(request.POST)
if form.is_valid():
user=form.save()
username = request.POST.get('username')
password = request.POST.get('password1')
login(request, user)
return redirect(reverse('home:home'))
else:
form = RegistrationForm()
args = {'form': form}
return render(request, 'accounts/reg_form.html', args)
test_views.py:
class TestViews(TestCase):
def setUp(self):
self.client = Client()
self.burial=User.objects.create_user(
username='burial',
password='secret'
)
def test_registration_view(self):
url = reverse('accounts:register')
response = self.client.post(url, {
'username': self.burial.username,
'password': self.burial.password
})
self.client.login(username=self.burial.username,
password=self.burial.password)
self.assertEquals(self.burial.username, 'burial')
self.assertEquals(response.status_code, 302)
I am getting AssertionError 200!=302
Thank you for any help.

Related

Django testing view with pytest

Could you please helpe me debugging this test? I got this error (I don't know whay since, I
have no pk in view): django.contrib.auth.models.User.DoesNotExist: User matching query does not exist.I think the error is due to pk=request.user.id passed as argument in User objects in the view function.
class TestViews(TestCase):
def setUp(self):
self.client = Client()
self.create_campaign_naming_tool_url = reverse('create_campaign_naming_tool')
self.user = User.objects.create_user(
username = 'admin',
email = 'admin#sigma.fr',
password = '1234'
)
def test_create_campaign_naming_tool(self):
response = self.client.get(self.create_campaign_naming_tool_url)
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, 'form.html')
Here is my view
def create_campaign_naming_tool(request):
current_user = User.objects.get(pk=request.user.id)
form = CampaignNamingToolForm(initial={'user': current_user})
context = {
'form': form,
}
if request.method == 'POST':
campaign = CampaignNamingTool(user=current_user)
form = CampaignNamingToolForm(request.POST, instance=campaign)
if form.is_valid():
form.save()
messages.success(request, "Your campaign haven ben\
success fully created.")
return render(request, 'form.html', context)
return render(request, 'form.html', context)
You did not login the user in the test:
class TestViews(TestCase):
def setUp(self):
self.client = Client()
self.create_campaign_naming_tool_url = reverse('create_campaign_naming_tool')
self.user = User.objects.create_user(
username = 'admin',
email = 'admin#sigma.fr',
password = '1234'
)
self.client.login(username='admin', password='1234')
# …
It also makes no sense to do such query to fetch the user: request.user is a User object, so you can work directly with this:
from django.contrib.auth.decorators import login_required
from django.shortcuts import redirect
#login_required
def create_campaign_naming_tool(request):
form = CampaignNamingToolForm(initial={'user': request.user})
if request.method == 'POST':
campaign = CampaignNamingTool(user=request.user)
form = CampaignNamingToolForm(request.POST, instance=campaign)
if form.is_valid():
form.save()
messages.success(request, 'Your campaign has been successfully created.')
return redirect('name-of-some-view')
context = {
'form': form,
}
return render(request, 'form.html', context)
Note: You can limit views to a view to authenticated users with the
#login_required decorator [Django-doc].
Note: In case of a successful POST request, you should make a redirect
[Django-doc]
to implement the Post/Redirect/Get pattern [wiki].
This avoids that you make the same POST request when the user refreshes the
browser.

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)

Why am I getting this error in django project ?`

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

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