提问者:小点点

正在更新用户的配置文件pic,但不请求用户上传pic


我想更新数据库中用户的配置文件图片,但它不要求用户上传图片,在点击上传按钮它只是重定向我到页面。

models.py

from django.db import models
from django.contrib.auth.models import User


class userprofile(models.Model):
    user = models.OneToOneField(User,on_delete = models.CASCADE)
    profilepic = models.ImageField(default='pp.png',upload_to='profile_pic',blank = True)

Forms.py

from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from .models import userprofile



class ProfileUpdateForm(forms.ModelForm):
    class Meta:
        model = userprofile
        fields = ['profilepic',]

views.py


@login_required
def profile(request):    
    if request.method == 'POST':
        p_form = ProfileUpdateForm(request.POST,request.FILES,instance=request.user.userprofile)
        if p_form.is_valid():
            p_form.save()        
            return render(request,'profile.html')
    else:
        p_form = ProfileUpdateForm(instance=request.user.userprofile)

    context = {
        'p_form': p_form        
        }

    return render(request,'profile.html',context)

profile.html

<form method ="POST" class="sm:w-1/3 text-center sm:pr-8 sm:py-8" enctype="multipart/form-data" >
            {% csrf_token %}
            {{ p_form|crispy }}
            <img id="profile_pic" alt="team" class="flex-shrink-0 rounded-lg w-full h-56 object-cover object-center mb-4" src="{{user.userprofile.profilepic.url}}">            
            <input style="padding: 8px 93px;" class="text-white bg-green-500 border-0 py-2 px-8 focus:outline-none hover:bg-green-700 rounded text-lg" type="submit" value="Upload">
</form>

共1个答案

匿名用户

您在呈现时忘记添加上下文

return render(request,'profile.html', context)