代码之家  ›  专栏  ›  技术社区  ›  user8520549

CreateView-尝试保存图像上载时出现TypeError

  •  0
  • user8520549  · 技术社区  · 7 年前

    我试着把我的脑袋放在图像上 Form handling with class-based views . 所以我在玩这个简单的模型。使用CreateView时,我是否必须使用form_类用自定义表单覆盖它才能成功上载/保存和图像?

    我不明白为什么我会这样:

    Exception Type:     TypeError
    Exception Value:    expected str, bytes or os.PathLike object, not tuple
    

    整个东西都是赤裸裸的,没有存货。

    模型。py公司

    class Post(models.Model):
        headline = models.CharField(max_length=80, blank=True, null=True)
        cover_image = models.ImageField('hero image', upload_to='images/', blank=True, null=True)
        slug = models.SlugField(max_length=80, blank=True, null=True, unique=True)
    
        def get_absolute_url(self):
            return reverse('details', args=[str(self.slug)])
    

    意见。py公司

    from django.contrib.auth.mixins import LoginRequiredMixin
    from django.views.generic import CreateView
    
    class PostCreateView(LoginRequiredMixin, CreateView):
        model = Post
        fields = ['headline', 'cover_image', 'slug']
    

    新闻/模板/新闻/post_表单。py公司

    <form enctype="multipart/form-data" method="post" action="">
        {% csrf_token %}
        {{ form.as_p }}
        <input type="submit" value="Save"/>
      </form>
    

    有人能帮我理解吗?

    按要求

    # Static files (CSS, JavaScript, Images)
    # https://docs.djangoproject.com/en/2.0/howto/static-files/
    
    STATIC_URL = '/static/'
    
    STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),)
    
    MEDIA_ROOT = (os.path.join(BASE_DIR, 'media'),)
    MEDIA_URL = '/media/'
    
    LOGIN_REDIRECT_URL = 'home'
    
    1 回复  |  直到 7 年前
        1
  •  0
  •   Daniel Roseman    7 年前

    您已经将MEDIA\u ROOT设置为元组,但它应该是字符串。

    MEDIA_ROOT = os.path.join(BASE_DIR, 'media')