【发布时间】:2020-08-30 13:44:20
【问题描述】:
我正在尝试使用表单在 django 中保存文件和其他一些详细信息。 而且我只希望它保存 CharField 和 FileField 而不是国家/地区字段。 对于国家/地区字段,我希望它通过发布请求获取其价值。 但是表格没有保存。错误显示“数据未验证”。 如果我不使用 FileField,此方法也可以正常工作。
models.py
class Simple(models.Model):
name = models.CharField(max_length=100)
city = models.FileField(upload_to='marksheet')
country = models.CharField(max_length=100)
forms.py
class SimpForm(forms.ModelForm):
class Meta:
model = Simple
fields = ['name','city']
来自 upload.html 的 sn-p
<form action="upload" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<label>Test input</label>
<input type="text" name="country">
{{form.name}}
{{form.city}}
<button type="submit">Submit</button>
</form>
views.py
def upload(request):
if request.method == 'POST':
a = request.POST.get('country')
form = SimpForm(request.POST,request.FILES)
if form.is_valid():
post = form.save(commit=False)
post.country = a
post.save()
return HttpResponse('saved')
else:
return HttpResponse('ERROR SAVING')
else:
form = SimpForm()
return render(request,'upload.html',{'form':form})
【问题讨论】:
-
如果您能粘贴完整的错误堆栈跟踪信息将会很有帮助。