在Django中添加头像,可以通过以下步骤实现:
pip install pillow
from django.db import models
from django.contrib.auth.models import User
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
avatar = models.ImageField(upload_to='avatars/', default='avatars/default_avatar.png')
上述代码中,头像字段名为avatar,它将上传的头像图片保存在avatars/目录下,并设置了一个默认头像。
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# 其他URL模式...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
from django import forms
from .models import UserProfile
class AvatarForm(forms.ModelForm):
class Meta:
model = UserProfile
fields = ['avatar']
from django.shortcuts import render, redirect
from .forms import AvatarForm
def upload_avatar(request):
if request.method == 'POST':
form = AvatarForm(request.POST, request.FILES)
if form.is_valid():
user_profile = form.save(commit=False)
user_profile.user = request.user
user_profile.save()
return redirect('profile') # 上传成功后跳转到用户个人资料页面
else:
form = AvatarForm()
return render(request, 'upload_avatar.html', {'form': form})
上述代码中,视图函数upload_avatar接收POST请求,处理用户上传的头像图片,并将其保存到用户的UserProfile模型中。
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">上传头像</button>
</form>
上述代码中,form.as_p将表单渲染为一个段落的形式,包含了头像上传字段。
from django.urls import path
from .views import upload_avatar
urlpatterns = [
# 其他URL模式...
path('upload_avatar/', upload_avatar, name='upload_avatar'),
]
上述代码中,将upload_avatar/路径与upload_avatar视图函数关联起来。
完成上述步骤后,你的Django应用将具备上传和保存用户头像的功能。用户可以访问/upload_avatar/路径来上传头像,上传成功后将跳转到用户个人资料页面。
领取专属 10元无门槛券
手把手带您无忧上云