python - 即使使用 DJANGO 模型表单提交后,图片也不会在数据库中更新

标签 python django django-models

我打算在 django 中制作一个带有个人资料图片的用户个人资料模型。

一切正常,但我无法更新用户的个人资料图片。

表单正在网站上显示,但单击提交后,数据库中看不到任何更改,并且图像也未上传。

下面是我的 HTML 表单代码。

<form method="POST" action="{% url 'profile' %}" enctype="multipart/form-data">
                                {% csrf_token %}
                                {{ form.as_p }}

                                  <br><br>
                                <div class="mb-3"><button class="btn btn-primary btn-sm" name="_picture" type="submit">Change Photo</button></div>
                            </form>

下面是代码 models.py,用于创建用户配置文件模型。

class UserProfileInfo(models.Model):

    # Create relationship (don't inherit from User!)
    user = models.OneToOneField(User, on_delete=models.CASCADE)

    isInstructor = models.BooleanField(default=False)
    department = models.ForeignKey(Department,on_delete=models.CASCADE)
    role = models.ManyToManyField(Role)

    profile_picture = models.FileField(upload_to='static/profile_pic/'+str(time.time()),default='d.jpeg')

    address = models.TextField(max_length=256)
    city = models.TextF
class UpdateProfilePic(ModelForm):
    class Meta:
        model = UserProfileInfo
        fields = ['profile_picture']

下面是views.py的代码

    @login_required
   def profile(request):

    current_user_profile = UserProfileInfo.objects.get(user=request.user)
    current_user = request.user

    form = UpdateProfilePic(instance=current_user_profile)

    context = {'current_user':current_user,'current_user_profile':current_user_profile,'form':form}
    if request.method=='POST':

        if '_user' in request.POST:
            temp_user = request.user
            temp_user.username = request.POST.get('username')
            temp_user.email = request.POST.get('email')
            temp_user.first_name = request.POST.get('first_name')
            temp_user.last_name = request.POST.get('last_name')
            temp_user.save()
            context = {'current_user':current_user,'current_user_profile':current_user_profile,'form':form}
            return render(request,'instructor_app/profile.html',context)

        if '_profile' in request.POST:
            temp_user_profile = UserProfileInfo.objects.get(user=request.user)
            temp_user_profile.address = request.POST.get('address')
            temp_user_profile.city = request.POST.get('city')
            temp_user_profile.pincode = request.POST.get('pincode')
            temp_user_profile.save()
            context = {'current_user':current_user,'current_user_profile':current_user_profile,'form':form}
            return render(request,'instructor_app/profile.html',context)

        if '_picture' in request.POST:
            print("in picture")
            form = UpdateProfilePic(request.POST, instance=UserProfileInfo.objects.get(user=request.user))
            form.save()
            context = {'current_user':current_user,'current_user_profile':current_user_profile,'form':form}
            return render(request,'instructor_app/profile.html',context)
    else:
        return render(request,'instructor_app/profile.html',context)

请帮我编写代码!

最佳答案

您可以通过创建模型表单或简单的 Django 表单(如下所示)并使用表单的 action 属性来传递文件来编辑模型。

你可以试试这个:

表单.py

from django import forms


class UpdateProfilePic(forms.Form):
    image = forms.ImageField()

在你的观点中.py

if '_picture' in request.POST:
            form = UpdateProfilePic(request.POST, request.FILES)
            if form.is_valid():
                m = UserProfileInfo.objects.get(user=request.user)
                m.profile_picture = form.cleaned_data['image']
                m.save()
                return redirect('/profile')

以及您的 HTML 文件

<form action="{% url 'profile' %}" method="POST" enctype="multipart/form-data">
                                    {% csrf_token %}
                                    <div class="input-group">
                                        <div class="custom-file">
                                          <input type="file" class="custom-file-input" id="inputGroupFile04" aria-describedby="inputGroupFileAddon04" name="image">
                                          <label class="custom-file-label" for="inputGroupFile04">Choose file</label>
                                        </div>
                                        <div class="input-group-append">
                                          <button class="btn btn-primary" type="submit" name="_picture" id="inputGroupFileAddon04">Upload</button>
                                        </div>
                                      </div>

                                </form>

关于python - 即使使用 DJANGO 模型表单提交后,图片也不会在数据库中更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62221998/

相关文章:

python如何将css文件解析为键值

python - 没有为 pandas boxplot (groupby) 设置标题

Django REST框架: Create/Update object using Related Field

python - Django:模型索引太慢

django - 覆盖管理员中的 save_form 对于内联管理员不起作用

python - 如何使用列表理解将列表附加到现有列表

django - 如何创建一个 Django 自定义字段来存储 MYSQL DATETIME(6) 并在 Django/MySQL 中启用小数秒(毫秒和或微秒)?

python - django 将关系添加到用户模型

python - 其他应用程序中的 Django 迁移文件?

python - pdb:在不在 sys.path 中的文件上设置断点