开发者

How to add a new instance of Django model with FileField by ModelForm?

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 data开发者_如何学Gobase 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!


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜