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
- Tag inside tag in django template
- Django counter in loop to index list
- Django 1.9: ProgrammingError: relation "users_user" does not exist
- Combining multiple Django templates in a single request
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
- Creating a Portable Python (local install) for Linux
- Django 1.7 removing Add button from inline form
- Django bootstrap alerts not working as expected
- Extending User object in Django: User model inheritance or use UserProfile?
Source:stackexchange.com