头像上传实例

1:定义表单
2:定义处理函数
3:路径设置
4:显示头像
其他Model迁移等问题,不再涉及,其他文章中有

class User(models.Model):
    username = models.CharField(max_length=30)
    password = models.CharField(max_length=20)
    register_date = models.DateField(auto_now_add=True)
    portrait = models.ImageField(upload_to="headers/", default="headers/default.jpg")
    gender = models.CharField(max_length=5)
    introduction = models.CharField(max_length=60)
    phone = models.IntegerField()

1:定义表单

        
        
    


2:定义处理函数
# 实现注册表单的处理
def register_handle(request):
    if request.method == "POST":
        username = request.POST["username"]
        password = request.POST["password"]
        phone = request.POST["phone"]
        gender = request.POST["gender"]
        img = request.FILES["img"]
        user = User()
        user.username = username
        user.password = password
        user.phone = phone
        user.gender = gender
        user.portrait = img
        user.save()
        request.session["username"] = username
        # context = {"username": username}
        # return redirect("/pianke/")   # render不会把session中的数据传回前台的但是redirect会
        # return redirect(reverse("pianke:")) # 因为render不会改变路径所以不能够触发index函数进行session里面数据的获取
        return render(request,"pianke/index.html")# 而redirect可以进行url的更新所以可以取到数据
    else:
        return HttpResponse("error")

3:路径设置

4:显示头像

将头像的路径从数据库传到前台


def logined_index(request):
    # return HttpResponse("index")
    articlelist = Article.objects.all()
    username = request.session.get("username")
    user = User.objects.get(pk=13) #将某张图片取出来
    # print(user.header.url)
    # return render(request, 'pianke/logined_index.html', {'portrait': user.portrait})
    context = {
        "username": username,
        "articlelist": articlelist,
        "portrait": user.portrait,
    }
    return render(request, "pianke/logined_index.html", context)

头像路径的拼接

     

你可能感兴趣的:(头像上传实例)