允许用户从后端反映后端(Django Admin)

时间:2017-01-13 17:28:25

标签: python django web web-frontend

我试图让我的用户从前端更新他们的个人资料,允许它反映在django管理员,特别是更新个人资料图片。 user.first_nameuser.last_name的更改工作正常,但图像也不会反映在后端。 我认为我缺少一些东西加上当firstname和lastname的字段为空时它发布为null我想我会使用一个例外,但我更关心的是配置文件图像。请帮助我,我没有得到它

这是我的代码

#views.py
    def edit_user_profile(request, username):
        user = request.user
        form = EditProfileForm(request.POST or None, request.FILES, initial={'first_name': user.first_name, 'last_name': user.last_name})
        if request.method == 'POST':
            if form.is_valid():
                # user.photo = UserExtended(photo=request.FILES['photo'] or None, )
                photo = UserExtended.objects.get(user=user)
                user.first_name = request.POST['first_name']
                user.last_name = request.POST['last_name']
                # username = request.POST['username']
                photo.save()
                user.save()
                context = {
                    'form': form,
                }

                return render(request, 'accounts/profile_updated.html', context)
        context = {
            'form': form,
            'username': username,

        }

        return render(request, 'accounts/edit_profile.html', context)

#model.py
    @python_2_unicode_compatible  # only if you need to support Python 2
    class UserExtended(models.Model):
        user = models.OneToOneField(User, related_name='user')
        photo = models.ImageField(upload_to='media/user_media/users', verbose_name='Profile Picture',
                                  default='/media/user_media/avatars/avatar.png', blank=True)
        address = models.CharField(max_length=255)
        phoneNumber = models.CharField(max_length=11)

        class Meta:
            verbose_name_plural = _("user")

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

        def image_tag(self):
            if self.photo:
                return mark_safe('<img src="/media/%s" width="150" height="150" />' % self.photo)
            else:
                return mark_safe('<img src="/media/user_media/avatars/avatar.png" width="150" height="150" />')

        image_tag.allow_tags = True
        image_tag.short_description = 'Profile Avatar'


    def create_profile(sender, **kwargs):
        user = kwargs["instance"]
        if kwargs["created"]:
            user_extended = UserExtended(user=user)
            user_extended.save()


    post_save.connect(create_profile, sender=User)


#forms.py

    class EditProfileForm(forms.ModelForm):
        first_name = forms.CharField(label='First Name', widget=forms.TextInput(attrs={'class': 'form-control'}),
                                     required=False)
        last_name = forms.CharField(label='Last Name', widget=forms.TextInput(attrs={'class': 'form-control'}),
                                    required=False)
        # username = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'}), required=True)
        photo = forms.ImageField(label='Change Profile Image', required=False)

        class Meta:
            model = User
            fields = ['photo', 'first_name', 'last_name', ]  # 'username',
            """

提前谢谢..

1 个答案:

答案 0 :(得分:0)

好的,在使用PyCharm进行调试时,我发现我使用的是User类的实例,而不是我的UserExtended的照片。我想自从发布user.fist_nameuser.last_name以来,我感觉太舒服了。这是解决方案:

#views.py
def edit_user_profile(request, username):
    user = request.user
    form = EditProfileForm(request.POST or None, request.FILES, initial={'first_name': user.first_name, 'last_name': user.last_name})
    if request.method == 'POST':
        if form.is_valid():
            #photo = UserExtended(photo=request.FILES['photo'] or None, )
            user_extended = UserExtended.objects.get(user=user)
            user.first_name = request.POST['first_name']
            user.last_name = request.POST['last_name']
            user_extended.photo = form.cleaned_data["photo"]
            # username = request.POST['username']
            user_extended.save()
            user.save()
            context = {
                'form': form,
            }

            return render(request, 'accounts/profile_updated.html', context)
    context = {
        'form': form,
        'username': username,

    }

    return render(request, 'accounts/edit_profile.html', context)