【问题标题】:CreateView - Getting a TypeError when trying to save an image uploadCreateView - 尝试保存图像上传时出现 TypeError
【发布时间】:2018-05-22 00:42:13
【问题描述】:

我正试图围绕图像和Form handling with class-based views 进行思考。所以我在玩这个简单的模型。使用 CreateView 时,我是否必须使用 form_class 用自定义表单覆盖它才能成功上传/保存和图像?

我不知道为什么会这样:

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

整个东西都是准系统,缺货。

models.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)])

views.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_form.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'

【问题讨论】:

  • 显示完整的回溯,以及 MEDIA_ROOT 设置。
  • 我已经更新了帖子
  • 你是对的。它是 MEDIA_ROOT。我将其更改为 MEDIA_ROOT = './media' 并且有效

标签: python django forms django-class-based-views


【解决方案1】:

您已将 MEDIA_ROOT 设置为一个元组,但它应该是一个字符串。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-05
    • 2020-03-14
    • 2016-09-29
    • 1970-01-01
    • 1970-01-01
    • 2018-04-01
    • 2020-04-10
    • 2021-01-29
    相关资源
    最近更新 更多