python - Django 无法更新用户个人资料图片

标签 python django forms image model

我创建了一个自定义 UserProfile 模型,并希望允许用户编辑他或她的个人资料字段。其他字段是可编辑的,但 ImageField 不可编辑。我能够将上传的图像存储到我的目标目录 (media/profile_pics) 中,但我不确定如何将其链接到当前登录的用户,以便他或她可以导航回个人资料页面并查看新图片。

我的views.py中的代码非常困惑。我希望有人能教我一种更好的方法,因为它是在部分理解的情况下拼凑在一起的。

models.py

#custom user profile
class UserProfile(models.Model):
    user = models.OneToOneField(User)
    description = models.CharField(max_length=200, default='')
    city = models.CharField(max_length=100, default='')

    profile_pic = models.ImageField(upload_to='profile_pics', blank=True)

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

def create_profile(sender, **kwargs):
    #if user object has been created, we want to create user profile
    if kwargs['created']:
                                                    #returns the instance of our user object
        user_profile = UserProfile.objects.create(user=kwargs['instance'])
#connecting to the post_save signal. Pass in a function that should run
post_save.connect(create_profile, sender=User)

当用户导航到可以编辑其个人资料的位置时,将使用查看功能“edit_profile”。它位于 views.py 中:

def edit_profile(request):
    user_profile = UserProfile.objects.get(user=request.user)
    profile_form = UserProfileForm(instance=user_profile)

    if request.method == 'POST':
        update_profile_form = UserProfileForm(data=request.POST, instance=user_profile)

                                            #so we know the user object
        form = EditProfileForm(request.POST, instance=request.user)

        if form.is_valid() and update_profile_form.is_valid():
            user = form.save()
            update_profile_form.save()

            handle_uploaded_file(request, request.FILES['profile_pic'])

            #return redirect(reverse('userapp:profile'))
            args = {'profile_form': update_profile_form}

            return render(request, 'userapp/profile.html', args)

    else:
        form = EditProfileForm(instance=request.user)
        args = {'form': form, 'profile_form': profile_form}
        return render(request, 'userapp/edit_profile.html', args)

edit_profile 使用以下函数将文件保存到我的目标目录中。这是取自 Django 文档:

def handle_uploaded_file(request, f):
    with open(os.getcwd() + "/media/profile_pics/" + f.name, 'wb+') as destination:
        for chunk in f.chunks():
            destination.write(chunk)

forms.py

class UserProfileForm(forms.ModelForm):
   # profile_pic = forms.ImageField()
    class Meta:
        model = UserProfile
        fields = ('profile_pic','city', 'description',)



class EditProfileForm(UserChangeForm):
    #template_name='/something/else'

    class Meta:
        model = User
        fields = (
            'email',
            'first_name',
            'last_name',
            'password'
            #'profile_pic'
        )

我显示以下 HTML“edit_profile.html”供用户更新字段:

{% extends 'base.html' %}
{% block title %} Profile {% endblock %}


{% block body %}
    <div class="container-fluid">
        <form method="post" enctype='multipart/form-data'>
            {% csrf_token %}
            {{  form.as_p }}
            {{ profile_form.as_p }}

            <button type="submit">Submit</button>

        </form>
        <br>
    </div>

{% endblock %}

这是用户配置文件 HTML。更新后,当用户导航回个人资料时,应显示他们新上传的图片:

{% extends 'base.html' %}
{% block title %} Profile {% endblock %}


{% block body %}
    <div class="container-fluid">
        <h2>Profile</h2>
        <p>{{ user }}</p>
        <p>First name: {{ user.first_name }}</p>
        <p>Last name: {{ user.last_name }}</p>
        <p>Email: {{ user.email }}</p>
        <p> City: {{ profile_form.instance.city }}</p>
        <p> Description: {{ profile_form.instance.description }}</p>
        <p>
            {% if profile_form.instance.profile_pic %}
                <img src="{{ profile_form.instance.profile_pic.url}}" border-radius=10px style="width:256px;height:256px;" />
            {% endif %}
        </p>


    </div>

{% endblock %}

最佳答案

您必须以表单形式传递request.FILES。看到这里https://docs.djangoproject.com/en/1.10/topics/http/file-uploads/

关于python - Django 无法更新用户个人资料图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43443733/

相关文章:

python - 如何将列表 "one by one"写入 python 中的二进制文件?

html - 与 Django 一起使用时,Bootstrap Navbar 不会变色

php - 更新一段时间制作的表格 - 表格

javascript - 在不安全的前端计算价格?

delphi - Application.Restore 无法让我回到之前的位置,为什么?

python - 将注释的列名称读取到 pandas 中

python - 如何将负位表示的数字转换为 python3 中的实际负 int 值?

python 多处理和 mmap

python - 数字 cargo 市场

Django 模板上下文多个 View