(1062,“键'user_id'的重复条目'2'”))

时间:2018-12-14 08:01:30

标签: python django base64

我正在尝试通过裁剪图像来更新配置文件,裁剪图像后,它给了我一个base64字符串,我必须将其隐蔽到图像中并存储在服务器上,并将其URL存储在数据库中。我正在服务器上获取图像,但无法将其url存储在数据库中。

models.py

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    image = models.FileField(default='default.jpg', 
    upload_to='profile_pics')

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

    def save(self, *args, **kwargs):
          #super(Profile, self).save(*args, **kwargs)
          super().save()
          img = Image.open(self.image.path)

          if img.height > 300 or img.width > 300:
              output_size = (300,300)
              img.thumbnail(output_size)
              img.save(self.image.path)     

forms.py

class ProfileUpdateForm(forms.ModelForm):
    class Meta:
        model = Profile
        fields = ['image']

views.py

#profile view
@login_required
def profile(request):
    #if any changes POST data
    if request.method == 'POST':
        image_data = request.POST['image']
        format12,img = image_data.split(';base64,')
        ext = format12.split('/')[-1]
        imageObj = ContentFile(base64.b64decode(img+"=="))
        file_name = "myphoto."+ext
        #print(file_name)
        #Profile.image = data
        #Profile.save(file_name, data, save=True)
        #Profile.save()
        profile = Profile()
        #profile.user_id = request.user.id
        #profile.image= imageObj
        u_form = UserUpdateForm(request.POST, instance=request.user)
        p_form = ProfileUpdateForm(request.POST, request.FILES,instance=request.user.profile)

        #check if both forms are valid
        if u_form.is_valid() and p_form.is_valid():
            u_form.save() # if yes Save
            profile.image.save(file_name, imageObj)
            profile.save()
            #p_form.save() # if yes save
            messages.success(request, format('Your Profile has been updated.'))
            return redirect('profile')
    else:
        u_form = UserUpdateForm(instance=request.user)#instance will show previous data in forms
        p_form = ProfileUpdateForm()#instance will show previous data in forms

    # Send form data to the template
    context = {
        'u_form': u_form,
        'p_form': p_form,
    }
    return render(request, 'users/profile.html', context)

我遇到错误:

django.db.utils.IntegrityError: (1062, "Duplicate entry '2' for key 'user_id'")

在这方面可以帮助我的任何专家吗?

2 个答案:

答案 0 :(得分:1)

更新 完成 这是views.py

@login_required
def profile(request):

    if request.method == 'POST':
        image_data = request.POST['image']
        b = json.loads(image_data)
        head, data = b["output"]["image"].split(',')
        binary_data = a2b_base64(data)
        profile = Profile()

        u_form = UserUpdateForm(request.POST, instance=request.user)
        p_form = ProfileUpdateForm(request.POST, request.FILES,instance=request.user.profile)

        if u_form.is_valid() and p_form.is_valid():
            u_form.save() # if yes Save
            profile.image.save('whatever.jpg', ContentFile(binary_data), save=False)

            t = Profile.objects.get(user_id=request.user.id)
            t.image = 'profile_pics/whatever.jpg'  
            t.save() 

            messages.success(request, format('Your Profile has been updated.'))
            return redirect('profile')
    else:
        u_form = UserUpdateForm(instance=request.user)#instance will show previous data in forms
        p_form = ProfileUpdateForm(instance=request.user.profile)#instance will show previous data in forms
    # Send form data to the template
    context = {
        'u_form': u_form,
        'p_form': p_form,
    }
    return render(request, 'users/profile.html', context)

如果您想知道如何转换base64图像,请参考此链接https://vinta.ws/code/read-and-save-file-in-django-python.html

答案 1 :(得分:0)

您的Profile对象与User是一对一的,这意味着,如果我没记错的话,创建Profile对象的唯一目的是添加附加字段。鉴于此,您不需要ID即可跟踪配置文件,而是依靠Django随附的User模型。尝试删除:

profile.user_id = request.user.id

,看看是否有帮助。基本上,在数据库中的某个位置,您尝试再次保存ID(主键)为2的User对象。如果您要保存对Profile对象所做的任何更改,请快速注意一下,

user = User.objects.get(id=request.user.id)
user.profile.some_property = some_value
user.save()