如何为模型字段和表单编写相应的“handle_uploaded_file”?

时间:2011-08-06 10:24:17

标签: django

attachment = models.FileField(upload_to='file/upload/question/%Y-%m-%d', verbose_name='attachment', null=True, blank=True,)

def handle_uploaded_file (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()

我不知道如何编写路径和以下代码?

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)

1 个答案:

答案 0 :(得分:2)

为什么你要自己处理文件附件,django会为你做。

Properties of FileField就在这里。我之前曾经说过几次,我记不清楚但是正在使用下面的东西必须要做的工作......

首先,从相关模型创建表单:

class SomeFormWithFileForm(forms.ModelForm):
class Meta:
    model = SomeModel

然后在您的视图中,您在其中创建表单实例,

form = SomeFormWithFileForm(request.POST, request.FILES)
if form.is_valid():
    form.save()

会做到这一点。