Reputation: 343
I hope, that I wrote the Title correctly...)))
I have the model article
, that can connect to User through ManyToMany
field.
from django.db import models
from django.contrib.auth.models import User
from django.db import models
class Article(models.Model):
class Meta():
db_table = 'article'
article_users = models.ManyToManyField(User, null=True, blank=True, default=None)
article_title = models.CharField(max_length=200, blank=False, null=False)
article_content = models.IntegerField(choices=CONTENT_CHOICES, null=True, blank=True)
And I can list all the users, who connected to that model in the template through:
{% for user in article.article_users.all %}
{{ user.username }}
{% endfor %}
But how can I list all the models, to which is current User connected to?
Upvotes: 0
Views: 87
Reputation: 137
Is that what you are looking for ?
{% for article in user.article_set.all() %}
{{article.article_title}}
{% endfor %}
Maybe you will need to prevent this code if user is anonymous :
{% if user.is_authenticated() %}
{% for article in user.article_set.all() %}
{{article.article_title}}
{% endfor %}
{% else %}
# Do something for anonymous users.
{% endif %}
Edit : replaced request.user with user
Upvotes: 1
Reputation: 5612
Can't you write something like this in your view :
Article.objects.filter(article_users=current_user)
or should the request necessarily be in the template ?
(see also the django documentation for Many to many relationship)
Upvotes: 1