Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django getting current user id

i have a mini app where users can login, view their profile, and follow each other. 'Follow' is a relation like a regular 'friend' relationship in virtual communities, but it is not necessarily reciprocal, meaning that one can follow a user, without the need that the user to be following back that person who follows him. my problem is: if i am a logged in user, and i navigate to a profile X, and push the button follow, how can i take the current profile id ?(current profile meaning the profile that I, the logged in user, am viewing right now.)

the view:

   def follow(request):
      if request.method == 'POST':
    form = FollowForm(request.POST)
    if form.is_valid():
    new_obj = form.save(commit=False)
    new_obj.initiated_by = request.user
    u = User.objects. what here?
    new_obj.follow = u   
    new_obj.save()
    return HttpResponseRedirect('.')    
   else:
       form = FollowForm()     
   return render_to_response('followme/follow.html', {
       'form': form,
       }, 
      context_instance=RequestContext(request))  

thanks in advance!

like image 495
dana Avatar asked Dec 07 '22 03:12

dana


2 Answers

Try request.user.id. But there is a better good practice. let me see.

http://docs.djangoproject.com/en/1.2/topics/db/optimization/ is a good start and is full of good practice. In your case, use request.user.id.

like image 103
dzen Avatar answered Dec 10 '22 12:12

dzen


If you add the user's profile to your form, you can pass it in with your post.

There are a number of ways to do it. You could add a hidden field to your FollowForm (pass in the profile as an instance).

You could do it more manually by inserting a hidden field such as:

<input type="hidden" name="profile_id" value="{{ profile.id }}" />

Then you could change your code above to:

u = User.objects.get(request.POST['profile_id'])

Or, perhaps you already have the profile's user id in your view?

like image 21
Dustin Avatar answered Dec 10 '22 13:12

Dustin