Ejemplo n.º 1
0
	def create(self,request):
		user = request.user
		serializer = ArticleSerializer(data=request.DATA,context={'request':request})
		if serializer.is_valid():
			serializer.save(user=user)
			return Response(serializer.data, status=status.HTTP_201_CREATED)
		return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Ejemplo n.º 2
0
 def put(self, request, pk, format=None):
     article = self.get_object(pk)
     serializer = ArticleSerializer(article, data=request.data)
     if serializer.is_valid():
         serializer.save()
         return Response(serializer.data)
     return Response(serializer.errors, status=400)
Ejemplo n.º 3
0
 def post(self, request):
     article = ArticleSerializer(data=request.data)
     if article.is_valid():
         article.save()
         return Response(data=article.data, status=status.HTTP_200_OK)
     else:
         return Response(data=article.errors,
                         status=status.HTTP_400_BAD_REQUEST)
Ejemplo n.º 4
0
 def post(self, request):
     request.data.update({'requester': request.user.profile.id})
     serializer = ArticleSerializer(data=request.data)
     if serializer.is_valid(raise_exception=ValueError):
         serializer.save()
         return Response(serializer.data, status=status.HTTP_201_CREATED)
     return Response(serializer.error_messages,
                     status=status.HTTP_404_BAD_REQUEST)
Ejemplo n.º 5
0
    def post(self, request: HttpRequest, board_id: int):
        data = JSONParser().parse(request)
        data[self.lookup_board_kwarg] = board_id

        serializer = ArticleSerializer(data=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)
Ejemplo n.º 6
0
 def get(self, request, *args, **kwargs):
     article = Article.objects.filter(id=kwargs['pk'])
     if not len(article):
         raise exceptions.ValidationError(
             'Request with this id didnt found')
     serializer = ArticleSerializer(article[0], many=False)
     return Response(serializer.data)
Ejemplo n.º 7
0
 def get(self, request: HttpRequest, board_id: int, article_id: int):
     article = Article.objects.get(id=article_id)
     serializer = ArticleSerializer(article)
     output = dict()
     output['data'] = serializer.data
     output['msg'] = 'SUCCESS'
     return Response(output, status=status.HTTP_200_OK)
Ejemplo n.º 8
0
def article_list(request):
    if request.method == 'GET':
        txt = request.GET.get('article_txt', '')
        writer = request.GET.get('article_writer', '')
        return_list = request.GET.get('return', '')
        articles = Article.objects.all()
        if txt:
            articles = articles.filter(Q(article_txt__icontains=txt))
        if writer:
            articles = articles.filter(Q(article_writer__icontains=writer))

        articles_serializer = ArticleSerializer(articles, many=True)
        if return_list:
            return_list = list(return_list.split(","))
            try:
                data = articles_serializer.data
                subset = lambda d, keys: dict([(key, d[key]) for key in keys])
                data = [subset(article, return_list) for article in data]
                return JsonResponse(data, safe=False)
            except:
                return HttpResponseServerError(
                    str("does not exist " +
                        ' , '.join(check_return_list(return_list))))
        else:
            return JsonResponse(articles_serializer.data, safe=False)
Ejemplo n.º 9
0
def search_articles(request):
    """
    Function to return title and snippet search results of a given request

    Args:
        request: as the frontend request

    Returns:
        JsonResponse: The matched articles
    """

    if request.method == 'GET':

        articles = Article.objects.all()
        search_string = request.GET.get('search')

        if search_string != '':

            articles = articles.filter(
                title__icontains=search_string) | articles.filter(
                    text_snippet__icontains=search_string) | articles.filter(
                        publisher__name__icontains=search_string
                    ) | articles.filter(
                        categories__name__icontains=search_string)

        serializer = ArticleSerializer(articles.distinct(), many=True)

        if not articles:
            return HttpResponse(status=200)
        else:
            return JsonResponse(serializer.data, safe=False)

    else:
        return JsonResponse({"msg": "Only GET requests allowed."}, status=404)
Ejemplo n.º 10
0
 def get(self, request, *args, **kwargs):
     profile = UserProfile.objects.filter(id=kwargs['pk'])
     if not len(profile):
         raise exceptions.ValidationError('No user with this id')
     serializer = ArticleSerializer(
         profile[0].my_articles.all().order_by('-reg_date'), many=True)
     return Response(serializer.data)
Ejemplo n.º 11
0
def article_list_by_user(request, pk):
    try:
        user = User.objects.get(pk=pk)
    except User.DoesNotExist:
        return Response(status=404)

    serializer = ArticleSerializer(Article.objects.filter(owner=pk), many=True)
    return Response(serializer.data)
Ejemplo n.º 12
0
def article_author(request, query, format=None):
	"""
	Retrieve articles by author string
	"""
	if request.method == 'GET':
		articles = Article.objects.filter(author__icontains=query)
		serializer = ArticleSerializer(articles, many=True)
		return Response(serializer.data)
Ejemplo n.º 13
0
def article_day(request, y, m, d, format=None):
	"""
	Retrieve articles by year
	"""
	if request.method == 'GET':
		articles = Article.objects.filter(date__day=d)
		serializer = ArticleSerializer(articles, many=True)
		return Response(serializer.data)
Ejemplo n.º 14
0
def article_publication(request, publication_pk, format=None):
    """
    Get articles from the publication given
    """
    if request.method == 'GET':
        articles = Article.objects.filter(publication=publication_pk)
        serializer = ArticleSerializer(articles, many=True)
        return Response(serializer.data)
Ejemplo n.º 15
0
class ImageSerializer(serializers.ModelSerializer):
    image = serializers.ImageField(max_length=None, use_url=True)
    gallery = serializers.SlugRelatedField(slug_field='slug', queryset=Gallery.objects.all())
    article = ArticleSerializer(many=False, read_only=True)

    class Meta:
        model = Image
        fields = '__all__'
Ejemplo n.º 16
0
def article_topic(request, topic_pk, format=None):
    """
    Get articles with the topic given
    """
    if request.method == 'GET':
        articles = Article.objects.filter(topic=topic_pk)
        serializer = ArticleSerializer(articles, many=True)
        return Response(serializer.data)
Ejemplo n.º 17
0
def article_detail(request, pk):
    """
    Retrieve, update or delete an article.
    """
    try:
        article = Article.objects.get(pk=pk)
    except Article.DoesNotExist:
        return HttpResponse(status=404)

    if request.method == 'GET':
        serializer = ArticleSerializer(article)
        return JsonResponse(serializer.data)

    elif request.method == 'PUT':
        data = JSONParser().parse(request)
        serializer = ArticleSerializer(article, data=data)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse(serializer.data)

        return JsonResponse(serializer.errors, status=400)

    elif request.method == 'DELETE':
        article.delete()
        return HttpResponse(status=204)
Ejemplo n.º 18
0
 def get(self, request, id, format=None):
     articles = Article.objects.all()
     for article in articles:
         if id == article.id:
             articlesserializer = ArticleSerializer(article)
             return Response(data=articlesserializer.data,
                             status=status.HTTP_200_OK)
         else:
             return Response(data='文章不存在,请重新确认', status=status.HTTP_200_OK)
Ejemplo n.º 19
0
 def get(self, request, *args, **kwargs):
     article = self.get_object()
     # ajout des vues sur l'article
     article = has_viewed_article(request, article.pk)
     serializer = ArticleSerializer(article)
     has_voted = has_voted_article(request, article.pk)
     return Response(
         OrderedDict([
             ('article', serializer.data),
             ('has_voted', has_voted)
         ]))
Ejemplo n.º 20
0
def article_id(request, pk, format=None):
    """
    Retrieve an article instance.
    """
    try:
        article = Article.objects.get(pk=pk)
    except Article.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        serializer = ArticleSerializer(article)
        return Response(serializer.data)
Ejemplo n.º 21
0
 def get(self, request, tag_id):
     try:
         tag = Tag.objects.get(pk=tag_id)
     except Tag.DoesNotExist:
         return Response("No Tag with this id",
                         status=status.HTTP_404_NOT_FOUND)
     # retrieve all children tags
     articles = tag.article_set.all()
     for tag in Tag.objects.filter(parent=tag):
         articles.append(tag.article_set.all())
     serializer = ArticleSerializer(articles, many=True)
     return Response(serializer.data, status=status.HTTP_200_OK)
Ejemplo n.º 22
0
 def post(self, request):  # 에러 테스트 필요함
     if request.user.is_authenticated:  # 사용자가 인증 되었을경우
         serializer = ArticleSerializer(data=request.data)
         try:
             profile = Profile.objects.get(user=request.user)
         except:
             Profile.objects.create(user=request.user)
             profile = Profile.objects.get(user=request.user)
         for temp in json.loads(
                 request.data.get('images_id')):  # 이미지의 id값들이 유효한지 체크
             if not self._is_image_available(temp):  # 잘못된 id값을 받았을 경우
                 return Response(status=status.HTTP_406_NOT_ACCEPTABLE)
         if serializer.is_valid():
             import pdb
             pdb.set_trace()
             serializer.save(writer=request.user,
                             group=profile.group)  # 작성자 요청자로 설정
             return JsonResponse(
                 serializer.data, status=status.HTTP_201_CREATED)
         return Response(
             serializer.errors,
             status=status.HTTP_400_BAD_REQUEST)  # 폼에 오류가 있을 경우
     return Response(status=status.HTTP_401_UNAUTHORIZED)  # 인증되지 않았을 경우
Ejemplo n.º 23
0
def profile(request, username):
    user = get_object_or_404(User, username=username)
    movies = Movie.objects.filter(like_users=user.id)
    movie_serializer = MovieSerializer(movies, many=True)
    ranks = Rank.objects.filter(user=user.id)
    rank_serializer = RankSerializer(ranks, many=True)
    articles = Article.objects.filter(user=user.id)
    article_serializer = ArticleSerializer(articles, many=True)
    comments = Comment.objects.filter(user=user.id)
    comment_serializer = CommentSerializer(comments, many=True)
    return Response({
        'movies': movie_serializer.data,
        'ranks': rank_serializer.data,
        'articles': article_serializer.data,
        'comments': comment_serializer.data
    })
Ejemplo n.º 24
0
 def next_article(self):
     logging.info("\t{} getting article".format(self.user))
     self.user.player.ready = False
     self.user.player.save()
     room = self.user.player.room
     # room.players_waiting = 1
     room.save()
     deck = self.user.player.room.deck
     list_articles = deck.articles.values_list(flat=True)
     article_counter = room.article_counter
     # game end
     logging.info("{} is seeing {} vs fixed {}".format(
         self.user, article_counter, len(deck.articles.all())))
     if article_counter == len(deck.articles.all()):
         if hasattr(self, "hosted_room"):
             if self.hosted_room.pk == room.pk:
                 logging.info("GAME ENDED")
                 room.article_counter = 0
                 room.save()
                 list_of_scores = self.get_list_of_scores("id")
                 self.send_everyone({
                     "action": "game end result",
                     "message": {
                         "score": list_of_scores,
                     }
                 })
                 signals.game_ended.send_robust(
                     sender=self.__class__,
                     room=room,
                     deck=deck,
                     player_scores=self.get_list_of_scores("pk"))
                 async_to_sync(self.channel_layer.group_send)(
                     self.room_group_name, {
                         "type": "receive_json",
                         "message": {
                             "action": "admin",
                             "schema": "close",
                         }
                     })
     else:
         curr_article = Article.objects.get(
             pk=list_articles[article_counter])
         serializer = ArticleSerializer(curr_article)
         serialized_data = serializer.data
         serialized_data["action"] = "card"
         # logging.info(serialized_data)
         self.send_json(serialized_data)
Ejemplo n.º 25
0
    def test_create(self):
        factory = APIRequestFactory()
        request = factory.post('/articles/add/', {'title': self.title, 'text': self.text})

        view = ArticleAddView.as_view()
        response = view(request)

        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        self.assertEqual(ArticleModel.objects.count(), 1)

        article = ArticleModel.objects.filter(title=self.title).first()
        self.assertIsInstance(article, ArticleModel)
        serializer = ArticleSerializer(article)
        self.assertEqual(response.data, serializer.data)
        self.assertEqual(len(response.data['revision']), 1)
        self.assertEqual(response.data['title'], self.title)
        self.assertEqual(response.data['revision'][0]['text'], self.text)
Ejemplo n.º 26
0
def article_list(request):
    """
    List all articles, or create a new article.
    """

    if request.method == 'GET':
        articles = Article.objects.all()
        serializer = ArticleSerializer(articles, many=True)
        return Response(serializer.data)

    elif request.method == 'POST':
        serializer = ArticleSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=201)
        return Response(serializer.errors, status=400)
Ejemplo n.º 27
0
class InvoiceSerializer(serializers.ModelSerializer):
    author = SmallUserSerializer(required=False, read_only=True)
    articles = ArticleSerializer(required=False, read_only=True, many=True)
    number_of_articles = serializers.SerializerMethodField()
    total_amount = serializers.SerializerMethodField('get_total_amount')

    def get_number_of_articles(self, obj):
        return obj.articles.all().count()

    def get_total_amount(self, obj):

        total_amount = 0
        for article in obj.articles.all():
            total_amount += article.price * article.quantity
        return total_amount

    class Meta:
        model = Invoice
        fields = ['id', 'created', 'updated', 'date', 'shop', 'restaurant', 'author', 'articles', 'number_of_articles', 'total_amount']
        read_only_fields = ['author']
Ejemplo n.º 28
0
def article_detail(request, pk):
    try:
        article = Article.objects.get(pk=pk)
    except Article.DoesNotExist:
        return Response(status=404)

    if request.method == 'GET':
        serializer = ArticleSerializer(article)
        return Response(serializer.data)

    if request.method == 'PUT':
        serializer = ArticleSerializer(article, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=400)

    elif request.method == 'DELETE':
        article.delete()
        return Response(status=204)
Ejemplo n.º 29
0
class RestaurantDetailsSerializer(serializers.HyperlinkedModelSerializer):
    articles = ArticleSerializer(many=True, read_only=True)

    class Meta:
        model = Restauraunt
        fields = ['pk', 'name', 'logo', 'articles']
Ejemplo n.º 30
0
def article_list_json_3(request):
    article = Article.objects.get(pk=1)
    serializer = ArticleSerializer(article)
    return Response(serializer.data)