Я работаю над проектом в django, у меня есть форма для комментариев, и я хочу, чтобы пользователи могли отправлять комментарий и прикреплять к нему изображение. Мой комментарий сохранен в базе данных, но изображение, которое я прикрепил к форме, не сохраняется в базе данных. Что такое
Models.py
class Comments (models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE, blank=True,null=True)
commented_image = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments', null=True, blank=True)
comment_post = models.TextField()
comment_pic = models.FileField(upload_to='CommentedPics/%Y/%m/%d/', blank=True)
active = models.BooleanField(default=True)
date = models.DateTimeField(auto_now_add=True)
parent = models.ForeignKey('self', null=True, blank=True, related_name='replies', on_delete=models.CASCADE)
Forms.py
class CommentForm(forms.ModelForm):
class Meta:
model = Comments
fields = (
'comment_post',
'comment_pic',
)
Views.py
def comment_view(request, id):
post = get_object_or_404(Post, id=id)
all_comments = post.comments.filter(active=True, parent__isnull=True).exclude(
user__profile__blocked_users__user=request.user, active=True)
if request.method == 'POST':
# comment has been added
form = CommentForm(request.POST, request.FILES)
if form.is_valid():
comment = form.save(commit=False)
comment.user = request.user
comment.commented_image = post
parent_obj = None
# get parent comment id from hidden input
try:
# id integer e.g. 15
parent_id = int(request.POST.get('parent_id'))
except:
parent_id = None
# if parent_id has been submitted get parent_obj id
if parent_id:
parent_obj = Comments.objects.get(id=parent_id)
# if parent object exist
if parent_obj:
# create replay comment object
replay_comment = form.save(commit=False)
# assign parent_obj to replay comment
replay_comment.parent = parent_obj
# normal comment
# create comment object but do not save to database
new_comment = form.save(commit=False)
# assign ship to the comment
new_comment.user = request.user
new_comment.commented_image = post
# save
new_comment.save()
return redirect('site:comments', id=id)
else:
form = CommentForm()
context = {
'form': form,
'post':post,
'all_comments': all_comments,
}
return render(...)
Шаблон:
<form method="POST" enctype="multipart/form-data" class="comment-form form-inline md-form form-sm">
{% csrf_token %}
{{ form }}
<input type="hidden" name="parent_id" value="{{ comment.id }}" >
<button type="submit" id="submit"><i class="fas fa-paper-plane" aria-hidden="true"></i></button>
</form>