UnboundLocalError:分配前已引用本地变量“电子邮件”

时间:2018-07-25 12:16:57

标签: python django-rest-framework

1. models.py

    class User(AbstractUser, BaseModel):
        full_name = models.CharField(max_length=64)
        addresss=models.CharField(max_length=40)
        phoneno=models.IntegerField(null=True, blank=True)
        email=models.EmailField()
        gender=models.IntegerField(choices=gender_choice,default='0')

class Student(BaseModel):
    user = models.ForeignKey(User, on_delete=models.CASCADE)

    father_name=models.CharField(max_length=64)
    mother_name=models.CharField(max_length=60)
    date_of_birth=models.DateField(null=True)

    def __str__(self):
        return self.user.full_name

2.Serializers.py

class UserPostSerializer(serializers.ModelSerializer):
    class Meta:
        model=User
        fields=('full_name','addresss','gender','id')
##Serializer Class for Student 
class StudentSerializer(serializers.HyperlinkedModelSerializer):
    user = UserPostSerializer()
    class Meta:
        model=Student
        fields=(
            'id',
            # 'father_name',
            # 'mother_name',
            # 'date_of_birth',
            'user',
            )

4.Views.py

class StudentViewset(viewsets.ModelViewSet):
    queryset = Student.objects.all()
    serializer_class = StudentSerializer

    http_methods = ['get', 'post','put','delete']


    def create(self, request):

        serializer=StudentSerializer(data=request.data)
        serializer.is_valid()
        row = serializer.data
        user = row['user']
        full_name = user['full_name']
        first_name = full_name.split(' ')[0]

        # email = first_name + '@schoolX.com'

        # _e = User.objects.filter(email=email)
        # if _e:
        #     email = first_name + str(+count) + '@schoolX.com'
        emailpattern =  '{}(\d*)@schoolx.com'.format(first_name)
        count = User.objects.filter(email__iregex=emailpattern).count()

        if count > 0:
            email = '{}{}@schoolx.com'.format(first_name, str(count))




        user,created = User.objects.get_or_create(email= email, 
            defaults={'full_name':row['user']['full_name'],'addresss':row['user']['addresss']})
        student = Student.objects.create(user_id=user.id)

        return Response({'email':email})

4.Urls.py

    router.register(r'students', views.StudentViewset)

当我尝试添加学生时,它显示出这样的错误;;

Internal Server Error: /students/
Traceback (most recent call last):
  File "/home/dinesh/.local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner
    response = get_response(request)
  File "/home/dinesh/.local/lib/python3.6/site-packages/django/core/handlers/base.py", line 128, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/home/dinesh/.local/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/dinesh/.local/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
    return view_func(*args, **kwargs)
  File "/home/dinesh/.local/lib/python3.6/site-packages/rest_framework/viewsets.py", line 103, in view
    return self.dispatch(request, *args, **kwargs)
  File "/home/dinesh/.local/lib/python3.6/site-packages/rest_framework/views.py", line 483, in dispatch
    response = self.handle_exception(exc)
  File "/home/dinesh/.local/lib/python3.6/site-packages/rest_framework/views.py", line 443, in handle_exception
    self.raise_uncaught_exception(exc)
  File "/home/dinesh/.local/lib/python3.6/site-packages/rest_framework/views.py", line 480, in dispatch
    response = handler(request, *args, **kwargs)
  File "/home/dinesh/Desktop/pro1/pro1/app1/views.py", line 50, in create
    user,created = User.objects.get_or_create(email= email,
UnboundLocalError: local variable 'email' referenced before assignment
[25/Jul/2018 12:04:05] "POST /students/ HTTP/1.1" 500 14800

然后我该如何解决该错误?我尝试了更多的方法,但无法修复..任何人都可以帮助解决此问题

1 个答案:

答案 0 :(得分:0)

取消注释此行-

# email = first_name + '@schoolX.com' 

或将电子邮件设置为空-

email = ''

检查是否为count > 0,因为如果没有,则不会分配email变量,这就是为什么

local variable 'email' referenced before assignment

您正在引用email行-

user,created = User.objects.get_or_create(email= email,...

在分配count < 0之前