尝试检索注册用户时出错

时间:2016-11-19 20:44:20

标签: python django django-rest-framework

我正在尝试通过CustomUser模型及其序列化程序来注册新用户并显示它们。

这是我的模特:

class CustomUser(models.Model):
user = models.OneToOneField(User)
additional_field = models.CharField(max_length=30, default='', blank=True)

我的序列化程序(来自Django REST Framework Creating custom user):

class CustomUserSerializer(serializers.ModelSerializer):
additional_field = serializers.CharField(source='customuser.additional_field')
class Meta:
    model = User
    fields = ('id', 'username', 'password', 'first_name', 'last_name', 'email', 'additional_field')

def create(self, validated_data):
    profile_data = validated_data.pop('customuser', None)
    user = super(CustomUserSerializer, self).create(validated_data)
    self.create_or_update_profile(user, profile_data)
    return user

def update(self, instance, validated_data):
    profile_data = validated_data.pop('customuser', None)
    self.create_or_update_profile(instance, profile_data)
    return super(CustomUserSerializer, self).update(instance, validated_data)

def create_or_update_profile(self, user, profile_data):
    profile, created = CustomUser.objects.get_or_create(user=user, defaults=profile_data)
    if not created and profile_data is not None:
        super(CustomUserSerializer, self).update(profile, profile_data)

我的观点,分别显示和注册用户:

def get_all_users(request):

all_friends = CustomUser.objects.all()

serial = CustomUserSerializer(all_friends, many=True)
json_data = JSONRenderer().render(serial.data)

return HttpResponse(json_data, content_type='application/json')


@api_view(['POST'])
def register_new_user(request):

if request.method == 'POST':
    print('POST request !')

    print(request.data)
    serializer = CustomUserSerializer(data=request.data)

    if serializer.is_valid():

        serializer.save()
        print('save friend!')
        return HttpResponse(status.HTTP_201_CREATED)

    else:
        print(serializer.errors)
        return HttpResponse(status.HTTP_403_FORBIDDEN)

虽然我可以使用以下代码注册用户:

import requests
import json

json_data = {'username': 'mylogin99', 'password': 'mypassword', 'email': 'mymail99@wanadoo.fr', 'additional_field' : 'myaddfield'}
r = requests.post('http://127.0.0.1:8000/register_new_user', json=json_data)

我无法显示注册用户,因为我收到以下错误:

AttributeError at /getAllUsers
Got AttributeError when attempting to get a value for field `username` on serializer `CustomUserSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `CustomUser` instance.
Original exception text was: 'CustomUser' object has no attribute 'username'.

我不明白为什么username字段未引用username模型的User字段。

1 个答案:

答案 0 :(得分:0)

我能想出的最好方法是在CustomUser模型中实现as_json方法:

def as_json(self):
    return dict(
        id=self.user.id, username=self.user.username,
        password=self.user.password, email=self.user.email,
        additional_field=self.additional_field)

因此,为了检索所有注册用户,我修改了get_all_user方法:

@api_view(['GET'])
def get_all_users(request):

    # retrieve all CustomUser objects
    all_friends = CustomUser.objects.all()
    lst = [friend.as_json() for friend in all_friends]
    json_data = JSONRenderer().render(lst)

    return HttpResponse(json_data, content_type='application/json')