how to write the corresponding "handle_uploaded_file" for the model field and form?
attachment = models.FileField(upload_to='file/upload/question/%Y-%m-%d', verbose_name='attachment', null=True, blank=True,)
def handle_uploaded_file 开发者_C百科(file_, user):
filename = "%s-%s" % (user.username , file_.name)
path = "%s/file/upload/question/%s/%s" % (settings.MEDIA_ROOT, user.username, filename)
if not os.path.exists (path):
os.makedirs(path)
f = path + file.name
fd = open(f, 'wb+')
for chunk in file.chunks():
fd.write(chunk)
fd.close()
i don't know how to write the path and the following code?
def submit_question(request):
current_user = request.user
url = '/question/list_questions/'
if request.method == 'POST':
form = QuestionForm(request.POST, request.FILES)
if form.is_valid():
handle_uploaded_file(request.FILES['attachment'], current_user)
new_question = Question(question = form.cleaned_data['question'],
question_type= form.cleaned_data['question_type'],
country = form.cleaned_data['country'],
submitter = form.cleaned_data['submitter'],
is_private = form.cleaned_data['is_private'],
#attachment = temp_attachment,
)
new_question.save()
return HttpResponseRedirect(url)
else:
form = QuestionForm()
context = {'form': form,}
context.update(csrf(request))
return render_to_response('question/submit.html', context)
Why do you want to handle file attachments by yourself, django will do it for you.
Properties of FileField is here. I uesd it a few times before, i can not remember exactly butusing something as following must do the job...
First, create your form from related model:
class SomeFormWithFileForm(forms.ModelForm):
class Meta:
model = SomeModel
then in your view, where you create your form instance,
form = SomeFormWithFileForm(request.POST, request.FILES)
if form.is_valid():
form.save()
will do the trick.
精彩评论