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

23πŸ‘

βœ…

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},]
πŸ‘€C. Alan Zoppa

6πŸ‘

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)
πŸ‘€user1839132

1πŸ‘

class UserProfile(models.Model):

    user = models.ForeignKey(User, unique=True)
    #other fields

    def get_friends(self):
        user = self.user
        return Friendship.objects.filter(Q(creator=user)|Q(friend=user))


    #then you can call elsewhere

    friends = user.get_profile().get_friends().all()
πŸ‘€Tiago

Leave a comment