- 的 models.py -
class resmodel(models.Model):
fname = models.CharField(max_length=20)
lname = models.CharField(max_length=20)
file_header = models.CharField(max_length=20)
upload_file = ContentTypeRestrictedFileField(
upload_to='documents', ]
content_types=['documents/msword', 'documents/pdf', 'documents/vnd.oasis.opendocument.text'],
max_upload_size=5242880,blank=True, null=True)
imag = models.ImageField(upload_to='images')
- 的 views.py -
def resview(request):
if request.method == "POST":
fname = request.POST.get('fname')
lname = request.POST.get('lname')
file_header = request.POST.get('file_header')
upload_resume = request.FILES['upload_resume']
imag = request.FILES['im']
if upload_file and imag:
details = resmodel(file_header=file_header, fname=fname, lname=lname, upload_file=upload_file, imag=imag)
details.save()
return HttpResponseRedirect('/profile/save/success/')
else:
return render_to_response('file.html')
- 的 file.html -
<form action="." method="post" enctype="multipart/form-data">{% csrf_token %}
<table border="0" align="center" cellsapcing="1" cellspadding="1">
<tr>
<td colspan="2"><h3> Personal Information</h3></td>
<td>First Name</td>
<td><input type="text" name="fname" /></td>
<td>Last Name</td>
<td><input type="text" name="lname" /></td>
<td>Resume Header<sub>(250 words max)</sub></td>
<td><input type="text" name="file_header"></td>
<td>Upload Resume<sub>(.doc/.docx, rtf, pdf, txt)</sub></td>
<td><input type="file" name="upload_resume" ></td>
<td>Upload image</td>
<td><input type="file" name="im" ></td>
<td>
<input type="submit" value="SUBMIT">
<input type="reset" value="RESET">
</td>
</tr>
</table>
</form>
对于“ContentTypeRestrictedFileField”,我跟随this link
但是我可以在imag和upload_file字段中上传所有文件和文件夹。 如何限制?任何人都可以帮我解决这个问题吗? 感谢。
答案 0 :(得分:1)
您必须使用表单验证。
from django.forms import models as model_forms
def resview(request):
if request.method == "POST":
form_class = model_forms.modelform_factory(resmodel)
form = form_class(request.POST)
if form.is_valid():
details = form.save()
return HttpResponseRedirect('/profile/save/success/')
else:
return render_to_response('file.html')
但要注意这是基本形式的用法。
将来您应该将表单传递给模板上下文并使用表单数据填充模板以显示表单输入,标签和验证错误。
此处有更多文档Creating forms from models 在这里Working with forms