Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Jkmarx/group name duplicate error #1573

Merged
merged 9 commits into from
Jan 17, 2017
9 changes: 8 additions & 1 deletion refinery/core/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@
from django.template import loader, Context
from django.core.cache import cache
from django.core.signing import Signer
from django.db import IntegrityError
from django.forms import ValidationError
from guardian.shortcuts import get_objects_for_user, get_objects_for_group
from guardian.models import GroupObjectPermission
from tastypie import fields
Expand Down Expand Up @@ -2018,7 +2020,12 @@ def obj_create(self, bundle, **kwargs):
user = bundle.request.user
data = json.loads(bundle.request.body)
new_ext_group = ExtendedGroup(name=data['name'])
new_ext_group.save()
try:
new_ext_group.save()
except (ValidationError, IntegrityError) as e:
raise ImmediateHttpResponse(HttpBadRequest(
'Invalid group creation request: %s.' % e
))
new_ext_group.user_set.add(user)
new_ext_group.manager_group.user_set.add(user)
return bundle
Expand Down
2 changes: 1 addition & 1 deletion refinery/core/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -1875,7 +1875,7 @@ def get_managed_group(self):
def save(self, *args, **kwargs):
Copy link
Member

@hackdna hackdna Jan 5, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It looks like the preferred way to validate model fields is via full_clean() and clean() model methods instead of overriding save(): https://docs.djangoproject.com/en/1.7/ref/models/instances/#django.db.models.Model.clean

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also, the group name cannot be blank already: name = models.CharField(_('name'), max_length=80, unique=True), so no additional checking for that is necessary. It might be a good idea to strip whitespace characters though.

if len(self.name) == 0:
logger.error("Group name cannot be empty.")
return
raise ValidationError('Group name cannot be empty')
else:
super(ExtendedGroup, self).save(*args, **kwargs)

Expand Down