我有这样的模型
class Ask(models.Model):
name = models.CharField(max_length=500)
designation = models.CharField(max_length=200, blank=True)
email = models.EmailField()
phone = models.CharField(max_length=20, blank=True)
avatar = models.ImageField(upload_to="ask/users/avaters", blank=True, )
question = models.CharField(max_length= 1024)
ques_time = models.DateField(auto_now_add=True)
answer = models.TextField(blank=True)
ans_time = models.DateField(blank=True,null=True, auto_now=True)
display = models.BooleanField()
asker_ip = models.CharField(max_length=100, blank=True)
def __unicode__(self):
return self.name
我的forms.py就像这样
class AskForm(forms.Form):
name = forms.CharField(required=True, max_length= 500)
email = forms.EmailField(required=True)
avater = forms.ImageField()
question = forms.CharField(required=True, max_length=1024)
我的观点是这样的
def handle_uploaded_file(f):
destination = open('D:/dsite/ak47/media/ask/users/avaters', 'wb+')
for chunk in f.chunks():
destination.write(chunk)
destination.close()
def submit_page(request):
data = {}
if request.method == 'POST':
data = request.POST.copy()
form = AskForm(request.POST, request.FILES)
if form.is_valid():
ask = Ask()
ask.name = form.cleaned_data['name']
ask.email = form.cleaned_data['email']
ask.question = form.cleaned_data['question']
handle_uploaded_file(request.FILES['avater'])
ask.save()
return HttpResponseRedirect('/ask/')
else:
form = AskForm()
return render_to_response('ask/index.html', {'form': form,})
问题出在我的Windows开发服务器上。当我点击提交它给我一个错误。没有权限。我试过给该文件夹一个完全的控制权限。我假设错误是出于其他原因。因为我可以从管理面板上传。
答案 0 :(得分:0)
您正在尝试将文件保存到文件夹中,但未指定文件名。 你的句柄功能应该是:
def handle_uploaded_file(f):
save_path = 'D:/dsite/ak47/media/ask/users/avaters'
destination = open(os.path.join(save_path,f.name), 'wb+')
for chunk in f.chunks():
destination.write(chunk)
destination.close()
并且不要忘记在views.py
的顶部添加import os
使用ModelForm and it's features。 You dont have to handle manually file uploading,它已经由ModelForm完成。您的 forms.py 应如下所示:
from .models import Ask
class AskForm(forms.ModelForm):
class Meta:
model = Ask
fields = ('name', 'email', 'question', 'avater')
您的views.py应如下所示:
def submit_page(request):
if request.method == 'POST':
form = AskForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return HttpResponseRedirect('/ask/')
else:
form = AskForm()
return render_to_response('ask/index.html', {'form': form,})
ModelForm将自动处理所有提交的数据并为其创建/保存新的Ask对象。