from django form uploading a image in windows development server
I have a model like this
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
my forms.py is like this
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)
my view is like this
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,})
problem is in my windows development server. When I hit submit it give me a io error. Permission denied. I tried give the folder a full control permission. I'm assuming the error is for other reason. Because I开发者_运维问答 can upload from admin panel.
You're trying to save file into folder, but did not specified file name. Your handle function should be:
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()
and dont forget add at top of your views.py
import os
Another solution for this case
Use ModelForm and it's features. You dont have to handle manually file uploading, it's already done by ModelForm. Your forms.py should look like this:
from .models import Ask
class AskForm(forms.ModelForm):
class Meta:
model = Ask
fields = ('name', 'email', 'question', 'avater')
Your views.py should look like this:
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 will automagically handle all submitted data and create/save new Ask object for it.
精彩评论