Answer the question
In order to leave comments, you need to log in
How to upload an image from a form?
There is a form for sending comments, there I attached the ability to upload a photo.
The page does not display the photo, instead it displays the path. If you upload a photo through the form, the path looks like this: /media/%3CMultiValueDict%3A%20%7B%7D%3E
if through the admin panel like this: /media/product_image/otziv/login.png
models.py
class Comment(models.Model):
product = models.ForeignKey('Product', related_name='comments', on_delete=models.CASCADE)
user = models.ForeignKey(get_user_model(), on_delete=models.SET_NULL, null=True, verbose_name="Пользователь")
comment = models.TextField("Ваш комментарий")
created = models.DateTimeField("Дата", auto_now_add=True)
image = models.ImageField(upload_to="product_image/otziv/", blank=True)
approved_comment = models.BooleanField(default=False)
def approved(self):
self.approved_comment = True
self.save()
def __str__(self):
return self.comment
def add_comment(request, slug):
form = CommentForm(request.POST)
product = get_object_or_404(Product, slug=slug)
if request.method == 'POST':
comment = form.save(commit=False)
comment.product = product
comment.user = request.user
comment.image = request.FILES
comment.save()
return redirect('products:detail', slug=product.slug)
else:
form = CommentForm()
template = "products/comment.html"
context = {'form': form}
return render(request, template, context)
{% for comment in product.comments.all %}
<div class="col-md-12 comments">
<strong>{{ comment.user }}</strong>
<div class="time">
Опубликованно: {{ comment.created|date:"G:i | d-m-Y " }}
</div>
{% if comment.image %}
{{ comment.image.url }}
{% endif %}
<h4 class="imeno_comment">Отзыв: {{ comment.comment }}</h4>
<hr>
</div>
{% empty %}
<p>Пока нет отзывов :(</p>
{% endfor %}
{% if user.is_active %}
<div class="btn-pos">
<label class="hvr-skew-backward ">
<a class="add_comment"
href="{% url 'products:add_comment' slug=product.slug %}">Добавить
отзыв</a>
</label>
</div>
{% else %}
<h4 align="center">Авторизуйтесь, чтобы оставить отзыв</h4>
{% endif %}
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ['comment', 'image',]
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