URL parameter in Django RESTApi - django

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.

Related

Django REST Framework router seems to be overriding my explicitly defined path in URLpatterns

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!

Django can't find my DetailView with Primary Key

I'm trying to make a simple page with Django where posts are being displayed using primary keys. However, the DetailView page with my posts can't be displayed.
This is my model:
class Post(models.Model):
author = models.CharField(max_length=100)
title = models.CharField(max_length=100)
posted_date = timezone.now()
text = models.TextField()
def get_absolute_url(self):
return reverse("postdetail", kwargs={"pk": self.pk})
def __str__(self):
return self.title
and here is my url pattern list:
urlpatterns = [
url(r'^posts/(?P<pk>\d+)$', views.PostDetail.as_view(), name="postdetail"),
url(r'^$', views.index, name="index"),
url(r'^thanks/$', views.Thanks.as_view(), name="thanks"),
url(r'^postlist/$', views.PostList.as_view(), name="postlist"),
]
The template is in my templates folder under the name "post_detail.html".
Here is the DetailView:
class PostDetail(DetailView):
context_object_name = 'post_details'
model = Post
I can't see where I might have a mistake. I have a ListView that shows my posts including the primary keys. But when I try to open the URL http://127.0.0.1:8000/posts/1/
I get:
`Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/posts/1/
Using the URLconf defined in myproj.urls, Django tried these URL patterns, in this order:
admin/
^posts/(?P<pk>\d+)$ [name='postdetail']
^$ [name='index']
^thanks/$ [name='thanks']
^postlist/$ [name='postlist']
The current path, posts/1/, didn’t match any of these.
Do you have a clue why the URL cannot be found? Thank you very much.`
Instead of url() use path()
from django.urls import path
urlpatterns = [
path('', views.index, name = "index"),
path('posts/<int:pk>', views.PostDetail.as_view(), name = "postdetail"),
path('postlist/', views.PostList.as_view(), name="postlist"),
path('thanks', views.Thanks.as_view(), name = "thanks"),
]
NB: url() been deprecated since version 3.1 and removed in 4.0
You are trying to access : http://127.0.0.1:8000/posts/1/ when you define the following http://127.0.0.1:8000/posts/1 without the backlash.
Try : http://127.0.0.1:8000/posts/1
First Things Is Your Views. You can send your database data with return it to the HTML.
views.py
def post(request,id):
post = Post.objects.get(id=id)
return render(request,'blog/index.html',{'post':post})
and before sending data into the HTML you should get the post id in your urls.py
urls.py
path('post/<int:id>', views.post, name='post.blog')
then in your HTML you can handle that data comes from your views.py
index.html
<div class="post-content content">{{ post.body|safe }}</div>

Django-rest-framework read url data

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.

missing 1 required positional argument: 'request' django restframework

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'}),
]

Django DetailView occurs an error?

I Implemented very simple DetailView in Django 1.9.5:
class PostDetailView(DetailView):
Model = Post
template_name = "post/detail.html"
urls.py
from django.conf.urls import url
from chacha_dabang.views import *
urlpatterns = [
url(r'^$', PostListView.as_view(), name="post_list"),
url(r'^new/$', post_new, name="post_new"),
url(r'^(?P<pk>\d+)/$', PostDetailView.as_view(), name="post_detail"),
url(r'^(?P<pk>\d+)/edit$', post_edit, name="post_edit"),
url(r'^(?P<pk>\d+)/delete$', post_delete, name="post_delete"),
url(r'^(?P<pk>\d+)/comment/new/$', comment_new, name="comment_new"),
url(r'^(?P<pk>\d+)/comment/(?P<comment_pk>\d+)/edit$', comment_edit, name="comment_edit"),
]
Errors :
I don't know why it says I have to override query_set(). (As I Know, DetailView automatically set query according to pk)
If I used Function Based View like below,
def post_detail(request, pk):
post = Post.objects.get(pk=pk)
return render(
request,
'post/detail.html',
{
'post': post,
}
)
It totally works fine. Need your helps.
You capitalized model. It is not Model, it should be model.