3

I am trying to create a restful api using class based views in django.

class SomeAPI(MultiDetailView):
    def get(self,request,format=None):
        #some logic
    def post(self,request,format=None):
        #some logic

I want to process a get request like www.pathtowebsite.com/api?var1=<someval>&var2=<someval>&var3=<someval>

My post url would be www.pathtowebsite.com/api/unique_token=<token_id>

Basically a get request would generate a unique token based on some parameters and a post request would post using that token.

How would my URL file look like in such a scenario?

P.S I have hardly ever worked with class based views.

1 Answer 1

1

First of all: DRF will do a lot of your legwork for you, even generate consistent URLs across your API. If you want to learn how to do things like this in the Django URL dispatcher then you can embed regexes in your URLS:

project/urls.py: from django.conf.urls import url

from project.app.views import SprocketView

urlpatterns = [
    url(r'^api/obj_name/(P<id>[a-f0-9]{24})/$', SprocketView.as_view()),
    url(r'^api/obj_name/unique_token=(P<id>[a-f0-9]{24})/$', SprocketView.as_view()),
    ]

project/app/views.py

from django.shortcuts import get_object_or_404
from django.views.generic import View
from .forms import SprocketForm
from .models import Sprocket

class SprocketView(View):

    def get(request, id):
        object = get_object_or_404(Sprocket, pk=id)
        return render(request, "sprocket.html", {'object':object}

    def post(request, id):
        object = Sprocket.get_or_create(pk=id)
        object = SprocketForm(request.POST, initial=object).save(commit=False)
        object.user = request.user
        object.save()
        return render(request, "sprocket.html", {'object':object, 'saved':True})

That's a lof of functionality that frameworks are supposed to lift from you and I suggest reading about Django CBV. One resource I can wholeheartedly recommend is Two Scoops.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.