Quick Contact

    Python Tutorial
    Python Panda Tutorial
    Python Selenium
    Python Flask Tutorial
    Python Django
    Numpy
    Tensorflow
    Interview Questions & Answers

    What is CRUD?

    CRUD stands for Create, Read, Update & Delete. These are the four basic operations which are executed on Database Models. We are developing a web app which is capable of performing these operations.

    Since we are developing a library app, let’s take an example of the same. In a library, books are objects. The books have attributes like name, author, etc. We need an application which can perform CRUD operations on book object. The CRUD operations are defined as follows:

    1. Read Operation

      The ability of the application to read data from the database.

    2. Create Operation

      The ability of the application to store data in the database.

    3. Update Operation

      The ability of the application to edit the stored value in the database.

    4. Delete Operation

      The ability of the application to delete the value in the database.

    We are going to develop the operations in the same order.

    Majority of applications on the internet are CRUD applications. For example – Facebook uses CRUD operations to save your data on their database. You can change your profile picture that means perform the update operation. Of course, you can see the data in-app or browser which is read operation.

    Django CRUD Tutorial

    Let’s explore the steps to design a CRUD application in Django framework:

    1. Making a Library CRUD Application

      Our first steps would be to make a new project in Django and a new virtual environment. To make a virtual environment, enter:

    2. Installing Application and Other Important Settings

      To install the app, just add the application’s name in the INSTALLED_APPS list. This is inside settings.py file.

      Once you complete this step, we also need to establish the Static Files Settings. Copy these settings as it is and replace it with the existing settings of your project.

      Code:

      # Ducatindia Static Files Settings
      STATIC_URL = '/static/'
      STATIC_ROOT = os.path.join(BASE_DIR, 'static-files')
      #Ducatindia #User_Uploaded_Files
      MEDIA_URL = 'media/'
      MEDIA_ROOT=os.path.join(BASE_DIR, 'media')
      
    3. Making Models for Books App

      In the book folder, open models.py and paste this code. We are making a model or database table for our books app.

      Code:

      from django.db import models
      #Ducatindia Models
      classBook(models.Model):
      name = models.CharField(max_length = 50)
      picture = models.ImageField()
      author = models.CharField(max_length = 30, default=’anonymous’)
      email = models.EmailField(blank = True)
      describe = models.TextField(default = ‘DataFlair Django tutorials’)
      def__str__(self):
      return self.name
      
    4. Making Model Forms in Book Directory

      Django makes it so much easier to make forms for models. We just need to use our models and we can easily make forms.

      Make a new file forms.py in book directory. Paste this code in this forms.py.

      Code:

      from django import forms
      from .models import Book
      #Ducatindia
      classBookCreate(forms.ModelForm):
      class Meta:
      model = Book
      fields = '__all__'
      
    5. 5. Registering Model in Django Admin

      Here we are editing admin.py existing in book folder. Import the model you want to register in the admin. In this case, it is a Book.

      Then paste this line below it.

      Code:

      admin.site.register(Book)

    6. Making View Functions for Django CRUD App

      The view functions are our actual CRUD operations in Django. Now, we are editing views.py in book folder. Open views.py file in the folder. Paste this code in it:

      Code:

      from django.shortcuts import render, redirect
      from .models import Book
      from .forms import BookCreate
      from django.http import HttpResponse
      #Ducatindia
      defindex(request):
      shelf = Book.objects.all()
      returnrender(request, 'book/library.html', {'shelf': shelf})
      defupload(request):
      upload = BookCreate()
      if request.method == 'POST':
      upload = BookCreate(request.POST, request.FILES)
      if upload.is_valid():
      upload.save()
      returnredirect('index')
      else:
      returnHttpResponse("""your form is wrong, reload on < a href = "{{ url :'index'}}">reload< /a>""")
      else:
      returnrender(request, 'book/upload_form.html', {'upload_form':upload})
      defupdate_book(request, book_id):
      book_id = int(book_id)
      try:
      book_sel = Book.objects.get(id = book_id)
      except Book.DoesNotExist:
      returnredirect('index')
      book_form = BookCreate(request.POST or None, instance = book_sel)
      if book_form.is_valid():
      book_form.save()
      returnredirect('index')
      returnrender(request, 'book/upload_form.html', {'upload_form':book_form})
      defdelete_book(request, book_id):
      book_id = int(book_id)
      try:
      book_sel = Book.objects.get(id = book_id)
      except Book.DoesNotExist:
      returnredirect('index')
      book_sel.delete()
      returnredirect('index')
      
    7. Making Templates

      The first thing you need to do is to make the templates folder in the book folder. Inside book/templates, make another folder book. We are going to make all our templates in that folder.

      Inside book/templates/book, make a new file:

      < !DOCTYPE html>
      {% load static %}
      < html>
      < head>
      < title>Books App< /title>
      < link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
      integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
      < /head>
      < body style="background-color:#4DB6AC;">
      < nav class="navbar navbar-light" style="background-color:#FF0033;">
      < a href="#" class="navbar-brand" style="background-color:#FFCC33;color:#000000;border-width:10px;border-color:#FFCC33;border-style:solid;border-spacing:30px;border-radius: 5px;">Library App< /a>
      < a class="navbar-link btn-lg" href="{% url 'index' %}" style="background-color:#FFCC33;color:#000000;">DataFlair< /a>
      < a href="{% url 'admin:index' %}" class = 'navbar-link btn-lg' style="background-color:#FFCC33;color:#000000;">Admin< /a>
      < a href="{% url 'upload-book' %}" class="navbar-link btn-lg" style="background-color:#FFCC33;color:#000000;">Upload Books< /a>
      < /nav>
      < br>
      {% block content %}
      < div class="card-columns">
      {% for book in shelf %}
      < div class="card" style="width: 18rem;">
      < img class="card-img-top" src="{{ book.picture.url }}">
      < div class="card-body">
      < h5 class="card-title">{{ book.name }}< /h5>
      < p class="card-text">{{ book.describe }}< /p>
      < div class="card-footer bg-transparent border-dark">
      < p class="card-title">{{book.author}}< /p>
      < center>
      < a href="update/{{book.id}}" class="btn btn-warning" id = '{{book.id}}'>edit< /a>
      < a href="delete/{{book.id}}" class="btn btn-danger" id = '{{book.id}}'>delete< /a>
      < /center>
      < /div>
      < /div>
      < /div>
      {% endfor %}
      < /div>
      {% endblock %}
      < /body>
      < /html>
      
    8. Configuring URLs

      Now, we need to configure the urls file. Paste this code as it is in the mentioned urls files. If the file doesn’t exist then make one and copy the whole thing.

      Code:
      from django.contrib import admin
      from django.urls import path, include
      #Ducatindia
      urlpatterns = [
      path('admin/', admin.site.urls),
      path('', include('book.urls'))
      ]
      

      Code:

      from django.urls import path
      from . import views
      from libraryapp.settings import DEBUG, STATIC_URL, STATIC_ROOT, MEDIA_URL, MEDIA_ROOT
      from django.conf.urls.static import static
      urlpatterns = [
      path('', views.index, name = 'index'),
      path('upload/', views.upload, name = 'upload-book'),
      path('update/< int:book_id>', views.update_book),
      path('delete/< int:book_id>', views.delete_book)
      ]
      #Ducatindia
      if DEBUG:
      urlpatterns += static(STATIC_URL, document_root = STATIC_ROOT)
      urlpatterns += static(MEDIA_URL, document_root = MEDIA_ROOT)
      

     

    Apply now for Advanced Python Training Course

    Copyright 1999- Ducat Creative, All rights reserved.

    Anda bisa mendapatkan server slot online resmi dan terpercaya tentu saja di sini. Sebagai salah satu provider yang menyediakan banyak pilihan permainan.