开发者

django forms instance

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 erro开发者_如何学JAVAr:'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)


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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜