Reputation: 1087
Well this is really confusing to me, whenever I execute the view I get an error at x = form.file_name form has no attribute file_name. However, when I comment out the line x = form.file_name the html {{form.file_name}} does not return an error and a file browser is outputted to the page. How come form.file_name returns an error when executed in views.py but not in upload.html?
upload.html
{{form.file_name}}
views.py
def upload(request):
form = CsvForm(request.POST or None, request.FILES or None)
x = form.file_name
return render(request, 'upload/upload.html', {'form' : form})
forms.py
class CsvForm(forms.ModelForm):
class Meta:
model = Csv
fields = ('file_name', 'public')
models.py
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Csv(models.Model):
file_name = models.FileField(upload_to='csvs', max_length = 100)
public = models.BooleanField(default = False)
user = models.ForeignKey(User, on_delete = models.CASCADE, null = True)
def __str__(self):
return "File id: {}".format(self.id)
Upvotes: 1
Views: 1994
Reputation: 66
Well this because behind the scene form saves the bound fields using __getitem__
.
So to access correctly the bound field:
form["file_name"]
If you want to access the field:
form.fields["file_name"]
Upvotes: 1