如何在 Django 中编写视图来更新模型图像?

How to write view to update model image in django?

我用配置文件模型扩展了 django 用户模型。我想添加更新用户的个人资料功能。因为我将 num 字段设为唯一字段,所以在我的更新视图函数中,更新表单的 is_valid 始终是 False。我也无法更新照片 png?这是我的代码;

型号:

class Profile(models.model):
   user = models.OneToOneField(User,on_delete=models.CASCADE)
   num =models.CharField('identity',max_length=254,unique=True)
   photo = models.ImageField('image',upload_to = 'images/licences')

表格:

class ProfileForm(forms.ModelForm):
    class Meta:
        model= Profile
        fields = ['num','photo']

观看次数:

def modify_view(request):
    user = request.user
    if request.method=="POST":
        form = ProfileForm(request.POST,request.FILES)
        if form.is_valid() 
            user_profile = Profile.objects.get(user=user)
            user_profile.image = form.clean_data['image']
            user_profile.save()
    else:
        form = ProfileForm()
        return render(request,"profile.html",{form:form}) 

模板

{% extends  'account/home/index.html' %}
{% block content %}
<div class="row">
    <div class="col-md-8 col-sm-8 col-8">

      <form class="signup needs-validation" id="signup_form" method="post"  enctype="multipart/form-data" >
        {% csrf_token %}
        {{form.as_p}}
        {% if redirect_field_value %}
        <input type="hidden" name="{{ redirect_field_name }}" value="{{ redirect_field_value }}" />
        {% endif %}
        <div class="form-group">
            <button  type="submit" class="col-sm-8  offset-sm-4 btn btn-success btn-block">update</button> 
        </div>
      </form>
    </div>
  </div>
{% endblock %}

由于 num 字段是唯一的,不会在更新个人资料图像时再次生成,您可以忽略 request.POST 并将 instance 参数传递给 ProfileForm class.

示例

def modify_view(request):
    user = request.user
    if request.method=="POST":
        user_profile = Profile.objects.get(user=user)

        form = ProfileForm(files=request.FILES, instance=user_profile)
        if form.is_valid():
            user_profile.image = form.clean_data['image']
            user_profile.save()
    else:
        form = ProfileForm()
    return render(request,"profile.html",{form:form}