I have a modelform that doesn't produce (some of) the HTML that (should) represent the model fields. As you can see from the output at the bottom, it's just outputting a blank line where it should be outputting the title and presumably a browse button (or something--right?) for the filefield.
#views.py
def upload_file(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
else:
form = UploadFileForm()
return render_to_response开发者_开发百科('files/upload_file.html', { 'form': form })
#models.py
from django import forms
from django.db import models
from django.forms import ModelForm
class UploadFile(models.Model):
title = forms.CharField(max_length = 50)
theFile = forms.FileField()
def __unicode__(self):
return str(title)
class UploadFileForm(ModelForm):
class Meta:
model = UploadFile
#upload_file.html
<form action="" method="POST" enctype="multipart/form-data">
{{ form }}
<input type="submit" value="Upload File">
</form>
#The HTML output
<form action="" method="POST" enctype="multipart/form-data">
<input type="submit" value="Upload File">
</form>
Actually on second thought your mistake is in declaring your model UploadFile (after doublechecking due to lack of a response). You are supposed to use models.CharField not forms.CharField. Thus your model doesn't have any content; hence the ModelForm doesn't have any fields (it didn't arise as an error just in case some advanced user wanted to attach the form fields you eventually wanted to use to a model). You also will need to give the FileField an upload_to location, principally your media directory.
class UploadFile(models.Model):
title = models.CharField(max_length = 50)
theFile = models.FileField(upload_to="files/")
def __unicode__(self):
return str(title)
精彩评论