我正在尝试创建一个视图类来处理新Person对象的创建。您可以通过以下链接在Github上访问我的代码:
https://github.com/DAkbari/FaceRecognitionDjangoWebApi
这是Person对象的定义
class Person(models.Model):
firstName = models.CharField(max_length=200)
lastName = models.CharField(max_length=200)
faceEncode = models.CharField(max_length=3000)
facePicture = models.FileField()
lastLoginPicture = models.FileField()
code = models.CharField(max_length=100)
我在UserForm
中创建了类forms.py
,以显示创建新Person对象所需的字段
from identify.models import Person
from django import forms
class UserForm(forms.ModelForm):
class Meta:
model = Person
fields = ['firstName', 'lastName', 'code', 'facePicture']
下一步,我为UserForm
创建了一个视图
class PersonCreate(View):
form_class = UserForm
template_name = 'identify/new_person_form.html'
#display a blink form
def get(self, request):
form = self.form_class(None)
return render(request, self.template_name, {'form': form})
# process form data
def post(self, request):
form = self.form_class(request.POST)
if form.is_valid():
user = form.save(commit=False)
# clean normalized data
facePicture = form.cleaned_data['username']
FName = form.cleaned_data['firstName']
LName = form.cleaned_data['lastName']
code = form.cleaned_data['code']
user.save()
导航到结果视图并单击“提交”按钮时输入必填字段后,我选择的文件消失,表单对该字段提出了必填错误
如果我从facePicture
中删除forms.UserForm
字段,一切都会很好
new_person_form.html:
<div class="container-fluid">
<div class="row">
<div class="col-sm-12 col-md-7">
<div class="panel panel-default">
<div class="panel-body">
<h3>Create a new account</h3>
<form class="form-horizontal" action="{% url
'identify:new' %}" method="post"
enctype="multipart/form-data">
{% csrf_token %}
{% include 'identify/form-template.html' %}
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-
success">Submit</button>
</div>
</div>
</form>
{% if errorMsg %}
<p style="color: red;">{{ errorMsg }}</p>
{% endif %}
</div>
</div>
</div>
</div>
</div>
form_template.html:
{% for field in form %}
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<span class="text-danger small">{{ field.errors }}</span>
</div>
<label class="control-label col-sm-2"> {{ field.label_tag }}</label>
<div class="col-sm-10"> {{ field }}</div>
</div>
{% endfor %}
答案 0 :(得分:0)
初始化表单实例时您忘记了request.FILES
:
form = self.form_class(request.POST, request.FILES)