首页 > 解决方案 > 如何让用户在不使用 Django 表单的情况下手动在 Django 中保存或编辑他的个人资料信息

问题描述

我正在研究引导模板。但是在数据库中保存配置文件信息时出现问题。这是我的代码。我不知道我是否做得对。但它不起作用。

模型.py

class Profile(models.Model):
  user = models.OneToOneField(User, on_delete=models.CASCADE)
  Propic = models.ImageField(upload_to="Banners/", null=True,blank=True)
  bio = models.TextField(max_length=500, blank=True)
  location = models.CharField(max_length=30, blank=True)

视图.py

def profile(request):
ids = request.user.id
user = User.objects.get(pk=ids)
if request.method == "POST":
    bio = request.POST["bio"]   
    location = request.POST["location"]
    image = request.FILES['pic']

    form = user.profile(bio = bio , location = location , propic=image)
    form.save() 
    return HttpResponse("info saved")

return render(request, "dashbord/user.html", {"user": user })

标签: pythondjangodjango-modelsdjango-formsdjango-views

解决方案


谢谢你们的帮助。我弄清楚该怎么做。您需要像这样单独保存每一列。

def profile(request , *args, **kwargs):
  ids = request.user.id
  user = User.objects.get(pk=ids)
  if request.method == "POST":  
     if "bio" in request.POST and "location" in request.POST:

        bio = request.POST["bio"]   
        location = request.POST["location"]

        user.profile.bio = bio 
        user.profile.location = location
        user.profile.save()

    elif "image" in request.FILES:

        image = request.FILES['image']  
        user.profile.Propic.save(image.name , image)

   return render(request, "dashbord/user.html", {"user": user })

推荐阅读