如何在django CBV(基于类的视图)createviews中上传图像

问题描述 投票:0回答:1

我一直在使用Django创建博客共享应用程序。我正在尝试添加图像字段,以便用户能够上传图像并将其作为帖子查看。但是图像没有被上传。 Django甚至没有抛出任何错误。代码运行正常,但图像未上传。

我已经尝试在模板中添加“ enctype”,并在urls.py中进行必要的更改。我什至在settings.py中指定了MEDIA_ROOT和MEDIA_URL。如果settings.DEBUG:urlpatterns + =静态(settings.MEDIA_URL,document_root = settings.MEDIA_ROOT)我已经在urls.py中添加了它。

我的模型.py

    from django.utils import timezone
    from django.contrib.auth.models import User
    from django.urls import reverse


    class Post(models.Model):
        title = models.CharField(max_length=100)
        content = models.TextField()
        date_posted = models.DateTimeField(default=timezone.now)
        author = models.ForeignKey(User, 
                         on_delete=models.CASCADE,related_name='% 
                                 (app_label)s_%(class)s_related')
        picture = 

  models.ImageField(upload_to='images',default='default.png',null=True)

        def __str__(self):
            return self.title 

       def get_absolute_url(self):
           return reverse('project-home')

我的Views.py

    class PostCreateView(SuccessMessageMixin,LoginRequiredMixin,CreateView):
        model = Post
        fields = ['title','content','picture']
        success_message = 'Your submission is sucessful!'
        def form_valid(self,form):
        form.instance.author = self.request.user
        return super().form_valid(form)

        def get_success_message(self):
            return self.success_message

图像未上传。预先感谢!

python django blogs
1个回答
0
投票

我认为您需要为Post Model创建一个表单并将此表单添加到创建视图[form_class = PostForm]而不是[model = Post]

© www.soinside.com 2019 - 2024. All rights reserved.