4

私はDjangoの初心者です。私の問題は些細なことだと思いますが、解決できません。1つのFileFieldを持つDocumentという名前のモデルがあります。

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 error: "This field is required!"モデルでFileFieldなしで取得したフォームを送信しようとすると、これは以前は機能していました。私はDjango1.2.5を持っています。3日間拷問しますが何もありません!私は絶望的です。私の言語でごめんなさい。助けてください!

4

2 に答える 2

0

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.

于 2011-03-19T20:02:02.670 に答える
0

ドキュメントモデルでは、ファイルをupload_t0「ドキュメント」に設定していますが、正確にはupload_toが指している場所です。

これが役立つかもしれません。

于 2013-04-21T23:20:29.877 に答える