我有一个这样的模型;我正在尝试使用以下字段创建注册:
username
first name
last name
email
address
profile image
class User(AbstractUser):
username = models.CharField(blank=True, null=True, max_length=50)
Email = models.EmailField(_('email address'), unique=True)
Address = models.CharField(max_length=100, default="")
UserProImage = models.ImageField(upload_to='accounts/',blank=True, null=False)
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['Email', 'first_name', 'last_name', 'Address', 'UserProImage']
def __str__(self):
return "{}".format(self.username)
def get_image(self, obj):
try:
image = obj.image.url
except:
image = None
return image
def perform_create(self, serializer):
serializer.save(img=self.request.data.get('UserProImage'))
为此模型,我编写了一个序列化器,如下所示:
class UserCreateSerializer(ModelSerializer):
Email = EmailField(label='Email Address')
ConfirmEmail = EmailField(label='Confirm Email')
class Meta:
model = User
fields = [
'username',
'first_name',
'last_name',
'Address',
'UserProImage',
'Email',
'ConfirmEmail',
'password',
]
extra_kwargs = {"password":
{"write_only": True}
}
objects = PostManager()
def __unicode__(self):
return self.username
def __str__(self):
return self.username
def validate(self, data):
return data
def perform_create(self, serializer):
serializer.save(self.request.data.get('UserProImage'))
return self.data.get('UserProImage')
def validate_email(self, value):
data = self.get_initial()
email1 = data.get('ConfirmEmail')
username = data.get('username')
email2 = value
if email1 != email2:
raise ValidationError("Emails must match.")
user_qs = User.objects.filter(email=email2)
username_qs = User.objects.filter(username=username)
if user_qs.exists():
raise ValidationError("This user has already registered.")
if username_qs.exists():
raise ValidationError("This user has already registered.")
return value
def validate_email2(self, value):
data = self.get_initial()
email1 = data.get('Email')
email2 = value
if email1 != email2:
raise ValidationError("Emails must match.")
return value
def create(self, validated_data):
username = validated_data['username']
email = validated_data['Email']
password = validated_data['password']
user_obj = User(
username=username,
email=email
)
user_obj.set_password(password)
user_obj.save()
return validated_data
当我运行服务器imagefiled(UserProImage)
为null
时,该如何解决?