Reputation: 603
i want to get all attribute data of articles in SetRundown
forms like title, category, author
via ManyToManyfield
i want to show all article in Rundown form with title category and author name can anybody know how can i do this...? if i run my code with {% render_field form.articles %}
then it will show the all articles title but i want the category and author name too with titles....
models.py
class Article(models.Model):
title = models.CharField(max_length=300, help_text="Short title")
category = models.ForeignKey(Category, on_delete=models.CASCADE)
author = models.ForeignKey(User, on_delete=models.CASCADE)
class SetRundown(models.Model):
pool_title = models.CharField(max_length=200)
articles = models.ManyToManyField(Article)
forms.py
from django import forms
class SetRundownForm(forms.ModelForm):
class Meta:
model = SetRundown
fields = ['pool_title', 'time_pool', 'articles']
def __init__(self, *args, **kwargs):
super(SetRundownForm, self).__init__(*args, **kwargs)
self.fields['articles'].queryset = Article.objects.filter(story_status='fr')
create_form.html
<form method="POST">{% csrf_token %}
{% render_field form.pool_title type="text" %}
{% render_field form.time_pool type="menu" %}
{% for article in form.articles %}
{{ article.title }}
{{ article.category }}
{{ article.author.username }}
{% endfor %}
<button class="btn btn-secondary" type="submit">Submit</button>
</form>
{% endblock %}
Upvotes: 1
Views: 922
Reputation: 477190
You can access the .queryset
of the .field
:
{% for article in form.articles.field.queryset %}
{{ article.title }}
{{ article.category }}
{{ article.author.username }}
{% endfor %}
In your SetRundownForm
, you can make use of .select_related(…)
[Django-doc] to avoid an N+1 problem:
class SetRundownForm(forms.ModelForm):
class Meta:
model = SetRundown
fields = ['pool_title', 'time_pool', 'articles']
def __init__(self, *args, **kwargs):
super(SetRundownForm, self).__init__(*args, **kwargs)
self.fields['articles'].queryset = Article.objects.select_related(
'author'
).filter(story_status='fr')
Upvotes: 2