尝试更新Django中的用户个人资料

时间:2019-10-16 21:02:08

标签: python django django-models

我希望可以更新portfolie_site字段和profile_image,所以我创建了ProfileUpdateForm,但是在保存输入时遇到了问题

我希望获得帮助,我不知道自己在做什么。 :)

更新!

现在:所以我可以更新urlfield,但不能更新imagefield

我更新了代码并添加了打印内容,以更清楚地了解正在发生的情况。 这就是我现在在命令行中得到的:

命令行

GET profile.html
[17/Oct/2019 11:12:51] "GET /accounts/profile/ HTTP/1.1" 200 1600
POST sending you back HOME
[17/Oct/2019 11:12:59] "POST /accounts/profile/ HTTP/1.1" 302 0
[17/Oct/2019 11:12:59] "GET / HTTP/1.1" 200 1100

Models.py

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    portfolio_site = models.URLField(blank=True)
    profile_image = models.ImageField(upload_to='swap_me/profile_image',blank=True)
    def __str__(self):
        return self.user.username

Forms.py

class ProfileUpdateForm(forms.ModelForm):
    class Meta():
        model = Profile
        fields = ("portfolio_site","profile_image")
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields["portfolio_site"].label = "Site"
        self.fields["profile_image"].label = "Image"

Views.py

@login_required
def profile_update(request):
    user = request.user
    form = ProfileUpdateForm(request.POST or None, instance=user.profile)
    if request.method == 'POST':
        if form.is_valid():
            form.save()
            print("POST sending you back HOME")
            return HttpResponseRedirect(reverse('home'))
        else:
            print("error")
    else:
        print("GET profile.html")
    context = {
        "profile_updateform":form,
    }
    return render(request, 'profile.html', context)

Profile.html

{% extends "base.html" %}
{% load staticfiles %}
{% block body_block %}

{% if user.is_authenticated %}
  <form enctype="multipart/form-data" method="POST">
    {% csrf_token %}
    {{ profile_updateform.as_p }}
    <input type="submit" name="" value="Update">
  </form>
{% else %}
  <h1>You need to login!</h1>
{% endif %}

{% endblock %}

1 个答案:

答案 0 :(得分:0)

您应该使用表单来保存模型:

@login_required
def profile_update(request):
    user = request.user
    form = ProfileUpdateForm(request.POST or None, initial={'profile_image': user.profile.profile_image,
                                                      'portfolio_site': user.profile.portfolio_site})
    if request.method == 'POST':
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('home'))
        else:
            print("Fist me daddy!")
    else:
        print(request.method)
    context = {
        "profile_updateform":form,
    }
    return render(request, 'profile.html', context)

更新

调用form.save()时,如果定义了实例,则表单对象将尝试更新现有模型,否则将尝试创建一个实例;否则,表单对象将尝试更新现有模型。由于您是使用initial手动添加数据的,因此该表单正在尝试在数据库中创建新的Profile行,但是该行没有必需的user_id(即{ {1}}字段),并抛出该错误。要解决此问题,您应该在表单中使用user而不是instance

initial