John Eipe
John Eipe

Reputation: 11228

update existing record or creating new

I'm trying to update the database if an entry is already there if not create a new one.

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})

It's throwing

(1062, "Duplicate entry '15' for key 'user_id'")

Upvotes: 1

Views: 9636

Answers (3)

ray6080
ray6080

Reputation: 893

You can use get_or_create which is much simpler.

Upvotes: 3

Eduardo Ivanec
Eduardo Ivanec

Reputation: 11862

You've got to use get for Django to fetch an existing object instead of creating a new one, which is what your call to UserProfiles(user=request.user) is currently doing.

For example:

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

See this link for more information.

Upvotes: 2

koniiiik
koniiiik

Reputation: 4382

First off, while it is true you can handle your forms manually this way, the “right way” to do forms with Django is to use django.forms. With this said…

I'll assume your UserProfiles model does not contain an explicit primary key. That means, Django creates its own field automatically, called id.

Now, when you create a new instance of a model using the constructor, the id field will remain empty. It will not fetch anything from the dabase, it will create a new object. Afterwards you assign some values to its fields. Note that the following two are equivalent:

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

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

since in both cases you just create a new object and set the values of user, location and email.

As soon as you try to save this object, you get an error.

The right way to do this is to first fetch the object from the database:

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.

For more information have a look at https://docs.djangoproject.com/en/dev/topics/db/queries/

Upvotes: 0

Related Questions