0

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)

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.