Answer the question
In order to leave comments, you need to log in
Manage related records in a view?
There are articles (the main table), I add the output of related files to them in the template and I want to edit them along with the main fields of the article.
class Article(models.Model):
slug = models.SlugField()
title = models.CharField()
class Image(models.Model):
article = models.ForeignKey(Article, on_delete=models.SET_NULL, related_name='images', null=True, blank=True)
file = models.ImageField('Файл', upload_to='uploads/')
def thumb(self):
if self.file:
return format_html('<a href="{0}" target="_blank"><img src="{0}" width="100"/></a>', self.file.url)
else:
return format_html('<img src="/media/no-image.png" width="100"/>')
thumb.short_description = 'Миниатюра'
@property
def filename(self):
return self.file.name.rsplit('/', 1)[-1]
class ArticleForm(forms.ModelForm):
#slug = forms.CharField(widget=forms.HiddenInput(), label='')
class Meta:
model = Article
fields = '__all__'
exclude = ['image']
files = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True}), required=False)
class ImageForm(forms.ModelForm):
class Meta:
model = Image
fields = ['file',]
def edit_article(request, slug=None):
...
edit_post = get_object_or_404(Article, slug=slug)
uploaded_files = Image.objects.filter(article_id=edit_post.pk)
...
context = {
'form': post_form,
'files': uploaded_files,
}
return render(request, catalog_app_name + 'edit-article.html', context)
<form class="article-form edit-form" action="" enctype="multipart/form-data" method="post">
{% csrf_token %}
{% for field in form %}
<div class="form-group">
{% if field.errors %}
<div class="alert alert-danger">
{{ field.errors }}
</div>
{% endif %}
{% if field.name == 'files' %}
{% for f in files %}
<div class="thumbnail-container">
<div>{{f.thumb}}</div>
<div>{{f.title}}</div>
</div>
{% endfor %}
{% endif %}
{{ field|as_crispy_field }}
</div>
{% endfor %}
<button class="btn btn-primary" type="submit">Сохранить</button>
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