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'
Related
I was just getting started on using Django's rest framework. The problem I faced is that Rest Framework didn't fetch from the right URL: I want it to get the list of Todos but it returned the URL where the API was located.
(Might be easy for many of you, but I am completely fresh to drf)
serializers
from .models import Todo
from rest_framework import serializers
class TodoSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Todo
fields = ['title', 'desc', 'level', 'created']
urls
from django.urls import path, include
from rest_framework import routers
from . import views
router = routers.DefaultRouter()
router.register(r'todos', views.TodoViewSet)
urlpatterns = [
path('', views.IndexView.as_view(), name='todo_all'),
path('api/', include(router.urls)),
]
views
from django.views.generic.base import TemplateView
from rest_framework import viewsets
from .models import Todo
from .serializers import TodoSerializer
class IndexView(TemplateView):
template_name = "todo/index.html"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['todos'] = Todo.objects.all()
return context
class TodoViewSet(viewsets.ModelViewSet):
queryset = Todo.objects.all()
serializer_class = TodoSerializer
What I want Rest to get:
What Rest actually displayed:
Like, I want the data of the todos, not the URL. Thanks in advance.
You have used HyperlinkedModelSerializer. Try to use ModelSerializer instead.
from .models import Todo
from rest_framework import serializers
class TodoSerializer(serializers.ModelSerializer):
class Meta:
model = Todo
fields = ['title', 'desc', 'level', 'created']
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 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)
I am new to Django and React. I am taking over a Django / React project and have an issue where an api url is called:
GET /api/admin/parents/
but the underlying sql statement:
from django.http import HttpResponseRedirect
from django.db.models import Q
from .models import *
from rest_framework import permissions, status
from rest_framework.decorators import api_view, permission_classes
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.generics import ListAPIView, ListCreateAPIView, CreateAPIView, RetrieveUpdateAPIView, DestroyAPIView
from .serializers import *
from twilio.rest import Client
class AdminAllParentsView(ListAPIView):
serializer_class = UserSerializer
queryset = User.objects.filter(is_staff=False, is_parent=True, is_active=True)
does not get re-executed each time the GET /api/admin/parents/ call is performed.
Say for instance.. a sql record is changed so that there are fewer records matching the is_parent=True part of the api call / query... the results returned by the api call don't reflect the real / current status of the query. The GET /api/admin/parents/ still returns the data from a previous, sql query ( a cached version I assume ) and does not re-execute the query.
The urls.py part of this is:
from django.urls import path
from rest_framework_jwt.views import obtain_jwt_token
from .views import *
urlpatterns = [
path('admin/parents/', AdminAllParentsView.as_view())
So how to I get current sql data from this each time I do a api call?
jack
... I see in the browser that the /api/admin/parents/ request goes out and returns the old data via json data. It's not a cached browser html thing.
and
... here is the user serializer code... someone said that this might be important too.
from rest_framework import serializers
from rest_framework_jwt.settings import api_settings
from .models import *
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = (
'id',
'email',
'first_name',
'last_name',
'is_parent',
'phone',
'mobile_phone',
'address',
'city',
'zip',
'county',
'agency_name',
'caseworker_name',
'caseworker_email',
'caseworker_phone',
'caseworker_ext',
'is_active',
'agency_approved',
)
class UserSerializerWithToken(serializers.ModelSerializer):
token = serializers.SerializerMethodField()
password = serializers.CharField(write_only=True)
def get_token(self, obj):
jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
payload = jwt_payload_handler(obj)
token = jwt_encode_handler(payload)
return token
def create(self, validated_data):
password = validated_data.pop('password', None)
instance = self.Meta.model(**validated_data)
if password is not None:
instance.set_password(password)
instance.save()
return instance
class Meta:
model = User
fields = '__all__'
I have a users app in a Django project (version 2.1 and python 3.6). After an user signup (both front end and when added in the admin dashboard ideally), I'd like to insert data in one other table. I know how to insert data, but I didn't find out how to do it right after a successfull signup.
Ideal answer would just show me how to do something like print('hello') right after an user created his account.
# users/admin.py
from django.contrib import admin
from django.contrib.auth import get_user_model
from django.contrib.auth.admin import UserAdmin
from .forms import CustomUserCreationForm, CustomUserChangeForm
from .models import CustomUser
class CustomUserAdmin(UserAdmin):
add_form = CustomUserCreationForm
form = CustomUserChangeForm
model = CustomUser
list_display = ['email', 'username',]
admin.site.register(CustomUser, CustomUserAdmin)
# users/forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from .models import CustomUser
class CustomUserCreationForm(UserCreationForm):
class Meta(UserCreationForm):
model = CustomUser
fields = ('username', 'email')
class CustomUserChangeForm(UserChangeForm):
class Meta:
model = CustomUser
fields = ('username', 'email')
# users/models.py
from django.contrib.auth.models import AbstractUser
from django.db import models
class CustomUser(AbstractUser):
# add additional fields in here
credit = models.IntegerField(default=200) # editable=False
def __str__(self):
return self.email
# users/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('signup/', views.SignUp.as_view(), name='signup'),
]
# users/views.py
from django.urls import reverse_lazy
from django.views import generic
from .forms import CustomUserCreationForm
class SignUp(generic.CreateView):
form_class = CustomUserCreationForm
success_url = reverse_lazy('login')
template_name = 'signup.html'
Use a post-save signal
https://docs.djangoproject.com/en/2.1/ref/signals/
from django.db.models.signals import post_save
from django.dispatch import receiver
#receiver(post_save, sender=User)
def say_hello(sender, instance, **kwargs):
if instate._state.adding:
print('hello')
Signal is better than a method on the view because the User may be created some way other than through the view e.g , via the shell, a management command, a migration, a different view, etc.
Note the _state is not "private" so don't feel bad about using it, it's just named that way to avoid clashing with field names.
Check _state instead of more common checking instance.pk because instance.pk is always present when primary key is a natural key rather than AutoField
I think the best approach would be overriding save method of CustomUser model. For example:
class CustomUser(AbstructUser):
def save(self, *args, **kwargs):
user = super(CustomUser, self).save(*args, **kwargs)
print("Hello World")
return user
Check here in Django documentation for more details: https://docs.djangoproject.com/en/2.1/topics/db/models/#overriding-predefined-model-methods.