无法更改(编辑)在 django 中上传的文件

Jer*_*ews 5 python django edit

我的项目包含一个人的个人资料,他们可以在其中上传他们的照片作为个人资料图片。问题是我无法更改这张照片。在编辑部分,我可以编辑所有其他内容,例如姓名、地址等,但不能编辑照片。

我的 models.py 是:

def get_upload_file_name(instance,filename):
    return "image/%s_%s"%(str(time()).replace('.','_'),filename)

class Customer_Profile(models.Model):
    user = models.OneToOneField(User)
    first_name = models.CharField(_('First Name'), max_length= 30)
    middle_name = models.CharField(_('Middle Name'), max_length= 30,null = True,blank=True)
    last_name = models.CharField(_('Last Name'), max_length= 30)
    photo = models.ImageField(_('Photo'), upload_to=get_upload_file_name, null=True, blank=True,default='image/nophoto.png')
Run Code Online (Sandbox Code Playgroud)

我的 forms.py 是:

class Customer_Prof(forms.ModelForm):
    class Meta:
        model = Customer_Profile
        fields = ('photo','first_name','middle_name','last_name','address','phone_no')

class update_company_prof(forms.ModelForm):
    class Meta:
        model = Company_Profile
        fields =    ('name','logo','address','phone_no','url','cat_software','cat_electronics','cat_ mechanical','cat_civil','cat_other','specialized_in','prev_projects')
Run Code Online (Sandbox Code Playgroud)

我的观点.py是:

def edit_customer(request, offset):
    if request.method == 'POST':
        customer_edit = update_customer_prof(request.POST, instance=request.user.customer_profile)
        if customer_edit.is_valid():
            customer_edit.save()
            return HttpResponseRedirect('customer/' + offset)
    else:
        customer_edit =  update_customer_prof(instance=request.user.customer_profile)
    return render_to_response('edit_cust_prof.html', {'customer_edit':  customer_edit},
                              context_instance=RequestContext(request))
Run Code Online (Sandbox Code Playgroud)

请帮助我... PS 我可以从管理页面更改照片。

小智 2

要管理文件,在您的视图中,您需要将 request.FILES 传递给表单:

customer_edit = update_customer_prof(request.POST, request.FILES, instance=request.user.customer_profile)
Run Code Online (Sandbox Code Playgroud)

有关表单文件管理的更多说明:https ://docs.djangoproject.com/en/1.7/topics/http/file-uploads/