如何从数据库中检索用户名?

时间:2014-04-14 12:49:23

标签: python django

请帮助解决错误

我添加到站点并访问授权系统到用户配置文件。每个用户都可以更改登录。为此,他必须以下面的形式进入登录并点击提交:

from django import forms
from userprofile.models import UserProfile
from django.contrib.auth.models import User
from django.conf import settings
import os


class UserProfileForm (forms.ModelForm):
class Meta:
model = UserProfile
fields = ('family', 'name', 'nation', 'status', 'login', 'nation_show')

def clean_family (self):
family = self.cleaned_data ['family']
letters_quantity = len (family)
if letters_quantity < 4 :
raise forms.ValidationError (" little beech in the name! " )

return family

def clean_login (self):
login = self.cleaned_data ['login']. strip ()
if login! ='':
login_form_db = User.objects.filter (username = 'qwe')
if login_form_db:
login_form_db = login_form_db.username



if login == login_form_db:
raise forms.ValidationError (" this username is busy " )
else:
User.username = login
User.save (self)

return login

但最后我收到以下消息错误:

AttributeError at / userprofile /
'QuerySet' object has no attribute 'username'
Request Method: POST
Request URL: http://127.0.0.1:8000/userprofile/
Django Version: 1.6.2
Exception Type: AttributeError
Exception Value:
'QuerySet' object has no attribute 'username'
Exception Location: c: \ Python33 \ django_projects \ mutants \ userprofile \ forms.py in clean_login, line 26

1 个答案:

答案 0 :(得分:2)

filter()返回一个查询集。由于您需要按用户名获取User对象,请改用get()

login_form_db = User.objects.get(username='qwe')