pass data from database in httpresponse redirect - django

Am new to django framework,am just trying to create seperate login form other than administrator login.I need to authenticate a user using username and password, fetch the details of that user from database and pass that data to a templae (home page) to display it.
My code is as follows:-
view.py:-
def login_user(request):
user = ''
passw = ''
username1 = ''
if request.POST:
user = request.POST.get('username')
passw = request.POST.get('password')
#password1 = ''
try:
userdata = Employee.objects.get(username = user, password = passw)
user_id = request.session["user_id"] = userdata.id
employee_details = Employee.objects.get(id=user_id)
request.session['user_id'] = employee_details.id
return HttpResponseRedirect('/home/', kwargs={'user_id': employee_details.id}))
except Employee.DoesNotExist:
state = "Username or password incorrect !"
return render_to_response('login.html',
{'username' : username1,'state' : state},
context_instance = RequestContext(request))
else:
state = "Please login here:"
return render_to_response('login.html' , {'state' : state} ,
context_instance = RequestContext(request))
i tried using kwargs={'user_id': employee_details.id} but it is not working.How can i pass datas to home page after redirecting?
Thanks

You can not redirect user using POST request. Use GET parameter instead.
In your case the requested data is already stored in session. Just try to read from the session on next request. Django contrib.auth uses user.is_authenticated method for the job.

i tried using kwargs={'user_id': employee_details.id} but it is not working.How can i pass datas to home page after redirecting?
You can:
use session variables
use "get" variables (pass variables encoded in the URL like '/home/?a=1&b=2', see urllib.urlencode)
However you should be using the standard Django user related functions and methods. See "How to log a user in". TLDR:
check credentials: user = authenticate(username=username, password=password)
test if user is not None and any other tests you want (is he active, has some privilege, etc)
mark the request.user as authenticated: login(request, user)

Related

How to update user profile in django properly

i created a form to update a django profile, i use the default user model, when i submit the form and logout and i tried to login again, the new password is not working, but the old one is.
this is my update view :
def edit_profil_to_base(request):
if not request.user.is_authenticated:
return redirect('authentification')
else:
nom_profil_new = request.POST.get('nom_profil')
nom_profil_old = request.user.username
old_mdp = request.POST.get('old_mdp') # type: object
new_mdp = request.POST.get('new_mdp')
final_mdp = request.POST.get('final_mdp')
mdp = request.user.set_password(new_mdp)
if request.user.check_password(old_mdp) and new_mdp == final_mdp:
User.objects.filter(username=nom_profil_old).update(username=nom_profil_new, password=mdp)
logout(request)
return redirect('authentification')
the new_mdp and final_mdp are the new password and the confirmation of the password
You need to use set_password. You can't do this via update, but you don't need to: you already have the actual object, request.user.
user = request.user
if user.check_password(old_mdp) and new_mdp == final_mdp:
user.username = nom_profil_new
user.set_password(mdp)
user.save()
However, you really should be using a ModelForm for all of this.

Django: Check user name from two different models

I have two models: Faculty and Student. Both have a username and password.
I want to check if the username and password input provided is present in either of them. In the view, I can do a simple check on one model like this:
try:
user = Student.objects.get(username=username, password=password)
except Student.DoesNotExist:
error_message = "**Incorrect login. Please try again."
context = {'error_message' : error_message}
return render_to_response('myapp/login.html',context, context_instance=RequestContext(request))
Can you point out how to do the same for both Faculty and Student at the same time?
The simplest way is probably just to try the second query if the first fails:
context = {}
try:
user = Student.objects.get(username=username, password=password)
except Student.DoesNotExist:
try:
user = Faculty.objects.get(username=username, password=password)
except Faculty.DoesNotExist:
error_message = "**Incorrect login. Please try again."
context['error_message'] = error_message
# rest of your view here
return render_to_response('myapp/login.html', context, context_instance=RequestContext(request))
By the way, you can save yourself some effort if you use django.shortcuts.render instead of render_to_response:
from django.shortcuts import render
...
return render(request, 'myapp/login.html', context)
I suggest, you should use custom user model to join your models and classic django auth utils.

Show recaptcha after 3 wrong attemps and process it in Django?

I am using Class-based view with Django: I want to show the captcha only after 3 times and process captcha only after it is shown. Till now, I can only show the captcha after one wrong attempt:
def post(self, request):
response = captcha.submit(
request.POST.get('recaptcha_challenge_field'),
request.POST.get('recaptcha_response_field'),
'[[ MY PRIVATE KEY ]]',
request.META['REMOTE_ADDR'],)
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
state = "The username or password is incorrect."
if user is not None:
login(request, user)
return HttpResponseRedirect('/index/')
else:
#captcha = CaptchaField()
public_key = settings.RECAPTCHA_PUBLIC_KEY
script = displayhtml(public_key=public_key)
return render_to_response('index.html', {'state':state, 'captcha':'captcha', 'script':script}, context_instance=RequestContext(request))
I want to show the captcha after three times and process it using response.is_valid. How can I do this?
The simplest solution is probably to store the number of attempts in a cookie, incrementing it on each failed attempt. Obviously this can be tampered with, which brings me to signed cookies:
https://docs.djangoproject.com/en/dev/ref/request-response/#django.http.HttpRequest.get_signed_cookie
https://docs.djangoproject.com/en/dev/ref/request-response/#django.http.HttpResponse.set_signed_cookie
Essentially a signed cookie will raise an exception if the value has been tampered with.
You can also store the counter in the session, but I don't see any point in prematurely creating a session object when a cookie will do the trick.

Using twython-django to authenticate a user when they submit a form

I'm building a Django app and am trying to use twython-django to authenticate a Twitter user when they submit a form. I have tried to edit my views.py, urls.py and models.py files as suggested by this example https://github.com/ryanmcgrath/twython-django/tree/master/twython_django_oauth but I'm simply guessing at it so I'm sure that's why it isn't working.
Could you please help me out with how to get this working? I'm completely new to Twitter wrappers so any help would very much be appreciated.
The flow I'm trying to achieve:
User submits a message through the form
User is asked to authenticate their Twitter account on hitting "Submit" button
User's message, Twitter name, Twitter screen_name, profile_image_url and followers_count are saved in the database (I'm using Heroku Postgres)
User's profile image, name, screen_name and message are printed to index.html in a (Twitter-like) feed.
My views.py:
def logout(request, redirect_url=settings.LOGOUT_REDIRECT_URL):
django_logout(request)
return HttpResponseRedirect(request.build_absolute_uri(redirect_url))
def submit(request):
twitter = Twython(
twitter_token=settings.TWITTER_KEY,
twitter_secret=settings.TWITTER_SECRET,
callback_url=request.build_absolute_uri(reverse('alpha.views.submit'))
)
auth_props = twitter.get_authentication_tokens()
request.session['request_token'] = auth_props
return HttpResponseRedirect(auth_props['auth_url'])
form = MessageForm(request.session.get('message'))
if form.is_valid():
new_message = form.save()
return HttpResponseRedirect('/')
else:
request.session['message'] = request.POST
twitter = Twython(
twitter_token = settings.TWITTER_KEY,
twitter_secret = settings.TWITTER_SECRET,
oauth_token = request.session['request_token']['oauth_token'],
oauth_token_secret = request.session['request_token']['oauth_token_secret'],
)
authorized_tokens = twitter.get_authentication_tokens()
try:
user = User.objects.get(username = authorized_tokens['screen_name'])
except User.DoesNotExist:
user = User.objects.create_user(authorized_tokens['screen_name'], authorized_tokens['oauth_token_secret'])
profile = Message()
profile.user = user
profile.name = name
profile.profile_image_url = profile_image_url
profile.oauth_token = authorized_tokens['oauth_token']
profile.oauth_secret = authorized_tokens['oauth_token_secret']
profile.save()
user = authenticate(
username = authorized_tokens['screen_name'],
password = authorized_tokens['oauth_token_secret']
)
login(request, user)
return HttpResponseRedirect(redirect_url)
Disclaimer: I'm a newbie so the above code is probably a complete mess!
Yes, your use-case is different from that intended by twython-django, but that doesn't mean it's not going to work in your case, and you can use the library as it stands with your flow. After setting up everything as described on the main page, you'll need something like this for your views.py:
from django.shortcuts import redirect, reverse
def submit(request):
# initial form submission, first check if we're authenticated
# if we are, process as normal, otherwise redirect to the login
# page. If you've set up twython-django correctly, it'll redirect
# to twitter for the actual login.
if request.method == "POST":
if request.user.is_authenticated():
form = MessageForm(request.POST)
if form.is_valid():
form.save()
return redirect('/')
else:
# Modify this to display validation errors
pass
else:
request.session['message'] = request.POST
# the reverse(submit) resolves this view for redirection
# back from the twitter authentication
return redirect(settings.LOGIN_URL, next=reverse(submit))
# A Get request, where we should first check for the message stored
# We then process the form and remove it from session to prevent
# accidental re-use.
else:
if 'message' in request.session and request.user.is_authenticated():
form = MessageForm(request.session['message'])
del request.session['message']
if form.is_valid():
form.save()
return redirect('/')
else:
# Modify this to display validation errors
pass
else:
# handle the case where this is a get request and the variable
# isn't in session
pass
As for loading their profile image and follower count, those are not currently handled at all by twython django. You can either fork it on github and add them to the TwitterProfile model and add the appropriate code to the thanks view to load those too, or you can add a new model to your code which extends TwitterProfile.
from twython_django_oauth.models import TwitterProfile
from django import models
class ExtendedTwitterProfile(models.Model)
profile = models.OneToOne(TwitterProfile, related_name="extended")
avatar = models.CharField(max_length=255)
followers = models.IntegerField()
And add the code into the submit view to add/update the profile as needed.
extended_profile = ExtendedTwitterProfile.objects.get_or_create(profile=request.user.twitterprofile)
extended_profile.avatar = avatarurl
extended_profile.followers = followercount
extended_profile.save()
You should be able to access those details via
user.twitterprofile.extended.avatar
Although, I have in the past used a url to get the avatar, for example:
# avatar redirection urls
url(r'^avatar/(?P<userid>[0-9A-Za-z_]+)$', redirect_to,
{ 'url' : 'http://api.twitter.com/1/users/profile_image/%(userid)s.json' }, name='avatar' ),
url(r'^avatar/(?P<userid>[0-9A-Za-z_]+)/(?P<size>[a-z]+)$', redirect_to,
{ 'url' : 'http://api.twitter.com/1/users/profile_image?screen_name=%(userid)s&size=%(size)s' } ),
In a template where you want to display the avatar, you simply use and img tag using the url template tag to do the reverse url resolution, like so:
<img src="{% url avatar userid=request.user.username %}" />
As a further pointer, you can also request all of the users' basic details via Twitter's json API
https://twitter.com/users/zandeez.json
For example, will get you my public profile in a form you can use either in python using urllib or even javascript/ajax depending on what you want to do with the follower count.
Hopefully that should get you sorted, if you need any more help fell free to ask.

django testing problems

This is my view that I want to be tested.
def logIn(request):
"""
This method will log in user using username or email
"""
if request.method == 'POST':
form = LogInForm(request.POST)
if form.is_valid():
user = authenticate(username=form.cleaned_data['name'],password=form.cleaned_data['password'])
if user:
login(request,user)
return redirect('uindex')
else:
error = "Nie prawidlowy login lub haslo.Upewnij sie ze wpisales prawidlowe dane"
else:
form = LogInForm(auto_id=False)
return render_to_response('login.html',locals(),context_instance=RequestContext(request))
And here's the test
class LoginTest(unittest.TestCase):
def setUp(self):
self.client = Client()
def test_response_for_get(self):
response = self.client.get(reverse('logIn'))
self.assertEqual(response.status_code, 200)
def test_login_with_username(self):
"""
Test if user can login wit username and password
"""
user_name = 'test'
user_email = 'test#test.com'
user_password = 'zaq12wsx'
u = User.objects.create_user(user_name,user_email,user_password)
response = self.client.post(reverse('logIn'),data={'name':user_name,'password':user_password},follow=True)
self.assertEquals(response.request.user.username,user_name)
u.delete()
And when i run this test i got failure on test_login_with_username:
AttributeError: 'dict' object has no attribute 'user'
When i use in views request.user.username in works fine no error this just fails in tests. Thanks in advance for any help
edit:Ok I replace the broken part with
self.assertEquals(302, response.status_code)
But now this test breaks and another one too.
AssertionError: 302 != 200
Here is my code for the view that now fail. I want email and username to be unique.
def register(request):
"""
Function to register new user.
This function will have to care for email uniqueness,and login
"""
if request.method == 'POST':
error=[]
form = RegisterForm(request.POST)
if form.is_valid():
username = form.cleaned_data['username']
email = form.cleaned_data['email']
if form.cleaned_data['password'] == form.cleaned_data['password_confirmation']:
password = form.cleaned_data['password']
if len(User.objects.filter(username=username)) == 0 and len(User.objects.filter(email=email)) == 0:
#email and username are bouth unique
u = User()
u.username = username
u.set_password(password)
u.email = email
u.is_active = False
u.is_superuser = False
u.is_active = True
u.save()
return render_to_response('success_register.html',locals(),context_instance=RequestContext(request))
else:
if len(User.objects.filter(username=username)) > 0:
error.append("Podany login jest juz zajety")
if len(User.objects.filter(email=email)) > 0:
error.append("Podany email jest juz zajety")
else:
error.append("Hasla nie pasuja do siebie")
#return render_to_response('register.html',locals(),context_instance=RequestContext(request))
else:
form = RegisterForm(auto_id=False)
return render_to_response('register.html',locals(),context_instance=RequestContext(request))
And here is the test that priviously work but now it is broken
def test_user_register_with_unique_data_and_permission(self):
"""
Will try to register user which provided for sure unique credentials
And also make sure that profile will be automatically created for him, and also that he he have valid privileges
"""
user_name = 'test'
user_email = 'test#test.com'
password = 'zaq12wsx'
response = self.client.post(reverse('register'),{'username': user_name,'email':user_email,
'password':password,'password_confirmation':password},follow=True)
#check if code is 200
self.assertEqual(response.status_code, 200)
u = User.objects.get(username=user_name,email = user_email)
self.assertTrue(u,"User after creation coudn't be fetched")
self.assertFalse(u.is_staff,msg="User after registration belong to staff")
self.assertFalse(u.is_superuser,msg="User after registration is superuser")
p = UserProfile.objects.get(user__username__iexact = user_name)
self.assertTrue(p,"After user creation coudn't fetch user profile")
self.assertEqual(len(response.context['error']),0,msg = 'We shoudnt get error during valid registration')
u.delete()
p.delete()
End here is the error:
AssertionError: We shoudnt get error during valid registration
If i disable login test everything is ok. How this test can break another one? And why login test is not passing. I try it on website and it works fine.
The documentation for the response object returned by the test client says this about the request attribute:
request
The request data that stimulated the response.
That suggests to me one of two things. Either it's just the data of the request, or it's request object as it was before you handled the request. In either case, you would not expect it to contain the logged in user.
Another way to write your test that the login completed successfully would be to add follow=False to the client.post call and check the response code:
self.assertEquals(302, response.status_code)
This checks that the redirect has occurred.
response.request is not the HttpRequest object in the view you are expecting. It's a dictionary of data that stimulated the post request. It doesn't have the user attribute, hence the AttributeError
You could rewrite your test to:
use the RequestFactory class introduced in Django 1.3 and call logIn in your test directly instead of using client.post.
inspect client.session after the post to check whether the user has been logged in.
Why one failing test can break another
When you edited the question, you asked
How this test can break another one?
The test_login_with_username was failing before it reached u.delete, so the user created in that test was not deleted. That caused test_user_register_with_unique_data_and_permission because the user test already existed.
If you use the django.test.TestCase class, the database will be reset in between each test, so this wouldn't be a problem.