我无法从基于类的视图中保存图像
我是Django的新手,我可能错过了一些东西。
views.py
class PostCreateView(LoginRequiredMixin,CreateView):
model = Post
fields = ['title', 'content','image']
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
models.py
class Post(models.Model):
title = models.CharField(max_length = 100)
content = models.TextField()
created_on = models.TimeField(auto_now = True)
author = models.ForeignKey(User, on_delete = models.CASCADE,)
image = models.ImageField(default = 'default.jpg',upload_to = 'post_pics',)
def save(self, *args, **kwargs):
super().save(*args,**kwargs)
img = Image.open(self.image.path)
if img.height > 300 or img.width > 300:
output_size = (300, 300)
img.thumbnail(output_size)
img.save(self.image.path)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('network:post_detail', kwargs={'pk':self.pk})
urls.py
app_name = 'network'
urlpatterns = [
path('', user_views.PostList.as_view(), name = 'homepage'),
path('post/<int:pk>/', user_views.PostDetail.as_view(), name = 'post_detail'),
path('post/new/', user_views.PostCreateView.as_view(), name = 'post_create'),
path('post/<int:pk>/update', user_views.PostUpdateView.as_view(), name = 'post_update'),
path('post/<int:pk>/delete', user_views.PostDeleteView.as_view(), name = 'post_delete'),
path('register/', user_views.register, name="register"),
path('login/',auth_views.LoginView.as_view(), name="login"), #we can add the template path manually in as_view()
path('logout/',auth_views.LogoutView.as_view(), name="logout"), #default is registration/logout.html
path('profile/<int:pk>',user_views.ProfileDetail.as_view(),name = 'profile_detail'),
path('post/new/',user_views.PostCreateView.as_view(),name = 'post-create'), #<app_name>/<model>_form.html
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
我希望该帖子随附我保存的图像 但实际上它带有默认图片