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.
Related
I want to display data taken from my Django models in my html file. So in the code bellow instead of a 0 I want the donation model data. Can someone please help? Thank you! also if anyone knows a easier way please tell me. i can update my question again if anyone needs more details.
Views.py
from django.forms import ModelForm
# Create your views here.
def index(request,*args, **kwargs):
return render(request, "index.html", {} )
#login_required(login_url='/login/')
def myview(request,id):
data= userdetails.objects.get(id=id)
return render(request,'dashboard.html',{'data':data}
def register(request ):
if request.user.is_authenticated:
return redirect('/dashboard/')
else:
form = CreateUserForm()
if request.method == "POST":
form = CreateUserForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
messages.success(request, f'Your account has been successfully created, {username} ')
return redirect('loginpage')
context = {'form': form}
return render(request, "register.html", context )
def loginpage(request):
if request.user.is_authenticated:
return redirect('/dashboard/')
else:
if request.method == 'POST':
username = request.POST.get('username')
password =request.POST.get('password')
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return redirect('/dashboard')
else:
messages.error(request, 'Username OR password is incorrect')
context = {}
return render(request, 'login.html', context)
def logoutuser(request):
logout(request)
return HttpResponseRedirect('/login/')
#login_required(login_url='/login/')
def donate(request):
if request.method == "POST":
title = request.POST['donationtitle']
phonenumber = request.POST['phonenumber']
category = request.POST['category']
quantity = request.POST['quantity']
location = request.POST['location']
description = request.POST['description']
ins = Donation(title = title, phonenumber = phonenumber, category = category, quantity = quantity, location = location, description = description, user=request.user, )
ins.save()
return render(request,'donate.html')
Error:
File "C:\Users\jbtai\coding\GoodDeedWeb\home\views.py", line 30
def register(request ):
^
You need a view that handle that:
def myview(request):
id = request.user.id
data= userderails.objects.get(id=id)
return render(request,'dashboard.html',{'data':data}
Then in your template 'dashboard.html' you could show details:
{{data.donations}}
{{data.points}}
use this url for that view instead of the old one
path('dashboard/',views.myview, name = 'dashboard' ),
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.
i was converting the below function view in class based view :
but the problem was the below login code uses request object . so how to use this request in a form view .
Functional view i wanted to change to class based view :
def login(request):
if request.method == 'GET':
form = UserLoginForm()
elif request.method == 'POST':
form = UserLoginForm(request.POST)
if form.is_valid():
username = form.cleaned_data.get('name')
password = form.cleaned_data.get('password')
user = User.objects.filter(name=username, password=password).first()
if user is not None:
request.session['user'] = username
return redirect('index')
else:
messages.error(request, 'Username or password no matched')
return render(request, 'products_app/login.html', {'form': form})
FormView/class based view of the above code i changed to that gives error :
class Login(FormView):
template_name = 'products_app/login.html'
form_class = UserLoginForm
success_url = reverse_lazy('index')
def form_valid(self, form):
username = form.cleaned_data.get('name')
password = form.cleaned_data.get('password')
user = User.objects.filter(name=username, password=password).first()
if user is not None:
request.session['user'] = username
else:
messages.error(request, 'Username or password no matched')
super().form_valid(form)
here the problem is ,request is not being received unlike in the functional view of above def login(request). so gives error:
module 'django.http.request' has no attribute 'session'
The problem is you are using the request module as stated in the error. What you actually want is the request instance that invoked the class. Your code should be self.request.
I've eliminated all the superfluous code to only show the parts with request.
class Login(FormView):
...
def form_valid(self, form):
...
if user is not None:
self.request.session['user'] = username
else:
messages.error(self.request, 'Username or password no matched')
...
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.
I have already used login class
class LoginForm(forms.Form):
username = forms.CharField()
password = forms.CharField(widget=forms.PasswordInput)
And views file of my app
from .forms import LoginForm
def user_login(request):
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
user = authenticate(username=cd['username'],password=cd['password'])
if user.is_active:
login(request, user)
return HttpResponse('Authenticated!')
else:
return HttpResponse('Disabled account')
else:
form = LoginForm()
return render(request, 'account/login.html', {'form': form})
(hunter) provides email verifier.This is HTTP request example
GET https://api.hunter.io/v2/email-verifier?email=steli#close.io
How to modify my login and views files?
Try to use the code below :
import urllib2
get_request = urllib2.urlopen('https://api.hunter.io/v2/email-verifier?email=' + username)
then the get_request variable will contain a JSON object as mentioned in hunter documentation.
the get_request will be added in after the cd = form.cleaned_data