How to add a new instance of django model using FileField from ModelForm?

I am starting Django. I think my problem is trivial, but I can’t solve it. I have a model called 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 of this class using 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)) 

The 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 the model to the database that works correctly, and the added file is located in the localization "upload_to". My form is not working. When I try to submit a form, I get a filefield form error: "This field is required!" Without FileField in the model, this works earlier. I have Django 1.2.5 I have been tormenting him for 3 days and nothing! I'm desperate. Sorry for my language. Please, help!

+4
source share
2 answers

As 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 as follows:

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

As an additional note, the action parameter that you have on the form may be incorrect.
This must be a URL; usually in django you want to put "." , but not a completely empty string ( "" ). However, I do not know if this could be a problem or not.

0
source

In your document model, you have the file installed in upload_t0 "documents", but where exactly the value of upload_to is specified.

Perhaps this will help.

0
source

Source: https://habr.com/ru/post/1344377/


All Articles