Reputation: 6555
I'm using Tastypie to create a user via an API call (see the api.py below). Any error triggers same except IntegrityError
as you can see. I would like for my model to rise the correct error messages back to the user. Example see the model manager below, when a email is blank the error 'The given email must be set' should be give back to the user as an IntegrityError error.
How should I do this?
api.py
class CreateResource(ModelResource):
"""
API Facet that creates and returns a new user with self.user_email
as login and self.user_password as password.
"""
class Meta:
object_class = CompanyUser
resource_name = 'accounts/create'
fields = ['password1', 'password2', 'email', 'company']
allowed_methods = ['post']
queryset = CompanyUser.objects.all()
serializer = urlencodeSerializer()
def obj_create(self, bundle, request=None, **kwargs):
try:
CompanyUser.objects.create_user(email=bundle.data['email'],
company=bundle.data['company'],
)
except IntegrityError:
raise BadRequest('Username already exists')
Model Manager
class EmailUserManager(BaseUserManager):
def create_user(self, email, password=None, **extra_fields):
"""
Creates and saves an EmailUser with the given email and password.
"""
now = timezone.now()
if not email:
raise ValueError('The given email must be set')
email = EmailUserManager.normalize_email(email)
user = self.model(email=email, is_staff=False, is_active=True,
is_superuser=False, last_login=now,
date_joined=now, **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
As I see it my options are:
1) In the api.py check all parameters one by one (which seems bad as my model does this already) then rise a IntegrityError
for each issue I have i.e. email blank.
if bundle.data['email'] = '':
raise BadRequest('no email')
2) Somehow return back the error from the manager to the api.py file and rise a dynamic IntegrityError.
Upvotes: 3
Views: 253
Reputation: 8354
If your using TastyPie then lookup validation. You can then use your forms.py methods to validate.
Upvotes: 2