фото поста не сохраняется при отправке POST запроса на сайте, через админку все работает.
models.py:
class Post(models.Model):
title = models.CharField(max_length=200)
content = models.TextField()
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True)
post_image = models.ImageField(upload_to='post_images', blank=True)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('blog-detail', kwargs={'pk': self.pk})
forms.py:
from django import forms
from .models import Post
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ('title', 'content', 'category', 'post_image')
views.py:
class PostCreateView(LoginRequiredMixin, CreateView):
model = Post
posting_form = PostForm
fields = ['title', 'content', 'category', 'post_image']
def save(request):
if request.method == 'POST':
post_form = PostForm(request.POST, request.FILES)
if post_form.is_valid():
post_form.save()
return redirect('blog-detail')
else:
post_form = PostForm()
context = {
'post_form': post_form
}
return render(request, 'post_form.html', context)
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
html:
<section class="post container">
<form action="" class="form" method="post">
{% csrf_token %}
<h1 class="form__title">New Post</h1>
{{ posting_form | crispy }}
<div class="form__center">
<button class="form__button">Create</button>
</div>
<div class="border-top pt-3">
<small class="text-muted">Do you want to return to the home page? <a href="{% url 'blog-home' %}">Go back</a></small>
</div>
</form>
</section>