更新“关于我”字段

时间:2016-03-27 09:49:57

标签: django django-models django-views

我在尝试提交快速表单以更新用户的“关于我”部分时遇到了很大困难。这是一个可选字段,用户可以根据需要将其留空。我无法理解!

models.py:

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    activation_key = models.CharField(max_length=40, blank=True)
    key_expires = models.DateField(default=datetime.date.today())
    about_me = models.CharField(max_length=500, blank=True, null=True, default='')
    portfolio_site = models.URLField(max_length=200, blank=True, null=True, default='')

    def __str__(self):
        return self.user.username

forms.py:

class UserForm(forms.Form):
    class Meta:
        model = User
        fields = ['first_name', 'last_name', 'password', 'email', 'username']

class ProfileForm(forms.Form):
    class Meta:
        model = UserProfile
        fields = ['about_me', 'portfolio_site']

views.py:

@login_required(login_url='sign_in')
def update_about(request, user_id):
    # Accquire submitted data and place to "data"
    data = request.POST

    # Isolate submitted data under "id_about_me", and place it to "about_me"
    about_me = data.get('id_about_me')

    new_about = UserProfile(id=request.user.id, about_me=about_me)
    new_about.save()


    return HttpResponse('Great Job!')

如果我使用“user_id = request.user.id”,则说:

IntegrityError at /update_about/1/
UNIQUE constraint failed: register_userprofile.user_id

如果我使用“id = request.user.id”,则说:

IntegrityError at /update_about/1/
NOT NULL constraint failed: register_userprofile.user_id

我可以很好地处理其他更新,但这个让我感到难过!

2 个答案:

答案 0 :(得分:1)

我认为这是因为您正在创建UserProfile模型的新实例并为其分配相同的user_id,从而导致Unique constraint错误。您应首先检索已存在的模型并进行修改,如下所示:

new_about = UserProfile.objects.get(user_id=user_request_id)
new_about.about_me = about_me
new_about.save()

告诉我这是否有效。但是,如果user_id是您的自动主键字段,则这应该不是问题。

答案 1 :(得分:0)

如果配置文件已存在,则需要创建或获取配置文件:

profile,created = UserProfile.objects.get_or_create(user=request.user)
profile.about_me = about_me
profile.save()

但你为什么不使用表格?

from django.shortcuts import redirect, render
from .forms import ProfileForm

@login_required(login_url='sign_in')
def update_about(request, user_id):
    form = ProfileForm(request.POST or None)
    if form.is_valid():
       profile = form.save(commit=False)
       profile.user = request.user
       profile.save()
       return redirect('/')
    return render(request, 'update_profile.html', {'form': form})

您的模板只有正常的表单呈现逻辑:

<form method="POST">
   {% csrf_token %}
   {{ form }}
   <input type="submit">
</form>