How to count rows on PostgreSQL database in Django? - django

How to count rows on PostgreSQL database in Django and show using highchart?
Example: I want to show how much record/row from 7.00am to 7.00 am next day.
models:
from django.db import models
from datetime import datetime, date
class hujan(models.Model):
id = models.AutoField(primary_key=True)
tanggal = models.DateTimeField(auto_now_add=True)
dtinms = models.IntegerField()
hujan = models.FloatField()
serializers:
from rest_framework import serializers
from .models import hujan, cahayasuhukelembapan
class hujanSerializer(serializers.ModelSerializer):
class Meta:
model = hujan
fields = ('tanggal','dtinms','hujan')
views:
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, JsonResponse
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.renderers import TemplateHTMLRenderer
from .models import hujan
from .serializers import hujanSerializer
def homePageView(request):
return render(request,'homepage.html')
class hujanlistall(APIView):
def get(self, request):
Hujan = hujan.objects.all()
serializer = hujanSerializer(Hujan, many=True)
return JsonResponse(serializer.data,safe=False)

Modify "views.py" file,
import datetime
class hujanlistall(APIView):
def get(self, request):
Hujan = hujan.objects.filter(tanggal__range = (datetime.datetime.combine(start_date,datetime.time.min),datetime.datetime.combine(end_date, datetime.time.max)))
RowCount = len(Hujan)
serializer = hujanSerializer(Hujan, many=True)
return JsonResponse(serializer.data,safe=False)

Related

How to POST multiple data in DRF and React with Axios

I have 2 models named Recipe and Step..
I have serialized both to make an API for GET request.. I want to know is there a way to create for POST request so that I can send both the data (steps and recipe) in the same request?
models.py:
from django.db import models
class Recipe(models.Model):
title = models.CharField( max_length=50)
uuid = models.CharField( max_length=100)
def __str__(self):
return f'{self.uuid}'
class Step(models.Model):
step = models.CharField(max_length=300)
uuid = models.ForeignKey(Recipe, on_delete=models.CASCADE)
def __str__(self):
return f'{self.step} - {self.uuid}'
serializers.py:
from rest_framework import serializers
from .models import *
class RecipeSerializer(serializers.ModelSerializer):
class Meta:
model = Recipe
fields = ['title', 'uuid']
class StepSerializer(serializers.ModelSerializer):
class Meta:
model = Step
fields = ['step', 'uuid']
views.py:
from django.shortcuts import render
from rest_framework.decorators import api_view
from rest_framework.response import Response
from .serializers import *
from .models import *
#api_view(['GET'])
def apiOverview(request):
api_urls = {
'List':'/recipe-list/',
'Detail View':'/recipe-detail/<str:pk>/',
'Create':'/recipe-create/',
'Update':'/recipe-update/<str:pk>/',
'Delete':'/recipe-delete/<str:pk>/',
'Steps' : '/steps/<str:pk>'
}
return Response(api_urls)
#api_view(['GET'])
def recipeList(request):
recipes = Recipe.objects.all()
serializer = RecipeSerializer(recipes, many=True)
return Response(serializer.data)
#api_view(['GET'])
def recipeDetail(request, pk):
recipe = Recipe.objects.get(uuid=pk)
recipe_serializer = RecipeSerializer(recipe, many=False)
steps = Step.objects.filter(uuid=pk)
steps_serializer = StepSerializer(steps, many=True)
return Response({
'recipe' : recipe_serializer.data,
'steps' : steps_serializer.data
})
How can I create a view for POST and handle both the models?
Try:
from rest_framework import generics
from .models import *
class StepAndRecipe(generics.CreateAPIView):
queryset = Step.objects.all()
queryset = Recipe.objects.all()
serializer_class = StepSerializer
serializer_class = RecipeSerializer
Add in urls.py:
from django.urls import path
from .views import StepAndRecipe
urlpatterns = [
path('steprecipepost', StepAndRecipe.as_view(), name='steps_recipes')
This will only work with POST! And one more thing: take care with the raw data and the HTML form, maybe theses get a little confused since you are using two models in the same view.

How to integrate mixpanel to django backend

I am new with integrating mixpanel to Django backend to track events,As i try to track, it gives me empty brackets anyone with ideas or resources please help me am quite stack
views.py
from django.shortcuts import render
from django.views import View
from rest_framework.generics import ListCreateAPIView
from rest_framework.views import APIView
from rest_framework.response import Response
from .serialize import UserSerializer, TweakSerializer, ChannelSerializer, SubscriberSerializer
from tweaks.models import Tweak
from accounts.models import User
from channels.models import Channel, Subscriber
from mixpanel import Mixpanel
import json
# Create your views here.
mp = Mixpanel('TOKEN')
class userApi(ListCreateAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
def get(self, request):
queryset = self.get_queryset()
serializer = UserSerializer(queryset, many=True)
return Response(serializer.data)
apiuser=userApi()
point = json.dumps(apiuser.__dict__)
mp.track(point, 'users')
serializers.py
from rest_framework import routers, serializers, viewsets
from django.urls import path, include
from accounts.models import User
from tweaks.models import Tweak
from channels.models import Channel, Subscriber
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = 'username', 'email', 'first_name', 'last_name', 'date_joined'

get() takes 1 positional argument but 2 were given :Django Rest

I'm currently making a simple get/post api with django 3. After i run the server and go to the employee/article/ url it return an error
VIEW.PY
from django.shortcuts import get_object_or_404
from django.http import HttpResponse
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from .models import employees
from .serializer import employeeSerializer
class employeeList(APIView):
def get(self):
employess1 = employees.objects.all()
serializer = employeeSerializer(employess1 ,many=True)
return Response(serializer.data)
serializer.py
from rest_framework import serializers
from .models import employees
class employeeSerializer(serializers.ModelSerializer):
class Meta:
model = employees
fields = ['first_name','last_name','salary']
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('employees/',views.employeeList.as_view()),
]
You are missing the request argument in the get method. See the docs here
class employeeList(APIView):
def get(self, request):
employess1 = employees.objects.all()
serializer = employeeSerializer(employess1 ,many=True)
return Response(serializer.data)

How to test DRF serializer when using additional keyword arguments?

I have a simple model and a serializer which uses additional keyword arguments(extra_kwargs) to limit max and min value for a field. I want to write two test cases in my tests.py to both test valid and invalid values for that field (weight). How should I do this?
I am using Python 2.7.
Model
from django.db import models
class Person(models.Model):
name = models.CharField(max_length=100)
weight = models.FloatField()
Serializer
from rest_framework import serializers
from .models import Person
class PersonSerializer(serializers.ModelSerializer):
model = Person
fields = ('name', 'weight')
extra_kwargs = {'weight': {'min_value': 5, 'max_value': 1000}}
tests.py
from django.test import TestCase
from .models import Person
class ModelTestCase(TestCase):
def setUp(self):
self.person = Person(name='Sam', weight=150)
def test_when_weight_isValid(self):
#e.g. when weight = 200
def test_when_weight_notValid(self):
#e.g. when weight = 3
import json
from django.urls import reverse
from django.contrib.auth import authenticate
from rest_framework import status
from rest_framework.test import APITestCase
from .models import *
class UserTests(APITestCase):
def setUp(self):
self.person = Person(name='Sam', weight=150)
def test_when_weight_isvalid(self):
url = reverse('person-detail', kwargs={'pk': self.person.id})
data = {'weight': 200}
response = self.client.patch(url, data, format='json')
self.assertEqual(response.status_code, status.HTTP_200_OK)
print json.dumps(response.data, ensure_ascii=False, indent=2)
Something like this,code is untest.

TypeError this constructor takes no arguments

I seem to be having a TypeError problem on my program using Django.
Views.py
from __future__ import unicode_literals
from django.shortcuts import render
from .models import Anteproyecto
from .forms import formulario_anteproyecto
from django.views.generic import CreateView
from django.core.urlresolvers import reverse, reverse_lazy
from django.contrib.messages.views import SuccessMessageMixin
class CrearAnteproyecto(SuccessMessageMixin, CreateView):
model = Anteproyecto
form_class = formulario_anteproyecto
template_name = "crear_anteproyectos.html"
success_url = reverse_lazy('crear_anteproyecto')
success_message = "El anteproyecto ha sido creado"
def form_valid(self, form):
self.object = form.save()
Forms. py
from django import forms
from .models import Anteproyecto
class formulario_anteproyecto:
class Meta:
model = Anteproyecto
fields = ['titulo', 'resumen','estado','palabras_claves']
Models.py
from __future__ import unicode_literals
from django.db import models
from taggit.managers import TaggableManager
from Actividades.models import Actividades
ESTADOS = (('Activo', 'Activo'), ('Inactivo', 'Inactivo'))
class Anteproyecto(models.Model):
titulo = models.CharField(max_length=100, verbose_name='Título')
estado = models.CharField(max_length=8, verbose_name="Estado", choices=ESTADOS, default='Activo')
resumen = models.CharField(max_length=500, verbose_name="Resumen")
claves = TaggableManager(verbose_name = "Palabras claves")
actividad = models.ForeignKey(Actividades, on_delete=models.CASCADE)
class Meta :
verbose_name = 'Anteproyecto'
verbose_name_plural = 'Anteproyectos'
def __str__(self):
return self.titulo
Importing the app "Actividades" to be used as a reference in models. Using as well Django-taggit to use a field that can work as tags, still not implemented due to TypeError. Html is a bootstrap template which prints the form as a paragraph. There are other creates in different views that use the same coding as this however this one is giving me the error.
Your formulario_anteproyecto does not inherit from anything. It needs to inherit from forms.ModelForm.