Skip to content

Instantly share code, notes, and snippets.

@drager

drager/views.py Secret

Created August 1, 2013 17:09
Show Gist options
  • Save drager/a0f732ec9d0f4b7a21fa to your computer and use it in GitHub Desktop.
Save drager/a0f732ec9d0f4b7a21fa to your computer and use it in GitHub Desktop.
Since you will get (1062, "Duplicate entry for key 'friendship_friendshiprequest_from_user_id_") you should add some validation for that. I made a simple view to show you an example.
@login_required
def friendship_add_friend(request, user_id, user_name):
to_user = User.objects.get(pk=user_id)
from_user = request.user
if request.user == to_user:
messages.error(request, (
'You can not add yourself as a friend...')
)
else:
try:
already_friends = Friend.objects.get(from_user=from_user, to_user=to_user)
except:
already_friends = None
if already_friends:
messages.error(request, (
u'You are already friends with %s' % slugify(user_name))
)
else:
try:
created, sent_request = FriendshipRequest.objects.get_or_create(from_user=from_user, to_user=to_user)
except:
sent_request = None
if sent_request:
messages.success(request, (
u'Your friend request has been sent to %s! '
u'You must now wait for %s to accept.' % (slugify(user_name), slugify(user_name)))
)
else:
messages.error(request, (
u'You have already sent a friend request to %s...' % slugify(user_name))
)
return redirect(reverse('friendship_view_friends', args=(user_id, slugify(user_name))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment