Суть в том, что написал уже модель, через консоль все работает, всё отлично. Не могу написать вьюху.
Каким образом сделать запрос подписаться? Как передать текущий "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/")
Вот так реализована вьюха, но нужно передавать Person вместо юзер, а как это сделать не знаю.
#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)
Вот так это работает в шеле