CRUD Function-Based Views Django.How

Author avatar wrote on 02/06/2022

1. Models.py


from django.db import models  
from django.urls import reverse  
from django.contrib.auth.models import User  
  
  
class Movies(models.Model):  
  
   user = models.ForeignKey(User, on_delete=models.CASCADE)  
   title = models.CharField(max_length=200)  
   genre = models.CharField(max_length=200)  
  
   def __unicode__(self):  
     return self.title  
  
   def get_absolute_url(self):  
     return reverse('CRUD_FBVs:movies_edit', kwargs={'pk': self.pk})

2. Admin.py


from django.contrib import admin  
from .models import Movies  
   
 admin.site.register(Movies)

3. Forms.py


from django import forms  
from .models import Movies  
   
   
class MoviesForm(forms.ModelForm):  
   
     class Meta:  
         model = Movies  
         fields = ['title', 'genre']

Function-Based Views

4. Views.py - Function-Based Views

5 Urls.py - Function-Based Views

from django.conf.urls import url  
 from django.contrib import admin  
 from CRUD_FBVs import views  
   
 app_name = 'CRUD_FBVs'  
   
 urlpatterns = [  
     url('admin/', admin.site.urls),  
     url(r'^$', views.movies_list, name='movies_list'),  
     url(r'^new$', views.movies_create, name='movies_new'),  
     url(r'^edit/(?P\d+)$', views.movies_update, name='movies_edit'),  
     url(r'^delete/(?P\d+)$', views.movies_delete, name='movies_delete'),  
 ]

Class-Based Views

4. Views.py - Class-Based Views

from django.views.generic import ListView  
 from django.views.generic.edit import CreateView, UpdateView, DeleteView  
 from django.urls import reverse_lazy  
   
 from CRUD_CBVs.models import Movies  
   
   
 class MoviesList(ListView):  
     model = Movies  
   
   
 class MoviesCreate(CreateView):  
     model = Movies  
     fields = ['title', 'genre']  
     success_url = reverse_lazy('CRUD_CBVs: movies_list')  
   
   
 class MoviesUpdate(UpdateView):  
     model = Movies  
     fields = ['title', 'genre']  
     success_url = reverse_lazy('CRUD_CBVs: movies_list')  
   
   
 class MoviesDelete(DeleteView):  
     model = Movies  
     success_url = reverse_lazy('CRUD_CBVs: movies_list')  

5. Urls.py - Class-Based Views

from django.conf.urls import url  
 from django.contrib import admin  
 from CRUD_CBVs import views  
   
 app_name = 'CRUD_CBVs'  
   
 urlpatterns = [  
     url('admin/', admin.site.urls),  
     url('', views.MoviesList.as_view(), name='movies_list'),  
     url(r'^new$', views.MoviesCreate.as_view(), name='movies_new'),  
     url(r'^edit/(?P\d+)$', views.MoviesUpdate.as_view(), name='movies_edit'),  
     url(r'^delete/(?P\d+)$', views.MoviesDelete.as_view(), name='movies_delete'),  
 ] 

6. Templates
Movie_list.html

Movies_form.html

Confirm_delete.html

  • https://www.c-sharpcorner.com/article/crud-operations-in-django
  • CRUDgen Django CRUD generator