Beispiel #1
0
 def post(self, request):
     serializer = UserSerializer(data=request.data)
     if serializer.is_valid():
         serializer.save()
         return Response(serializer.data, status=status.HTTP_201_CREATED)
     else:
         raise ValidationError(serializer.errors)
Beispiel #2
0
 def test_update_user(self):
     data = UserSerializer(self.user).data
     data.update({
         "username": "******",
     })
     response = self.client.put(reverse('DetailUser', args=[self.user.id]), data)
     self.assertEqual(response.status_code, status.HTTP_200_OK)
Beispiel #3
0
 def post(self, request):
     serializer = UserSerializer(data=request.data)
     if serializer.is_valid():
         new_user = serializer.save()
         return Response(serializer.date, status=status.HTTP_201_CREATED)
     else:
         return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Beispiel #4
0
 def put(self, request, pk):
     user = get_object_or_404(User, pk = pk)
     serializer = UserSerializer(instance=user, data=request.date)
     if serializer.is_valid():
         serializer.save()
         return Response(serializer.data, status=status.HTTP_200_OK)
     else :
         return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Beispiel #5
0
 def post(self, request, format='json'):
     #serialize the data sent from the front end
     serializer = UserSerializer(data=request.data)
     if serializer.is_valid():
         user = serializer.save()
         #after the user is saved, create a token for the user
         if user:
             token = Token.objects.create(user=user)
             json = serializer.data
             json['token'] = token.key
             return Response(json, status=status.HTTP_201_CREATED)
     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Beispiel #6
0
class ConsumerTimeSlotMappingRelationSerializer(serializers.ModelSerializer):
    consumer = UserSerializer()
    time_slot = ProvidersTimeSlotSerializer()

    class Meta:
        model = ConsumerTimeSlotMapping
        fields = "__all__"
Beispiel #7
0
 def post(self, request):
     user = User.objects.create_user(email=request.data['email'],
                                     password=request.data['password'])
     #user.set_password(request.data['password'])
     #user.save()
     serializer = UserSerializer(user)
     return Response(serializer.data)
Beispiel #8
0
class PostSerializer(HyperlinkedModelSerializer):
    author = UserSerializer()

    class Meta:
        model = Post
        fields = ('id', 'front_image_url', 'title', 'text', 'author',
                  'created_at', 'updated_at')
class NotesSerializer(serializers.ModelSerializer):
    user = UserSerializer(read_only=True)
    user_id = serializers.IntegerField(write_only=True)

    class Meta:
        model = Notes
        fields = '__all__'
Beispiel #10
0
class LocationConnectionsSerializer(serializers.ModelSerializer):

    connections = ConnectionListSerializer(many=True, read_only=True)
    users = UserSerializer(many=True, read_only=True)

    class Meta:
        model = Locations
        fields = ['id', 'location_name', 'connections', 'users']
Beispiel #11
0
class JmxListSerializer(serializers.ModelSerializer):
    """
    jmx列表查询
    """
    add_user = UserSerializer()
    class Meta:
        model = Jmxs
        exclude = ['jmx']
Beispiel #12
0
class TasksListSerializer(serializers.ModelSerializer):

    # add_user是Tasks模型中的字段
    add_user = UserSerializer()

    class Meta:
        model = Tasks
        fields = "__all__"
Beispiel #13
0
def jwt_response_payload_handler(token, user=None, request=None):
    return {
        'code': 200,
        'msg': 'ok',
        'data': {
            'token': f"{settings.JWT_AUTH['JWT_AUTH_HEADER_PREFIX']} {token}",
            'user': UserSerializer(user).data['id']
        }
    }
Beispiel #14
0
def get_user(request):
    query = request.query_params
    if len(query) == 0:
        user = Users.objects.all()
        return Response(UserSerializer(instance=user, many=True).data,
                        status=200)
    elif 'user_id' in query.keys() and len(query['user_id']) == 0:
        return Response({"error_message": "User ID not found!"}, status=400)
    elif 'user_id' in query.keys() and not query['user_id'][0].isdigit():
        return Response({"error_message": "User ID should be an Integer!"},
                        status=400)
    elif 'user_id' in query.keys():
        id = int(query['user_id'])
        user = Users.objects.filter(id=id).first()
        if user is None:
            return Response({"error_message": "User not found!"})
        return Response(UserSerializer(instance=user).data, status=200)
    else:
        return Response({"error_message": "User Id not found!"}, status=400)
Beispiel #15
0
class RegistrationSerializerByCourse(serializers.ModelSerializer):
    user = UserSerializer()

    # course = CourseSerializer()
    class Meta:
        model = Registration
        fields = (
            'user',
            # 'course',
            'cnt_abcense',
        )
Beispiel #16
0
class LocationSerializer(serializers.ModelSerializer):
    #is_fav = serializers.SerializerMethodField('getFav')

    users = UserSerializer(many=True, read_only=True)

    class Meta:
        model = Locations
        fields = [
            'id',
            'location_name',
            'users',
        ]
Beispiel #17
0
def login(request: Request) -> Response:
    err_response = Response(status=status.HTTP_401_UNAUTHORIZED)
    if 'username' not in request.data or 'password' not in request.data:
        return err_response
    username = request.data['username']
    password = request.data['password']
    user = authenticate(request, username=username, password=password)
    if user is None:
        return err_response
    django_login(request, user)
    serializer_data = UserSerializer(user).data
    serializer_data['csrftoken'] = csrf.get_token(request)
    return Response(serializer_data, status=status.HTTP_200_OK)
Beispiel #18
0
class ContentsSerializer(serializers.ModelSerializer):
    user = UserSerializer(read_only=True)

    class Meta:
        model = Contents
        fields = ('id', "user", 'comment', "rating", 'created_at')

    def create(self, validated_data):
        contents = super(ContentsSerializer, self).create(validated_data)
        user = self.context['request'].user
        if not user.is_anonymous:
            contents.user = user
        contents.save()
        return contents
Beispiel #19
0
    def post(self, request):

        email = request.data['email']
        password = request.data['password']

        try:
            user = User.objects.get(email=email)
            user = authenticate(request, email=email, password=password)
            login(request, user)

        except Exception as e:
            raise e

        return Response(UserSerializer(user).data)
Beispiel #20
0
 def assertUserDetailEqual(self, content: str, user: User):
     # 时间正确性不能通过字符串比较
     compare_fields = set(UserSerializer.Meta.fields) - {'last_login', 'date_joined', 'username', 'student_id'}
     json1 = json.loads(content)
     json2 = UserSerializer(user).data
     for field in compare_fields:
         self.assertEqual(json1[field], json2[field])  # 获取的数据和数据库中的数据在 json 意义上等价
     self.assertDatetimeEqual(json1['date_joined'], user.date_joined)
     self.assertDatetimeEqual(json1['last_login'], user.last_login)
     if not (user.is_staff or user.is_superuser or int(user.id) == int(json1['id'])):
         self.assertEqual(json1['username'], '***')
         self.assertEqual(self, json1['student_id'], user.userprofile.student_id[0:4])
     else:
         self.assertEqual(json1['username'], user.username)
         self.assertEqual(json1['student_id'], user.userprofile.student_id)
Beispiel #21
0
class TweetsSerializer(serializers.ModelSerializer):
    user = UserSerializer(read_only=True)

    class Meta:
        model = Tweet
        fields = "__all__"

    def create(self, validated_data):
        user = self.context["request"].user
        return Tweet.objects.create(user=user, **validated_data)

    def update(self, instance, validated_data):
        if instance.user == self.context["request"].user:
            return super().update(instance, validated_data)
        else:
            error = {"message": "You can not edit another user's post"}
            raise serializers.ValidationError(error)
Beispiel #22
0
class RegistrationSerializer1(serializers.ModelSerializer):
    c_teacher = UserSerializer()
    student = serializers.SerializerMethodField()

    def get_student(self, obj):
        result_set = Registration.objects.filter(course=obj)
        return RegistrationSerializer(result_set, many=True).data

    class Meta:
        model = Course
        fields = (
            'c_id',
            'c_name',
            'c_code',
            'c_teacher',
            'cnt_sign',
            'student',
        )
Beispiel #23
0
def user_create(request):
    try:
        name = request.data["name"]
        password = request.data["password"]
        username = request.data["username"]
        short_bio = request.data["short_bio"]
        email_id = request.data["email_id"]
    except KeyError:
        return Response(
            {
                "error_message":
                "Error! Please make sure all the Fields are provided properly."
            },
            status=400)
    if len(name) == 0 or name is None:
        return Response({"error_message": "Name field cannot be empty"},
                        status=400)
    if len(password) < 6 or password is None:
        return Response(
            {
                "error_message":
                "Password length cannot be less than 6 characters!"
            },
            status=400)
    does_username = Users.objects.filter(username=username).first()
    if does_username is not None:
        return Response(
            {
                "error_message":
                "Please Choose another Username as User with this Username already exists!"
            },
            status=400)
    new_user = Users.objects.create(name=name,
                                    password=make_password(password),
                                    short_bio=short_bio,
                                    username=username,
                                    email_id=email_id)
    new_user.save()
    return Response(UserSerializer(instance=new_user).data, status=200)
Beispiel #24
0
class ThreadSerializer(serializers.ModelSerializer):
    user = UserSerializer(read_only=True)
    thread = ResponseSerializer(many=True, read_only=True)

    class Meta:
        model = Thread
        fields = (
            "id",
            "user",
            "title",
            "created_at",
            "thread",
            "is_active",
            "is_writable",
        )

    def create(self, validated_data):
        thread = super(ThreadSerializer, self).create(validated_data)
        user = self.context['request'].user
        if not user.is_anonymous:
            thread.user = user
        thread.save()
        return thread
Beispiel #25
0
def signup(request: Request) -> Response:
    register_serializer = UserRegisterSerializer(data=request.data)
    if not register_serializer.is_valid():
        return Response(register_serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    if User.objects.filter(userprofile__student_id=register_serializer.validated_data['student_id']):
        # 判断注册的用户是微信小程序用户:姓名和学号与数据库中相同,且数据库中密码为空
        # 如果满足条件,则将找到的用户的信息更新,然后返回 200
        origin_wechat_user = User.objects.filter(
            userprofile__student_id=register_serializer.validated_data['student_id'],
            first_name=register_serializer.validated_data['first_name'],
            password='')
        if origin_wechat_user:
            u = origin_wechat_user[0]
            user_serializer = UserSerializer(u)
            user_serializer.update(u, register_serializer.validated_data)
            return Response(user_serializer.data, status=status.HTTP_200_OK)
        else:
            return Response(data={"student_id": "学号已存在"}, status=status.HTTP_400_BAD_REQUEST)
    u = register_serializer.save()
    user_serializer = UserSerializer(u)
    return Response(user_serializer.data, status=status.HTTP_201_CREATED)
Beispiel #26
0
class ScheduleSerializer(serializers.ModelSerializer):
    class Meta:
        model = Schedule
        fields = '__all__'

    stafalty = UserSerializer()
Beispiel #27
0
from utils.mail import send_reset_password_email
from utils.permissions import login_required
from utils.random import generate_uuid
from utils.swagger import *
from utils.validators import is_valid_password


@swagger_auto_schema(
    method='POST',
    operation_summary='注册新用户',
    operation_description='成功注册新账户:返回 201\n'
                          '成功绑定微信小程序账户:返回200\n'
                          '失败(参数错误或不符合要求):返回 400\n'
                          '注:注册以后不会自动登录',
    request_body=UserRegisterSerializer,
    responses={201: UserSerializer()}
)
@api_view(['POST'])
@csrf_exempt
def signup(request: Request) -> Response:
    register_serializer = UserRegisterSerializer(data=request.data)
    if not register_serializer.is_valid():
        return Response(register_serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    if User.objects.filter(userprofile__student_id=register_serializer.validated_data['student_id']):
        # 判断注册的用户是微信小程序用户:姓名和学号与数据库中相同,且数据库中密码为空
        # 如果满足条件,则将找到的用户的信息更新,然后返回 200
        origin_wechat_user = User.objects.filter(
            userprofile__student_id=register_serializer.validated_data['student_id'],
            first_name=register_serializer.validated_data['first_name'],
            password='')
        if origin_wechat_user:
class ArticleSerializer(serializers.HyperlinkedModelSerializer):
    user = UserSerializer()

    class Meta:
        model = Article
        fields = ('id', 'user', 'title', 'content', 'image')
Beispiel #29
0
class CourseSerializer(serializers.ModelSerializer):
    c_teacher = UserSerializer()

    class Meta:
        model = Course
        fields = ('c_id', 'c_code', 'c_name', 'c_teacher', 'cnt_sign')
Beispiel #30
0
 def test_update_user(self):
     data = UserSerializer(self.user).data
     data.update({"username": "******"})
     response = self.client.put(reverse("DetailUser", args=[self.user.id]), data)
     self.assertEqual(response.status_code, status.HTTP_200_OK)
Beispiel #31
0
 def get(self, request, pk):
     if not self.get_user(pk):
         Response('user Not Found in database',
                  status=status.HTTP_404_NOT_FOUND)
     serializer = UserSerializer(self.get_user(pk))
     return Response(serializer.data)
Beispiel #32
0
    def get(self, request, **kwargs):
        try:
            # fetch provider with categories
            category_id = kwargs['category_id']

            queryset = User.objects.filter(
                providercategorymappings__category__id=category_id)
            print('length1>>>', len(queryset))
            if len(queryset) != 0:
                data_to_send = dict()
                print('length2>>>>', queryset[0])
                _category = queryset[0].providercategorymappings.filter(
                    category_id=category_id)
                print('length3>>>>', len(_category))
                if len(_category) != 0:
                    print('length4>>>>', _category[0])
                    _category_serializer = CategoriesSerializer(
                        _category[0].category)
                    data_to_send.update(
                        {'category': _category_serializer.data})
                    data_to_send['category'].update({
                        'image':
                        base_url + data_to_send['category']['image']
                    })
                    data_to_send.update({'providers': []})

                    for d in queryset:
                        print('location>>>', d.location_set.all()[0])
                        provider_dict = dict()
                        provider_dict.update(UserSerializer(d).data)
                        provider_dict.update({
                            'location':
                            LocationSerializer(d.location_set.all()[0]).data
                        })
                        data_to_send['providers'].append(provider_dict)

                    return Response(data={
                        'msg': "Retrieved data",
                        'success': True,
                        'data': data_to_send
                    },
                                    status=status.HTTP_200_OK)
                else:
                    return Response(data={
                        'msg': "Category not found",
                        'success': False,
                        'data': ''
                    },
                                    status=status.HTTP_404_NOT_FOUND)
            else:
                return Response(data={
                    'msg': "User not found",
                    'success': False,
                    'data': ''
                },
                                status=status.HTTP_404_NOT_FOUND)
        except Exception as e:
            print('error>>>>>>>>>', e.args)
            return Response(data={
                'msg': "Data not found",
                'success': False,
                'data': ''
            },
                            status=status.HTTP_404_NOT_FOUND)
Beispiel #33
0
 def put(self, request, pk):
     user = self.get_user(pk)
     serializer = UserSerializer(user, data=request.data)
     if serializer.is_valid():
         serializer.save()
     return Response(serializer.data)