如何在django中保存图像

时间:2016-10-17 07:44:15

标签: django django-models django-forms

我有模特

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    phone_no= models.CharField(max_length=10, null=True)
    shop_name=models.CharField(max_length=244, null=True)
    shop_address=models.CharField(max_length=200,null=True,blank=True)
    city=models.CharField(max_length=20,null=True)
    country=models.CharField(max_length=20,null=True)
    abn=models.CharField(max_length=11)
    website = models.CharField(max_length=200, blank=True, null=True)
    #last_4_digits = models.CharField(max_length=4, default=False)
    #stripe_id = models.CharField(max_length=255, default=False)
    #subscribed = models.BooleanField(default=False)
    created_at = models.DateTimeField(default=datetime.now, blank=True)
    updated_at = models.DateTimeField(default=datetime.now, blank=True)
    Emg_no=models.CharField(max_length=10, null=True,blank=True)
    area_code=models.CharField(null=True,blank=True,max_length=2)
    landline_number= models.CharField(null=True,blank=True,max_length=9)
    payment_date = models.DateTimeField(default=datetime.now, blank=True)
    status=models.ForeignKey(Status,blank=True,null=True)
    user_image = models.ImageField(upload_to='user_image')

    def __str__(self):
       return self.user.first_name

    class Meta:
        db_table = 'registration_userprofile'

我想单独保存图像,以便我写一个表单

class User_imageForm(forms.Form):
    user_image = forms.ImageField(required= False)
    class Meta:
        model=UserProfile
        Fields=('user_image')

现在我想将图像保存在给定的路径上,我的观点是

    @login_required(login_url="/registration/login/") 
def user_image(request,user_id):
    print("start of user_image view")
    server1 = get_object_or_404(User, pk=user_id)
    print("hiiiiiiiiiiiii")
    if request.method == 'POST':
        print("post ")
        userimage = User_imageForm(request.POST,request.FILES)
        if userimage.is_valid():
            print("form is valid")
            server1.user_image=userimage.cleaned_data['user_image']
            server1.save()
            print("image save")
            print(request.user.id)

            variables=RequestContext(request,
                               {'id':request.user.id})
            return redirect('updatedetails', int(request.user.id) )

        else:
            print("form is not valid") 
            userimage = User_imageForm() 
            return render_to_response('registration/profile_try.html')

0 个答案:

没有答案