Home > Software engineering >  django restframwork Put and DELETE doesn't work
django restframwork Put and DELETE doesn't work

Time:06-05

Get and post work pretty well for me . but put and delete i use "U_repo_name" to look in table i got the error message :

Page not found (404) Request Method: PUT Request URL: http://localhost:8000/gitapi/repo/authoo/ Using the URLconf defined in gitit.urls, Django tried these URL patterns, in this order:

admin/ gitapi/ [name='gitapi'] gitapi/ repo/ gitapi/ repo/str:U_repo_name

this is my model :

class UserRepos(models.Model):
    U_repo_name =models.CharField( max_length=50)

this is my url :

urlpatterns = [
    path('repo/',view=userreposapi),
    path('repo/<str:U_repo_name>',view=userreposapi),
]

project urls :

urlpatterns = [
    path('admin/', admin.site.urls),
    path('gitapi/',include('gitapi.urls')),
]

this is my serializer :

class UserReposSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserRepos
        fields ='__all__'

and this is my views :

@csrf_exempt
def userreposapi(request,id=0):
    if request.method=='GET':
        userrepos = UserRepos.objects.all()
        userreposserializer = UserReposSerializer(userrepos , many=True)
        return JsonResponse(userreposserializer.data , safe=False)

    elif request.method=='POST':
        userrepos_data=JSONParser().parse(request)
        userreposerializer = UserReposSerializer(data=userrepos_data)
        if userreposerializer.is_valid():
            userreposerializer.save()
            return JsonResponse("added successfully!!",safe=False)
        return JsonResponse("failed to add",safe=False)
    
    elif request.method=='Put':
        userrepos_data=JSONParser().parse(request)
        userrepos = UserRepos.objects.get(U_repo_name=userrepos_data['U_repo_name'])
        userreposserializer=UserReposSerializer(userrepos,data=userrepos_data)
        if userreposserializer.is_valid():
            userreposserializer.save()
            return JsonResponse("updated successfully", safe=False)
        return JsonResponse("failed to update",safe=False)


    elif request.method=='DELETE':
        userrepos = UserRepos.objects.all()
        userrepos.delete()
        return JsonResponse("deleted",safe=False)

CodePudding user response:

Hi! I see a few issues with your code that might be causing this problem.

  1. request.method is always full capitalized, so you should use the string 'PUT' instead of 'Put' on this line:

    elif request.method=='Put':
    
  2. You are adding a trailing slash to your route when trying to access it (/gitapi/repo/authoo/), but the pattern set in urlpatterns doesn't have this trailing slash:

    path('repo/<str:U_repo_name>',view=userreposapi),
    

    You can use re_path() instead of path() to set a regex URL pattern that works whether you add a trailing slash or not:

    re_path(r'repo/(?P<U_repo_name>\w )/?', view=userreposapi),
    

    (?P<U_repo_name>\w ) creates a named group called U_repo_name that matches any word character ([a-zA-Z0-9_]) from one to more times. /? matches a single optional /.

  3. Your route 'repo/<str:U_repo_name>' captures a string in the variable U_repo_name. This variable is provided to the view userreposapi() as a keyword argument, but the view currently only accepts the id kwarg. You should either add the U_repo_name kwarg as an optional argument or make the view accept other keyword arguments with **kwargs:

    # Both are valid:
    def userreposapi(request, id=0, U_repo_name=None):
        ...
    def userreposapi(request, id=0, **kwargs):
        ...
    

Fixing these 3 issues should make the route work.

CodePudding user response:

I think the trailing slash in the url is the problem. I should be not there.

http://localhost:8000/gitapi/repo/authoo  # here I removed the trailing slash.
  • Related