pythondjangodjango-views

How do I GET and POST from different urls to the same class based view in my django project?


I am working on this coursework where I need to create a Django back-end with API routes and templated routes. Within the descriptor, I was given the routes which the project needs to follow. I made a class based view which successfully creates albums. However, the issue which I see is that my implementation GET and POST to /albums/new. Where the descriptor, says I have to GET from /albums/new and POST to /albums to create a new album. I've looked everywhere online to figure out how to implement this and haven't found anything. The lecturer then gave us a tip: The POST of /albums/new/ could be mapped to POST /albums/ using the Django URL dispatcher, where it calls the same class or method for POST. But still had no luck finding anything.

Here's my code:

views.py album creation view

class AlbumCreateView(SuccessMessageMixin, generic.edit.CreateView):
    form_class = AlbumForm
    template_name = 'label_music_manager/update_album.html'    
    success_message = _('AlbumCreated')

    def get_success_url(self):
        return self.object.get_absolute_url()

    def dispatch(self, request):
        if not check_editor(request.user):
            return redirect('album_list')
        return super().dispatch(request)

url patterns of my view (I created a temporary fix where I can POST to /albums by calling the same view but I don't think that's intended because they wouldn't have separated it)

path('albums/', views.AlbumCreateView.as_view(), name='create_album'),
path('albums/new/', views.AlbumCreateView.as_view(), name='new_album'),

Solution

  • You could catch and check the url in the dispatch method.

    def dispatch(self, request, *args, **kwargs):
            if not check_editor(request.user):
                return redirect('album_list')
    
            if request.method == 'POST' and self.request.path == reverse_lazy('new_album'):
                return redirect('create_album')
            return super().dispatch(request, *args, **kwargs)
    

    This way, it would re-direct to the / url