From 175c0102967ad02293d6cb16be3b5a4689a939f0 Mon Sep 17 00:00:00 2001 From: Akita Noek Date: Fri, 10 Jun 2016 11:53:52 -0400 Subject: [PATCH] Attach labels instead of erroring on creation if label already exists If a label already exists, don't error out when trying to post to the job_templates/n/labels endpoint, instad just lookup the ID and attach it. This is primarily to benefit the UI, but in general seems like a good behavior for this endpoint anyways. Fixes #2135 --- awx/api/views.py | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/awx/api/views.py b/awx/api/views.py index 734640577b..6bd917cab2 100644 --- a/awx/api/views.py +++ b/awx/api/views.py @@ -2497,6 +2497,18 @@ class JobTemplateLabelList(SubListCreateAttachDetachAPIView, DeleteLastUnattachL parent_model = JobTemplate relationship = 'labels' + def post(self, request, *args, **kwargs): + # If a label already exists in the database, attach it instead of erroring out + # that it already exists + if 'id' not in request.data and 'name' in request.data and 'organization' in request.data: + existing = Label.objects.filter(name=request.data['name'], organization_id=request.data['organization']) + if existing.exists(): + existing = existing[0] + request.data['id'] = existing.id + del request.data['name'] + del request.data['organization'] + return super(JobTemplateLabelList, self).post(request, *args, **kwargs) + class JobTemplateCallback(GenericAPIView): model = JobTemplate @@ -3815,7 +3827,6 @@ class RoleChildrenList(SubListAPIView): - # Create view functions for all of the class-based views to simplify inclusion # in URL patterns and reverse URL lookups, converting CamelCase names to # lowercase_with_underscore (e.g. MyView.as_view() becomes my_view).