views:

22

answers:

2

hello, i have a method where i am saving the data from users, but each user has to have a single profile, so each time he saves, the data should be overwritten. first i verify if he already has a profile data, and in this case i add an instance to the form. if not, (this is his first registration), i simply add data into DB my code is: but i get an error:'QuerySet' object has no attribute '_meta' is my method right? thanks!

def save_userprofile(request):

   if request.method == 'POST':
        u = UserProfile.objects.filter(created_by = request.user)
        if u:

             form = UserProfileForm(request.POST, request.FILES,instance=u ) 
        else:
             form = UserProfileForm(request.POST, request.FILES)
+1  A: 

The instance argument of UserProfileForm doesn't expect to receive a QuerySet, which is what you're giving it. To retrive the profile, you should use this, which returns a single UserProfile object:

u = UserProfile.objects.get(created_by = request.user)
Justin Voss
+2  A: 

If you're expecting just one object back from a query, you should use the get() method.

from django.core.exceptions import ObjectDoesNotExist
try:
    u = UserProfile.objects.get(created_by = request.user)
    # can update here
except ObjectDoesNotExist:
    # create object

The queryset reference should explain all. You may also find get_or_create() is useful.

pycruft