templatetags/follow_tags.py
@register.simple_tag
def in_follow(user, follower):
return user.who_follows.filter(follower=follower).exists()
urls.py
url(r'^to_follow/(?P<user_id>\d+)/$', follow, name='add_to_follow'),
template/user_page_blablabla.html
{% load follow_tags %}
...
{% if messages %}
<ul class="messages">
{% for message in messages %}
<li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
...
{% in_follow user current_user as user_in_follow %}
{% if user_in_follow %}
<span>{% trans "In follow" %}</span>
{% else %}
<a href="{% url "add_to_follow" user_id=current_user.id %}">Add to follow</a>
{% endif %}
views.py
@login_required
def follow(request,user_id):
selected_user = User.objects.get(id=user_id)
_, created = Followship.objects.get_or_create(following=request.user,
follower=selected_user)
if created:
messages.success(request, 'ok')
else:
messages.error(request, 'User already following')
return reverse('user_page_blablabla')
models.py
class Followship(models.Model):
following = models.ForeignKey(User, related_name="who_follows")
follower = models.ForeignKey(User, related_name="who_is_followed")
class Meta:
unique_together = ('following', 'follower')