lordsarcastic
lordsarcastic

Reputation: 369

How do I structure my Django view classes?

I and a friend are about working on a project. I have a structure for working with my views. If I'm working with the User model, and I want to write code for CRUD operation, I write using four different classes. One for each like so:

class CreateUser(FormView):
    <code here>


class ReadUser(DetailView):
    <code here>


class UpdateUser(UpdateView):
    <code here>


class DeleteUser(DeleteView):
    <code here>

Each has a respective URL pattern:

urlpatterns = [
    path("auth/users/create-user/", CreateUser().as_view(), name="create_user"),
    path("auth/users/<int:pk>", ReadUser().as_view(), name="user_detail"),
    path("auth/users/<int:pk>/update", UpdateUser().as_view(), name="update_user"),
    path("auth/users/<int:pk>/delete/", DeleteUser().as_view(), name="delete_user")
]

He proposes that instead, all functionalities should be in one class and performed by methods, like so:

class UserView(View):
    <class variables>

    def post(self, request):
        <code here>

    def get(self, request):
        <code here>

    def patch(self, request):
        <code here>

    def delete(self, request):
        <code here>

And the urlpatterns be:

urlpatterns = [
    path("auth/users/", UserView.as_view(), name="user")
]

The questions I have are which is better:

  1. Django-wise;
  2. Generally;
  3. When rendering from server side in django;
  4. When writing APIs in django

The first or the second one?

Upvotes: 0

Views: 111

Answers (1)

hectorcanto
hectorcanto

Reputation: 2286

I think your friend's proposal goes the right way and I would go a little bit further.

I recommend you using Django Rest Framework. It already has Class-based views that can save you a lot of time of coding.

Depending on the degree of customization you want to introduce you may choose between:

API Views or Generics Classes with Mixins

Also, I will be careful about mixing user registration and user authentication. It is quite usual to keep the resource "user(s)" and "auth" apart.

As a last advice, I will recommend you to avoid building the registration and authentication process by yourself - although it is a good learning exercise and go for an existing solution, either by public repositories or the wide variety of libraries out there that can provide you with token generation, OAUTH2, social register and authentication (Social Django f.i.) and many more.

Upvotes: 1

Related Questions