Harv
Harv

Reputation: 497

Django model form not producing expected HTML

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>

Upvotes: 1

Views: 543

Answers (1)

dr jimbob
dr jimbob

Reputation: 17751

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)

Upvotes: 5

Related Questions