1

新しいエントリを作成しない場合、エントリが既に存在する場合はデータベースを更新しようとしています。

def saveprofile(request):
    location = request.POST['location']
    email = request.POST['email']
    if request.user.is_authenticated():
        userprofile = UserProfiles(user=request.user)
        if userprofile:
           userprofile.location=location
           userprofile.email=email
           userprofile.save()
           return render_to_response('profile.html',{'pfields':userprofile})
        else:
           userprofile = UserProfiles(user=request.user, location=location, email=email)
           userprofile.save()
           return render_to_response('profile.html',{'pfields':userprofile})

投げてる

(1062、「キー 'user_id' のエントリ '15' が重複しています」)

4

3 に答える 3

3

get_or_createはるかに簡単な方を使用できます。

于 2014-03-31T01:46:45.593 に答える
2

Djangoを使用getして、新しいオブジェクトを作成する代わりに既存のオブジェクトをフェッチする必要があります。これは、UserProfiles(user=request.user)現在の呼び出しが行っていることです。

例えば:

try:
    userprofile = UserProfiles.objects.get(user=request.user)
except DoesNotExist:
    # create object here.

詳細については、このリンクを参照してください。

于 2012-04-26T16:55:40.530 に答える
0

まず、この方法でフォームを手動で処理できるのは事実ですが、Django でフォームを処理する「正しい方法」は を使用することdjango.formsです。これで…</p>

UserProfilesモデルに明示的な主キーが含まれていないと仮定します。つまり、Django は という独自のフィールドを自動的に作成しますid

これで、コンストラクターを使用してモデルの新しいインスタンスを作成すると、idフィールドは空のままになります。データベースから何も取得せず、新しいオブジェクトを作成します。その後、いくつかの値をそのフィールドに割り当てます。次の 2 つは同等であることに注意してください。

userprofile = UserProfiles(user=request.user, location=location, email=email)

# and
userprofile = UserProfiles(user=request.user)
userprofile.location=location
userprofile.email=email

どちらの場合も、新しいオブジェクトを作成し、 と の値を設定するuserだけlocationですemail

このオブジェクトを保存しようとすると、すぐにエラーが発生します。

これを行う正しい方法は、最初にデータベースからオブジェクトを取得することです。

try:
    profile = UserProfiles.objects.get(user=request.user)
except DoesNotExist:
    # Handle the case where a new object is needed.
else:
    # Handle the case where you need to update an existing object.

詳細については、https://docs.djangoproject.com/en/dev/topics/db/queries/をご覧ください。

于 2012-04-26T16:58:57.377 に答える