2012-04-26 12 views
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}) 

それはあなたが既存のをフェッチするためにDjangoのためgetを使うために持って

(1062、 "キー 'のuser_id' の重複エントリー '15'")

答えて

2

を投げています新しいオブジェクトを作成するのではなく、オブジェクトを作成します。これはUserProfiles(user=request.user)への呼び出しが現在行っている作業です。例えば

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

詳細についてはthis linkを参照してください。

0

まず、この方法でフォームを手動で処理できますが、Djangoでフォームを行う「正しい方法」はdjango.formsを使用することです。これは言った...

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

コンストラクタを使用してモデルの新しいインスタンスを作成すると、idフィールドは空のままです。これは、データベースから何もフェッチしません、それは新しいオブジェクトを作成します。その後、フィールドにいくつかの値を割り当てます。

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

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

両方のケースで、あなただけの新しいオブジェクトを作成し、userlocationemailの値を設定するため、次の二つが等価であることに注意してください。

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

これを行うための正しい方法は、最初にデータベースからオブジェクトをフェッチすることです。詳細については

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. 

はあなたがはるかに簡単であるget_or_createを使用することができますhttps://docs.djangoproject.com/en/dev/topics/db/queries/

3

を見てみましょう。

+1

壊れたリンク。可能であれば更新してください。 –

関連する問題