Сделал возможность для пользователя добавлять посты, у поста может быть превью картинка и я добавил возможность ее добавления, но после того как нажимаешь опубликовать пост, все данные сохраняются, но вот картинка не хочет.
Моя модель:
class Articles(models.Model):
title = models.CharField(max_length=350, verbose_name='Title of article')
info = models.TextField(verbose_name='Information')
img = models.ImageField(upload_to='images/article_images/', verbose_name='Preview photo', blank=True)
author = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name='Author of article', on_delete=models.CASCADE)
tags = models.ManyToManyField(Tags, verbose_name='Tags', related_name='articles')
def __str__(self):
return f'Title: {self.title}, author: {self.author}'
class Meta:
verbose_name = 'Article'
verbose_name_plural = 'Articles'
Форма добавления поста:
class CreateArticleForm(forms.ModelForm):
class Meta:
model = Articles
fields = ('img', 'title', 'tags', 'info')
widgets = {
'img': forms.FileInput(attrs={'class': 'form-control mt-2'}),
'title': forms.TextInput(attrs={'class': 'form-control mt-2'}),
'tags': forms.SelectMultiple(attrs={'class': 'form-control mt-2'}),
'info': forms.Textarea(attrs={'class': 'form-control mt-2', 'rows': '30'}),
}
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['tags'].queryset = Tags.objects.none()
if 'tags' in self.data:
self.fields['tags'].queryset = Tags.objects.all()
Код во views:
class CreateArticleView(LoginRequiredMixin, View):
login_url = 'sign-in'
def get(self, *args, **kwargs):
create_article_form = CreateArticleForm()
if is_ajax(self.request):
term = self.request.GET.get('term')
tags = Tags.objects.all().filter(name__icontains=term)
response_content = list(tags.values())
return JsonResponse(response_content, safe=False)
return render(self.request, 'Article/create-article.html', {'form': create_article_form})
def post(self, *args, **kwargs):
article_form = CreateArticleForm(self.request.POST)
if article_form.is_valid():
article = article_form.save(commit=False)
article.author = self.request.user
print(article_form.cleaned_data['img'])
article.save()
article.tags.set(article_form.cleaned_data['tags'])
return redirect('create-article')
return render(self.request, 'Article/create-article.html', {'form': article_form})
Форма в шаблоне:
<form enctype="multipart/form-data" action="" method="post" style="width: 100% !important">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="btn btn-success btn-block" style="margin-bottom: 20px">Post</button>
</form>