I was using routers for creating urls now i want to make urls for my api, but problem is, i am getting error
createuser() missing 1 required positional argument: 'request'missing 1 required positional argument: 'request'
iam getting same error for all my methods inside UserAuthAPIView class, i have already read solutions on stackoverflow but they are not working i my case.
I have many methods in UserAuthAPIView class and i want to create urls for all of those.
for eg
127.0.0.1:8000/api
127.0.0.1:8000/api/createuser
127.0.0.1:8000/api/login
127.0.0.1:8000/api/<pk>/viewuser
urls.py
from django.conf.urls import url
from UserAPI.api import views
from UserAPI.api.views import UserAuthAPIView
urlpatterns = [
url(r'^$', UserAuthAPIView.as_view({'get': 'list'}), name='user-list'),
url(r'createuser/$', views.UserAuthAPIView.createuser, name='user-create'),
#url(r'userlogin/$', views.UserAuthAPIView.userlogin, name='user-login'),
]
views.py
class UserAuthAPIView(ModelViewSet):
queryset = UserModel.objects.all()
serializer_class = ListViewSerializer
def get_object(self, queryset=None):
return self.request.user
#action(methods=['post'], detail=False, permission_classes=[AllowAny], serializer_class=UserSerializer)
def createuser(self, request, *args, **kwargs):
data = request.data
serializer = UserSerializer(data=data)
if serializer.is_valid():
serializer.save()
return Response({ "status" : "user created successfully"}, status=HTTP_201_CREATED)
Routers preform a couple of operations on the viewset and in particular add a mapping from the http verbs to the associated functions.
You need to do something similar for your action:
urlpatterns = [
url(r'^$', UserAuthAPIView.as_view({'get': 'list'}), name='user-list'),
url(r'createuser/$', views.UserAuthAPIView.as_view({'post': 'createuser'}), name='user-create'),
]
You are call the Viewset in urls in wrong way. You need do it like this:
router = routers.DefaultRouter()
router.register(r'auth', UserAuthAPIView)
urlpatterns = [
url(r'^', include(router.urls)),
]
Or
urlpatterns = [
url(r'createuser/$', UserAuthAPIView.as_view({'post':'createuser'}),
]
Related
am confuse right now...i want to pass in a key value but i kept on getting error
my code urls
from django.urls import URLPattern, path
from . import views
urlpatterns = [
path('', views.projects, name="projects"),
path('project/', views.project, name="project"),
]
and the function i created
def project(request, pk):
projectObj = None
for i in projectslist:
if i['id'] == pk:
projectObj = i
return render(request, 'projects/single-project.html', {'project': projectObj})
You need to set the pk argument in your url.
path('project/<int:pk>/', views.project, name="project"),
Related docs. URLS, Views
new to coding so I'm sure this is a simple problem but I can't seem to figure it out. I've abbreviated the code so it's simpler to see the problem.
urls.py
router = routers.DefaultRouter()
router.register(r'clients', views.ClientViewSet, basename='client')
urlpatterns = [
#Bunch of other paths here.
path('client/<int:pk>/contacts',
login_required(views.contacts_by_client), name="client-contacts"),
path('api/', include(router.urls)),
]
views.py
def contacts_by_client(request, pk):
client = Client.objects.get(id=pk)
contact_list = Contact.objects.filter(user=request.user, client=pk)
context = {
'contacts': contact_list,
'client': client
}
return render(request, 'pages/contacts-client.html', context)
class ClientViewSet(viewsets.ModelViewSet):
serializer_class = ClientSerializer
permission_classes = [permissions.IsAuthenticated]
#action(detail=True, methods=['get'], name="Contacts")
def contacts(self, request, pk=None):
# Bunch of code here.
My suspicion is that the router is creating a route name called "client-contacts" based on the action created in views.py, however, I don't understand why it would take precedence over the explicitly labeled url pattern that comes before it.
I know I must be missing something super simple, but I can't figure it out. Thank you all for your help!
Thank you in advance,
I'm new to Django REST Framework.
when i use get() method with id parameter, it is working fine
Below is url.py
urlpatterns = [
path('admin/', admin.site.urls),
url(r'api/userList/$', UserList.as_view(), name="userList"),
url(r'^api/userList/(?P<id>\d+)/$', UserDetails.as_view(), name="userDetails")
]
Below is api.py:
class UserDetails(APIView):
def get(self, request, id):
model = Users.objects.get(id=id)
serializer = UsersSerializers(model)
return Response(serializer.data)
above code is fine
When i try to get user details by using emailID, i'm not able to get the details, showing below error:
Using the URLconf defined in myProject.urls, Django tried these URL patterns, in this order:
1. admin/
2. api/userList/$ [name='userList']
3. ^api/userList/(?P<emailID>\d+)/$ [name='userDetails']
The current path, api/userList/sannila1527#gmail.com/, didn't match any of these.
Below is api.py:
class UserDetails(APIView):
def get(self, request, emailID):
model = Users.objects.get(emailID=emailID)
serializer = UsersSerializers(model)
return Response(serializer.data)
Can you please help me on this.
Try changing your url.py to
urlpatterns = [
path('admin/', admin.site.urls),
url(r'api/userList/$', UserList.as_view(), name="userList"),
url(r'^api/userList/(?P<emailID>\w+|[\w.%+-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4})/$', UserDetails.as_view(), name="userDetails")
]
Try changing this, urls.py
url(r'^api/userList/(?P<id>\d+)/$', UserDetails.as_view(), name="userDetails")
to,
url(r'^api/userList/(?P<emailID>\d+)/$', UserDetails.as_view(), name="userDetails")
Note: This can make problems at other places, you can fix them by replacing id with emailID elsewhere.
urls.py
from rest_framework import routers
router = routers.DefaultRouter()
router.register('fan/<str:name>', FanView)
urlpatterns = [
path(r'', include(router.urls)),
]
view.py
class FanView(viewsets.ModelViewSet):
queryset = Fan.objects.all()
serializer_class = FanSerializer
def get_queryset(self):
queryset = Fan.objects.all()
print(self.request.query_params.get('name', None))
return queryset
Hi i am trying to send name in djnago-rest-framework url.
And reading the same in my viewSet.
But, i am always getting None.
I don't wants to send data like fan/?name=foo
Please have a look
Is there any way to achive that ?
What you are trying to access is not in query_params. This is a url parameter and is stored in self.kwargs.lookup_field. You can find here how to access the url parameter.
I have a ViewSet:
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
And appropriate urls:
from .users.api.views import UserViewSet
router = routers.DefaultRouter()
router.register('users', UserViewSet, 'user')
urlpatterns = [
url(r'^v1/', include(router.urls)),
]
It works, but I want to add username-password authentification to UserViewSet:
#list_route(methods=['post'], permission_classes=[AllowAny])
def login(self, request):
#check login and password
#creare and return token
Of cource I can write It by my-self, but I interest, how I can use rest_framework.authtoken.views.ObtainAuthToken for my goals.
Per the documentation, you can expose an API endpoint that takes a username/password and returns a token using rest_framework.authtoken.view.obtain_auth_token. See the rest framework Docs for more details. You urls.py would look like this:
from .users.api.views import UserViewSet
from rest_framework.authtoken import views
router = routers.DefaultRouter()
router.register('users', UserViewSet, 'user')
urlpatterns = [
url(r'^v1/', include(router.urls)),
url(r'^v1/login, views.obtain_auth_token)
]
If you really want this url to belong to the UserViewSet that you've already defined, you will need to define a detail_route and manually call authenticate and then generate a token for the authenticated user (if authenticate succeeds). I recommend using the first pattern I described as it's less code/customization.