Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to make Django's "user" system have "friends" [closed]

Tags:

django

I am using Django's authorization system to make accounts on my application.

What's the best way at making a "friends" system using the authorization system? I want to be able to link the Users together, but they have to accept the friend request first, and I also want to hold the date they became friends.

like image 951
dotty Avatar asked Dec 30 '10 17:12

dotty


2 Answers

An M2M field almost gets you there, but will only store the relationship, not the date it was created. It would be a lot simpler if you can manage without the friendship date.

Otherwise you'll want to create a model something like this:

class Friendship(models.Model):
    created = models.DateTimeField(auto_now_add=True, editable=False)
    creator = models.ForeignKey(User, related_name="friendship_creator_set")
    friend = models.ForeignKey(User, related_name="friend_set")

You'll want to create a method, probably on the user profile model to make sense of the relationships. Ideally, it should get you something like this:

>> User.userprofile.friends()
[{'name': "Joe", 'created': 2010-12-01},]
like image 132
C. Alan Zoppa Avatar answered Nov 10 '22 07:11

C. Alan Zoppa


I have done these:

models.py

class FriendMgmt(models.Model):
    """
        friends table
    """
    user = models.ForeignKey(User)
    friend = models.ForeignKey(User, related_name="friends")

forms.py

class FriendMgmtForm(forms.Form):
    """
        Manages friends connections
    """
    friend = forms.CharField(max_length=100,required=False)

views.py

def my_friends(request):
    """
        used for Displaying and managing friends
    """
if request.method == 'POST':

    form = FriendMgmtForm(request.POST)
    if form.is_valid():

        user = User.objects.get(id=80)
        friend_manage = FriendMgmt(user=request.user, friend= user)
        friend_manage.save()

        return HttpResponseRedirect('/myfriends/')

else:
    form = PdfValidationForm()

user = request.user
profile = UserProfile.objects.get(user=user)
full_name = user.get_full_name()
email = user.email
area_interest = profile.area_of_interest
designation = profile.designation
friends = FriendMgmt.objects.filter(user=request.user)


return render_to_response('friends.html',{'form': form,
                                      'full_name':full_name,
                                      'email':email,
                                      'area_interest':area_interest,
                                      'designation':designation,
                                      'friends':friends,

                                      }
                          )

url.py

 url(r'^myfriends/$',my_friends)
like image 6
user1839132 Avatar answered Nov 10 '22 09:11

user1839132