Answer the question
In order to leave comments, you need to log in
How to implement subscriptions like on Twitter?
The bottom line is that the model has already been written, everything works through the console, everything is fine. I can't write a view.
How to make a request to subscribe? How to pass the current "Person"
#Model
class Person(models.Model):
"""docstring for UserProfile"""
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete = models.CASCADE)
relationships = models.ManyToManyField('self', through='Relationship', related_name='related_to', symmetrical=False)
def __str__(self):
return self.user.username
def add_relationship(self, person, status):
relationship, created = Relationship.objects.get_or_create(
from_person=self,
to_person=person,
status=status)
return relationship
def remove_relationship(self, person, status):
Relationship.objects.filter(
from_person=self,
to_person=person,
status=status).delete()
return
def get_relationships(self, status):
return self.relationships.filter(
to_people__status=status,
to_people__from_person=self)
def get_related_to(self, status):
return self.related_to.filter(
from_people__status=status,
from_people__to_person=self)
def get_following(self):
return self.get_relationships(RELATIONSHIP_FOLLOWING)
def get_followers(self):
return self.get_related_to(RELATIONSHIP_FOLLOWING)
def create_person(sender, instance, created, **kwargs):
if created:
Person.objects.create(user=instance)
post_save.connect(create_person, sender= User)
RELATIONSHIP_FOLLOWING = 1
RELATIONSHIP_BLOCKED = 2
RELATIONSHIP_STATUS = (
(RELATIONSHIP_FOLLOWING, 'Following'),
(RELATIONSHIP_BLOCKED, 'Blocked'),
)
class Relationship(models.Model):
from_person = models.ForeignKey(Person, related_name='from_people', on_delete=models.DO_NOTHING)
to_person = models.ForeignKey(Person, related_name='to_people', on_delete=models.DO_NOTHING)
status = models.IntegerField(choices=RELATIONSHIP_STATUS)
#URLS
path('users/', views.users, name='users'),
path('users/follow/<int:users_id>', views.follow, name='follow'),
#template
<div>
<ul class="list-group">
{% for users in users_list %}
<li class="list-group-item" id="firstuser">{{users.user}}
<form method="post" action="follow/{{users.id}}">
<button type="submit" class='btn btn-light float-right' >Follow </button>
{% csrf_token %}
</li>
</form>
#View
def follow(request, users_id):
current_user = request.user
users = Person.objects.get(id=users_id)
current_user.add_relationship(users, RELATIONSHIP_FOLLOWING)
return HttpResponseRedirect("/users/")
#shell
from twitter.models import Person
john = Person.objects.create(name='John')
paul = Person.objects.create(name='Paul')
from twitter.models import RELATIONSHIP_FOLLOWING
john.add_relationship(paul, RELATIONSHIP_FOLLOWING)
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question