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)
Related
I've been attempting to construct a multi-step form using the Django session wizard for hours, but I keep getting the error, AttributeError: 'function' object has no property 'as_view'. I'm not sure why this mistake occurred. Any ideas?
views
from django.shortcuts import render
from formtools.wizard.views import SessionWizardView
from .forms import WithdrawForm1, WithdrawForm2
class WithdrawWizard(SessionWizardView):
template_name = 'withdraw.html'
form_list = [WithdrawForm1, WithdrawForm2]
def done(self, form_list, **kwargs):
form_data = [form.cleaned_data for form in form_list]
return render(self.request, 'done.html', {'data': form_data})
forms
from django import forms
from .models import Investment, Withdraw
from .models import WithdrawStepOne, WithdrawStepTwo
class WithdrawForm1(forms.ModelForm):
class Meta:
model = WithdrawStepOne
fields = ['investment_id',]
class WithdrawForm2(forms.ModelForm):
class Meta:
model = WithdrawStepTwo
fields = [
'proof_of_address',
'user_pic'
]
urls
from django.urls import path
from .forms import WithdrawForm1, WithdrawForm2
from . import views
urlpatterns = [
path('withdraw/', views.WithdrawWizard.as_view(), name='withdraw'),
]
You used #login_required decorator on WithdrawWizard class, but the decorator works only for function based views.
Use LoginRequiredMixin for class based views.
I have the below simple rest api set up in Django. Calling the url http://127.0.0.1:8000/listheros/ returns
TypeError: Object of type Hero is not JSON serializable
for a reason I can't seem to figure out.
# views.py
from rest_framework.views import APIView
from rest_framework.response import Response
from .serializers import HeroSerializer
from .models import Hero
class ListHeros(APIView):
def get(self, request, format=None):
"""
Return a list of all users.
"""
queryset = Hero.objects.all().order_by('name')
serializer_class = HeroSerializer
print('get')
return Response(queryset)
# urls.py
from django.urls import include, path
from applications.api.views import ListHeros
urlpatterns = [
path('listheros/', ListHeros.as_view()),
path('api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]
# serializers.py
from rest_framework import serializers
from .models import Hero
class HeroSerializer(serializers.ModelSerializer):
class Meta:
model = Hero
fields = ('name', 'alias')
# models.py
from django.db import models
class Hero(models.Model):
name = models.CharField(max_length=60)
alias = models.CharField(max_length=60)
def __str__(self):
return self.name
You don't serialize your queryset of heroes. Your ListHeroes api view should looks like below:
class ListHeros(APIView):
def get(self, request, format=None):
"""
Return a list of all users.
"""
queryset = Hero.objects.all().order_by('name')
serializer = HeroSerializer(queryset, many=True)
return Response(serializer.data)
You can also use generics ListApiView instead of APIView:
from rest_framework.generics import ListAPIView
class ListHeros(ListAPIView):
queryset = Hero.objects.all().order_by('name')
serializer_class = HeroSerializer
i can't call my detail class using reverse_lazy
from django.shortcuts import render, redirect
from django.urls import reverse_lazy, reverse
from . models import Task
from . forms import Taskform
from django.views.generic import ListView
from django.views.generic.detail import DetailView
from django.views.generic.edit import UpdateView
class Tasklistview(ListView):
model = Task
template_name = 'home.html'
context_object_name = 'task'
class Detailview(DetailView):
model=Task
template_name = "details.html"
context_object_name = 'task'
class Updateview(UpdateView):
model = Task
template_name = "update.html"
context_object_name = "task"
fields = ('name', 'priority', 'date')
def get_success_url(self):
return reverse_lazy("cbvdetail",kwargs={'pk':self.object.id})
urls.py
from django.urls import path
from . import views
app_name='todoapp'
urlpatterns = [
path('',views.home,name='home'),
# path('details', views.details,name='ere')
path('delete/<int:id>/',views.delete,name='delete'),
path('edit/<int:id>/',views.update,name='update'),
path('cbvhome/',views.Tasklistview.as_view(),name='home'),
path('cbvdetail/<int:pk>/',views.Detailview.as_view(),name='cbvdetail'),
path('cbvupdate/<int:pk>/',views.Updateview.as_view(),name='edit'),
]
i want to resolve this
You specified an app_name in the urls.py file. That means you need to prefix the name of the view with that app label, so:
def get_success_url(self):
return reverse_lazy('todoapp:cbvdetail', kwargs={'pk':self.object.id})
If you override get_success_url, it does not make much sense to work with reverse_lazy, since that method will (normally) only be triggered in case the urls are already loaded, you can thus work with:
from django.urls import reverse
# ⋮
def get_success_url(self):
return reverse('todoapp:cbvdetail', kwargs={'pk':self.object.id})
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'
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)