Reputation:
I have a Django project where a user can re post other users posts by creating a relationship between the user and the post itself. But when I display this on my template, I want the tweets that have been re posted to have a different link next to them in order to un repost but instead with my current set up it still has the re post link, so I was just wondering how I could see if a relationship exists in a Django template as part of my conditional.
template
{% for tweets in combined_tweets %}
<p>{{ tweets.userprofile.user}} | {{ tweets }} | {{ tweets.date }} |
{% if tweets.userprofile.user == request.user %}
<a href='{% url "delete_tweet" request.user.id tweets.id %}'>DELETE</a>
{% elif ###Something to check if realtionship exists### %}
UN REPOST LINK
{% else %}
<a href='{% url "retweet" tweets.id %}'>RETWEET</a>
{% endif %}</p>
{% endfor %}
models.py
class UserProfile(models.Model):
user = models.OneToOneField(User)
bio = models.CharField(max_length=120, blank=True, verbose_name='Biography')
follows = models.ManyToManyField('self', related_name='followers', symmetrical=False, blank=True)
theme = models.ImageField(upload_to=get_image_path, blank=True)
profile_picture = models.ImageField(upload_to=get_image_path, blank=True)
def __str__(self):
return self.bio
class Tweet(models.Model):
userprofile = models.ForeignKey(UserProfile)
retweet = models.ManyToManyField(UserProfile, related_name='retweet_people', symmetrical=False, blank=True)
tweets = models.TextField(max_length=120)
date = models.DateTimeField()
Upvotes: 0
Views: 2378
Reputation: 47856
You can check that a relationship exists between the current user and other user tweets
using a custom template filter.
We will write a custom template filter check_relationship_exists
which will take the current user as the argument. This will check if the current tweet object is related to the user passed by performing a filter on its retweet
attribute using user.id
. If there exists a relationship, then the UN REPOST
link will be displayed otherwise a RETWEET
link will be shown.
from django import template
register = template.Library()
@register.filter(name='check_relationship_exists')
def check_relationship_exists(tweet_object, user):
user_id = int(user.id) # get the user id
return tweet_object.retweet.filter(id=user_id).exists() # check if relationship exists
Then in your template, you can do the following:
{% elif tweets|check_relationship_exists:request.user %}
Upvotes: 1