S
S
Stanislav Shabalin2020-08-30 13:02:13
Django
Stanislav Shabalin, 2020-08-30 13:02:13

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.

Screen

5f4b70d7ec26f586236870.png


Models.py

Models
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]



forms.py

Forms
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',]



Views.py

Views (передаю в шаблон связанные файлы со статьей )
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)



Template edit-article.html
<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>


Please, does anyone know how to implement this? FormSet will help? To be honest, I still could not understand him)
Thanx

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Tikhonov, 2020-09-01
@Starck43

Read the ModelFormSet documentation.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question