def create(self, request): # TODO: change this to get_serializer serializer = ProjectSerializer(data=request.data) if serializer.is_valid(): serializer.save(owner=request.user) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def create(self, request, *args, **kwargs): serializer = ProjectSerializer(data=request.data, context={"request": self.request}) serializer.is_valid(raise_exception=True) exp = serializer.save() data = ProjectModelSerializer(exp).data return Response(data, status=status.HTTP_201_CREATED)
def post(self, request): data = request.data serializer = ProjectSerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=400)
def put(self, request, project_id): project = self.get_object(project_id) serializer = ProjectSerializer(project, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def get(self, request): """ get: Project state Retrieve the project state for data manager. """ pk = int_from_request(request.GET, "project", 1) # replace 1 to None, it's for debug only project = get_object_with_check_and_log(request, Project.objects.with_counts(), pk=pk) self.check_object_permissions(request, project) data = ProjectSerializer(project).data data.update({ "can_delete_tasks": True, "can_manage_annotations": True, "can_manage_tasks": True, "source_syncing": False, "target_syncing": False, "task_count": project.tasks.count(), "annotation_count": Annotation.objects.filter(task__project=project).count(), 'config_has_control_tags': len(project.get_control_tags_from_config()) > 0 }) return Response(data)
def put(self, request, id): data = request.data instance = self.get_obj(id) serializer = ProjectSerializer(instance, data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=200) return JsonResponse(serializer.errors, status=400)
def test_put_consistent(self, make_proj): (user1, proj) = make_proj client = APIClient() client.force_authenticate(user=user1) modproj = ProjectSerializer(proj).data del modproj['owner'] response = client.put('/projects/1/', modproj) assert response.data == ProjectSerializer(proj).data
def put(self, request, pk): proj = get_object_or_404(Project, pk=pk) self.check_object_permissions(self.request, proj) serializer = ProjectSerializer(proj, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def post(self, request, format=None): serializer = ProjectSerializer(data=request.DATA) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def put(self, request, pk, format=None): project = self.get_object(pk) serializer = ProjectSerializer(project, data=request.DATA) if serializer.is_valid(): serializer.save() return Response(serializer.data) # why no status else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def put(self, request, pk, format=None): project = self.get_object(pk=pk) serializer = ProjectSerializer(project, data=request.data) if serializer.is_valid() and request.user == project.user: serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def post(self, request, format=None): serializer = ProjectSerializer(data=request.data) if serializer.is_valid(): user = authenticate(username='******', password='******') print(user) serializer.save(owner=user) return Response({"data": serializer.data}, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def project_list(request, format=None): """ List all code snippets, or create a new snippet. """ if request.method == 'GET': snippets = Project.objects.all() serializer = ProjectSerializer(snippets, many=True) return Response(serializer.data) elif request.method == 'POST': serializer = ProjectSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class EnvironmentSerializerFull(serializers.ModelSerializer): feature_states = FeatureStateSerializerFull(many=True) project = ProjectSerializer() class Meta: model = Environment fields = ("id", "name", "feature_states", "project", "api_key")
def project_members(request, project_uuid): project = get_object_or_404(Project, pk=project_uuid) check_if_admin_of_project(request.user.id, project.uuid) data = JSONParser().parse(request) if "user_id" in data: if not ProjectMemberRole.objects.filter( project_id=project_uuid, user_id=data["user_id"] ): user = User.objects.filter(id=data["user_id"]) if not user: return HttpResponse( "No user found with this id", status=status.HTTP_404_NOT_FOUND ) project = Project.objects.filter(uuid=project_uuid).first() project.members.add(user.first(), through_defaults={"is_admin": False}) serializer = ProjectSerializer(project) return JsonResponse(serializer.data) return HttpResponse( "The user is already a member of the project", status=status.HTTP_400_BAD_REQUEST, ) return HttpResponse( "You must provide a user_id", status=status.HTTP_400_BAD_REQUEST )
class DocumentDetailSerializer(DocumentSerializer): from clients.serializers import ClientSerializer from projects.serializers import ProjectSerializer author = CRMUserTinySerializer(read_only=True) client = ClientSerializer() project = ProjectSerializer() task = ProjectTaskSerializer()
class ProjectsDataSerializer(serializers.Serializer): projects_count = serializers.SerializerMethodField() active_issues = serializers.SerializerMethodField() asigned_issues = ActivitySerializer(source="get_asigned_issues_chart", many=True) reported_issues = ActivitySerializer(source="get_reported_issues_chart", many=True) part_projects = ProjectSerializer(many=True, read_only=True) last_issues = IssueMinSerializer(source="get_last_issues", many=True, read_only=True) class Meta: fields = [ "projects_count", "asigned_issues", "activity", "reported_issues", "part_projects", "last_issues", ] ref_name = "User Data" def get_projects_count(self, obj): user = self.context["request"].user return Project.objects.filter(members=user).count() def get_active_issues(self, obj): user = self.context["request"].user return Issue.objects.filter(Q(reporter=user, asignee=user)).count()
def test_get_valid_single_project(self): response = client.get( reverse('projects-detail', kwargs={'pk': self.test.pk})) project = Project.objects.get(pk=self.test.pk) serializer = ProjectSerializer(project) self.assertEqual(response.data, serializer.data) self.assertEqual(response.status_code, status.HTTP_200_OK)
class CustomUserSerializer(serializers.Serializer): id = serializers.ReadOnlyField() username = serializers.CharField(max_length=200) email = serializers.CharField(max_length=200) password = serializers.CharField(write_only=True) image = serializers.URLField(source='profile.image', required=False) is_superuser = serializers.BooleanField(default=0) is_staff = serializers.BooleanField(default=0) owner_projects = ProjectSerializer(many=True, read_only=True) pledges = PledgeSerializer(many=True, read_only=True) def create(self, validated_data): user = CustomUser.objects.create(username=validated_data['username'], email=validated_data['email']) user.set_password(validated_data['password']) user.save() return user def update(self, instance, validated_data): instance.username = validated_data.get('username', instance.username) instance.email = validated_data.get('email', instance.email) # instance.set_password(validated_data['password']) profile_data = validated_data.pop('profile', {}) for (key, value) in validated_data.items(): setattr(instance, key, value) instance.save() for (key, value) in profile_data.items(): setattr(instance.profile, key, value) instance.profile.save() return instance
def get(self, request): user = self.get_object() # if you don't call check_object_permissions here, the view won't check if the user has the right permissions! self.check_object_permissions(request, user) # user_serializer = CustomUserSerializer(user) user_serializer = UserSerializerForProfileUpdates(user) pledges = Pledge.objects.filter(user_id=user.id).order_by('-date') pledge_serializer = ExtendedPledgeSerializer(pledges, many=True) projects = Project.objects.filter( user_id=user.id).order_by('-date_created') project_serializer = ProjectSerializer(projects, many=True) location = user.location location_serializer = LocationSerializer(location) response_data = { "user": user_serializer.data, "location": location_serializer.data, "projects": project_serializer.data, "pledges": pledge_serializer.data } return Response(response_data)
def post(self, request): # print(request.data) user_id = request.GET.get('user_id', '') user = User.objects.get(id=user_id) timestamp = datetime.datetime.now().strftime("%Y-%m-%d-%H:%M:%S") project_title = request.data['title'] project_description = request.data['description'] project_type = request.data['type'] project = Project(title=project_title, location="not yet decided", description=project_description, type=project_type, create_time=datetime.datetime.now(), user=user) project.save() project_path = settings.MEDIA_ROOT + str(user_id) + "/" + str( project.id) + "/" print(project_path) if not os.path.exists(project_path): os.makedirs(project_path) video_path = project_path + "videos/" os.makedirs(video_path) image_path = project_path + "images/" os.makedirs(image_path) image_default_path = project_path + "images/unknown/" os.makedirs(image_default_path) model_path = project_path + "models/" os.makedirs(model_path) print(str(user_id) + "/" + str(project.id) + "/") project.location = str(user_id) + "/" + str(project.id) + "/" project.save() print(project.location) serializer = ProjectSerializer(project, many=False) return JsonResponse(serializer.data, safe=False)
def put(self, request): user = self.get_object() # if you don't call check_object_permissions here, the view won't check if the user has the right permissions! self.check_object_permissions(request, user) user_serializer = UserSerializerForProfileUpdates(user, data=request.data, partial=True) if user_serializer.is_valid(): user_serializer.save() location = user.location location_serializer = LocationSerializer(location) pledges = Pledge.objects.filter(user_id=user.id) pledge_serializer = PledgeSerializer(pledges, many=True) projects = Project.objects.filter(user_id=user.id) project_serializer = ProjectSerializer(projects, many=True) response_data = { "user": user_serializer.data, "location": location_serializer.data, "projects": project_serializer.data, "pledges": pledge_serializer.data } return Response(response_data) return Response(user_serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class LabelSerializer(serializers.HyperlinkedModelSerializer): user = UserSerializer() project = ProjectSerializer() class Meta: model = Label fields = ['id', 'name', 'color', 'user', 'project', 'creation_date']
def first_project(request): """Returns the first project of the user. This is used to speed up the loading of the first project page""" projects = get_user_projects(request.user.id) serializer = ProjectSerializer(projects.first(), context={"user_id": request.user.id}) return JsonResponse(serializer.data)
class EnvironmentSerializerFull(serializers.ModelSerializer): feature_states = FeatureStateSerializerFull(many=True) project = ProjectSerializer() class Meta: model = Environment fields = ('id', 'name', 'feature_states', 'project', 'api_key')
def project_detail(request, pk): try: project = Project.objects.get(pk=pk) except Project.DoesNotExist: return HttpResponse(status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': project_serializer = ProjectSerializer(project) return JsonResponse(project_serializer.data) elif request.method == 'PUT': try: project_data = JSONParser().parse(request) name = project_data.get('name', 'updated project name') description = project_data.get('description', 'updated project description') duration = project_data.get('duration', datetime.datetime.now()) if duration == '': duration = datetime.datetime.now() project.name = name project.description = description project.duration = duration project.save() return HttpResponse(status=status.HTTP_201_CREATED) except: return HttpResponse(status=status.HTTP_400_BAD_REQUEST) elif request.method == 'DELETE': project.delete() return HttpResponse(status=status.HTTP_204_NO_CONTENT)
def post(self, request): serializer = ProjectSerializer(data=request.data) if serializer.is_valid(): data = serializer.validated_data try: user = User.objects.get(username=data['username']) except User.DoesNotExist: return Response({'errors': ["invalid user."]}, status=400) project = Project.objects.create(name=data['name'], description=data['description']) project.owners.add(user) return Response({'notes': ['project created']}, status=200) else: return Response({'errors': serializer.errors}, status=400)
def project_list(request): if request.method == 'GET': projects = Project.objects.all() projects_serializer = ProjectSerializer(projects, many=True) return JsonResponse(projects_serializer.data, safe=False) elif request.method == 'POST': try: project_data = JSONParser().parse(request) name = project_data.get('name', 'default project name') description = project_data.get('description', 'default project description') duration = project_data.get('duration', datetime.datetime.now()) if duration == '': duration = datetime.datetime.now() project = Project(name=name, description=description, duration=duration) project.save() return HttpResponse(status=status.HTTP_201_CREATED) except: return HttpResponse(status=status.HTTP_400_BAD_REQUEST) elif request.method == 'DELETE': Project.objects.all().delete() return HttpResponse(status=status.HTTP_204_NO_CONTENT)
def get(self, request): user_id = request.GET.get('user_id', '') print(user_id) user = User.objects.get(id=user_id) projects = Project.objects.filter(user=user) print(projects) serializer = ProjectSerializer(projects, many=True) return JsonResponse(serializer.data, safe=False)
def post(self, request, project_pk, format=None): project_obj = Project.objects.filter(id=int(project_pk)).first() if project_obj: project_obj.users.add(request.user.id) project_obj.save() serializer = ProjectSerializer(project_obj) return Response(serializer.data)
class SubmitSerializer(serializers.ModelSerializer): scanTask = ScanSerializer(read_only=True, many=False) fileSubmitted = serializers.FileField(max_length=None, use_url=True) project = ProjectSerializer(read_only=True, many=False) class Meta: model = SubmitModel exclude = ('submitter',)
def test_put_inconsistent(self, make_proj): (user1, proj) = make_proj client = APIClient() client.force_authenticate(user=user1) req = ProjectSerializer(proj).data req['owner'] = 3 response = client.put('/projects/1/', req) assert response.status_code == 400
def post(self, request, format=None): serializer = ProjectSerializer(data=request.data) if serializer.is_valid(): project = serializer.save() self.mongo_db.create_collection('collection_' + str(project.id)) db_id = utils.get_database_id('mongo') if (utils.sync_schema(db_id)): table_id = utils.get_table_id(db_id, 'collection_' + str(project.id)) project.table_id = table_id project.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_503_SERVICE_UNAVAILABLE) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def get(self, request, format=None): tag_name = self.request.query_params.get('tag_name', None) if tag_name is None: projects = Project.objects.all() else: projects = Project.objects.filter(tags__name=tag_name) serializer = ProjectSerializer(projects, many=True) return Response(serializer.data)
def project_detail(request, pk, format=None): """ Retrieve, update or delete a code snippet. """ try: snippet = Project.objects.get(pk=pk) except Project.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': serializer = ProjectSerializer(snippet) return Response(serializer.data) elif request.method == 'PUT': serializer = ProjectSerializer(snippet, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) elif request.method == 'DELETE': snippet.delete() return Response(status=status.HTTP_204_NO_CONTENT)