first excuse me for my english it isn't the best one.
I'm pretty new to django and python and i try to programm a user authen开发者_JAVA百科tification. I used the django documentation and everything works fine with these code below:
def anges(request):
username = []
password = []
if request.method == "POST":
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
render_to_response ('registration/login.html', {'username': username, 'password': password})
if user is not None:
if user.is_active:
login(request, user)
angestellte_list = Employee.objects.all().order_by('lastname')
return render_to_response(("emp/angestellte.html"), {'angestellte_list': angestellte_list})
else:
return HttpResponse('disabled account')
else:
return HttpResponse('invalid login')
else:
return render_to_response ('registration/login.html', {'username':username, 'password':password})
But this is just a function and i want to use this object oriented for my other functions in my views.py, because of DRY. This is just a first test but it doesn't works because the debugger says:"global name 'request' is not defined" That's my code:
class einloggen:
def __init__(self):
self.Username = request.POST['username']
def angestellte(self):
return HttpResponse("hello")
How can I use the request variable in classes or is there anything more to consider?
Quite obvious that you can't use the request
variable in __init__
in the einloggen
class, because, quite frankly, you don't send the request variable in to the constructor.
I can't see you making a einloggen
object anywhere in your view either, but you should probably to something like:
class einloggen:
def __init__(self, request):
self.Username = request.POST.get('username')
and then in your view (where you've got the request variable):
def anges(request):
myobj = einloggen(request)
However, Django already has an authentication system. And you'd be much better off using that. You can use the beautiful decorators to make it really easy and nice to «protect» views.
精彩评论