属性错误 - ' QuerySet'对象没有属性

时间:2015-02-18 07:25:54

标签: python django modelform

如果我的普通用户的模型对象已经存在但是它给出了属性错误,我试图创建一个初始化的表单

my views.py-

def edit_profile(request):
    if request.method == 'POST':
        post = request.POST
        if 'save' in post:
            form = user_profile_form(post)
            if form.is_valid():
                f = form.save(commit = False)
                f.username = request.session.get('username')
                f.save()
                return redirect('wall')
            else:
                return redirect('error')
    else:
        if 'username' in request.session:
            u = user_profile.objects.filter(username = request.session.get('username', ''))
            if u:
                form = user_profile_form(initial = {'last_name': u.last_name})
                u.delete()
            else:
                form = user_profile_form()
            return render(request, 'wall/edit_profile_page.html', {'form': form})
        else:
            return redirect('error')

和我的models.py -

class user_profile(models.Model):
    username = models.CharField(max_length = 30, blank = True)
    first_name = models.CharField(max_length = 30, blank = True)
    last_name = models.CharField(max_length = 30, blank = True)

它正在给出错误 -

'QuerySet' object has no attribute 'last_name'

即使你存在

提前致谢

2 个答案:

答案 0 :(得分:1)

你可以试试这个

try:
   u = user_profile.objects.get(username =request.session.get('username', None))
   form = user_profile_form(initial = {'last_name': u.last_name})
   u.delete()
except ObjectDoesNotExist:
   form = user_profile_form()

答案 1 :(得分:0)

Queryset是对象的“列表”。您应该使用first()方法从查询集中获取第一个实例:

u = user_profile.objects.filter(username=request.session.get('username', '')) \
                        .first()