如何通过 ModelForm 使用 FileField 添加 Django 模型的新实例?

发布于 2024-10-24 18:16:27 字数 1630 浏览 6 评论 0原文

我是 Django 初学者。我认为我的问题很微不足道,但我无法解决。 我有一个名为 Document 的模型,带有一个 FileField:

class Document(models.Model):
    file = models.FileField(upload_to="documents")
    created = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)
    category = models.ForeignKey(DocumentCategory)
    title = models.CharField(max_length=255, unique=True)
    description = models.TextField()

    def __unicode__(self):
        return self.title

我想通过此 ModelForm 向该类添加一个新实例:

class DocumentForm(ModelForm):
    class Meta:
        model = Document

在views.py 中,我有:

def add_document(request):
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/')
        else:
            return render_to_response('add_document.html', {'form':form}, context_instance=RequestContext(request))
    else:
        form = DocumentForm()
    return render_to_response('add_document.html', {'form':form}, context_instance=RequestContext(request))

此模板(即 add_document.html):

{% extends "base.html" %}
{{block content %}
<form enctype="multipart/form-data" method="post" action="">{% csrf_token %}
{{form}}
<input type="submit" value="Add document" />
</form>
{% endblock %}

在管理界面中向数据库工作正常,并且添加文件处于“upload_to”本地化状态。我的表格不起作用。当我尝试提交表单时,我收到 Filefield 错误:“此字段是必需的!” 如果模型中没有 FileField,则此操作之前可以正常工作。 我有 Django 1.2.5 我用它折磨了3天,毫无效果!我很绝望。对不起我的语言。请帮忙!

I'm a Django beginner. I think my problem is trivial but I can't solve it.
I have a model named Document with one FileField:

class Document(models.Model):
    file = models.FileField(upload_to="documents")
    created = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)
    category = models.ForeignKey(DocumentCategory)
    title = models.CharField(max_length=255, unique=True)
    description = models.TextField()

    def __unicode__(self):
        return self.title

I want to add a new instance to this class by this ModelForm:

class DocumentForm(ModelForm):
    class Meta:
        model = Document

In views.py I have:

def add_document(request):
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/')
        else:
            return render_to_response('add_document.html', {'form':form}, context_instance=RequestContext(request))
    else:
        form = DocumentForm()
    return render_to_response('add_document.html', {'form':form}, context_instance=RequestContext(request))

Template for this (i.e. add_document.html):

{% extends "base.html" %}
{{block content %}
<form enctype="multipart/form-data" method="post" action="">{% csrf_token %}
{{form}}
<input type="submit" value="Add document" />
</form>
{% endblock %}

In the Admin Interface adding a model to the database is working correctly and adding a file is in "upload_to" localization. My form does not work. When I try to submit a form I get Filefield error: "This field is required!" Without FileField in model this works before.
I have Django 1.2.5
I torture with it for 3 days and nothing! I'm desperate. Sorry for my language. Please help!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

娜些时光,永不杰束 2024-10-31 18:16:27

就像现在一样,需要一个文件。您是否尝试在没有文件的情况下保存表单?
如果您想让该文件成为可选文件,则需要按以下方式定义它:

class Document(models.Model):
    file = models.FileField(upload_to="documents", blank=True, null=True)

作为附加说明,表单中的操作参数可能不正确。
它应该是一个 URL;通常在 Django 中,您需要放置 ".",但不是完全空的字符串 ("")。也就是说,我不知道这是否是一个问题。

As it is now, a file is required. Are you trying to save the form without a file?
If you want to make the file optional, you need to define it in this way:

class Document(models.Model):
    file = models.FileField(upload_to="documents", blank=True, null=True)

As a an additional note, the action parameter you have in the form may be incorrect.
It should be an URL; usually in Django you would want to put ".", but not a completely empty string (""). That said, I do not know if this may be an issue or not.

罗罗贝儿 2024-10-31 18:16:27

在文档模型中,您将文件设置为 upload_t0“文档”,但 upload_to 到底指向哪里。

可能会有帮助。

In you Document model, you have your file set to upload_t0 "documents", but where exactly is upload_to pointed to.

May be this will help.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文