SlideShare una empresa de Scribd logo
1 de 17
Descargar para leer sin conexión
Basic CRUD in Django
Low-Level Creation, Updating, and Deletion of Data

                   by Mike Cantelon
                 http://mikecantelon.com
Setting Up a Project
1.   Change to the directory in which your project should be created

2.   Issue the command django-admin.py startproject linkdump

3.   This command will have created a directory, with the specified project name (in
     this case “linkdump”), containing base files for the project

4.   Change to this directory

5.   Issue the command python manage.py runserver to start the
     development server (http://127.0.0.1:8000)

6.   If your project is to use a new, rather than existing, database then create it
     (unless using sqlite, which be automatically created)

7.   Edit settings.py to configure access to your database

8.   Issue the command python manage.py syncdb to build database tables
     needed by the administration interface (useful later). Follow the prompts.
Creating an Application
1.   As a simple demonstration, we’ll create an application to submit links to

2.   To create the application’s directory and base files, we issue the command
     python manage.py startapp linktracker (“linktracker” being the
     name of our application)

3.   Next, we edit linktracker/models.py to define our model
          class Link (models.Model):
              link_description = models.CharField(maxlength=200)
              link_url = models.CharField(maxlength=200)

4.   To add our app to the project, we edit the project’s settings.py to add our
     app (linkdump.linktracker) to the INSTALLED_APPS list in settings.py

5.   To update the database, automatically creating the necessary tables, we issue
     the command python manage.py syncdb
Activating
                 Administration
1.   Add “django.contrib.admin” to the INSTALLED_APPS list in settings.py

2.   Issue the command python manage.py syncdb

3.   Edit urls.py to enable admin (the next slide will talk more about this file’s functionality)

4.   Issue the command python manage.py runserver

5.   You can verify that admin is running by browsing http://127.0.0.1:8000/admin

6.   Edit linktracker/models.py to turn on admin for links:
            class Link(models.Model):
                  # ...
                  class Admin:
                       pass

7.   Edit linktrackers/models.py to enable default (naming) column for links
            def __str__(self):
                  return self.link_description
Designing URLs
•   Now that we can enter data, adding a way for user to see this data would be
    useful

•   To present data we need to write a “view” which is mapped to a URL
    pattern

•   Editing urls.py allows URL patterns to be defined using regular expressions

•   Add the below link to your urls.py file:
    (r’^links/$’, ‘linkdump.linktracker.views.list’)

•   The above line will, if someone browses /links/ on our site, try to display the
    results of the list view of the links application of the linkdump project... we
    have not yet created a list view, however, so we just get an error!
Enabling Templating
1.   Views usually incorporate HTML templates so presentation is separated
     from logic

2.   To enable templating, create a directory called “template” in which to store
     your templates then edit settings.py and add “template” to TEMPLATE_DIRS

3.   Edit linktracker/views.py to create a list view for links that uses templating
         from linkdump.linktracker.models import Link
         from django.template import Context, loader
         from django.shortcuts import render_to_response

         def list(request):
             link_list = Link.objects.all()
             return render_to_response(
                 ‘links/list.html’,
                 {‘link_list’: link_list}
             )
Creating A Template
1.   We’ll create a template to crudely display link items

2.   Edit template/links/list.html:

          {% if link_list %}
              <ul>
                   {% for link in link_list %}
                       <li><a href=’{{ link.link_url }}’>
                           {{link.link_description}}</a></li>
                   {% endfor %}
              </ul>
          {% else %}
              <p>No links found.</p>
          {% endif %}

3.   The /links/ URL pattern now actually does something!
Pagination (1 of 3)
•   Use the admin interface to add a bunch of links then reload
    the /links/ URL

•   An unlimited list is a problem so we need to add pagination

•   We will have to add pagination support in three places: our
    URL patterns (urls.py), our list view (linktracker/views.py),
    and our template (template/links/list.html

•   To add a URL pattern supporting pagination, add the below
    line to urls.py:
    (r’^links/(?P<page>d+)’, ‘linkdump.linktracker.views.list’)
Pagination (2 of 3)
•   To add pagination support to linktracker/views.py, first add the following line
    near the start:
      from django.core.paginator import ObjectPaginator, InvalidPage


•   Next, change the list function in linktracker/views.py to the code below:
        def list(request, page = 0):
            page = int(page)
            link_list = ObjectPaginator(Link.objects.all(), 5)
            has_previous = link_list.has_previous_page(page)
            has_next = link_list.has_next_page(page)
            return render_to_response(‘links/list.html’,
                {‘link_list’: link_list.get_page(page),
                 ‘has_previous’: has_previous,
                 ‘previous_page’: page - 1,
                 ‘has_next’: has_next,
                 ‘next_page’: page + 1}
            )
Pagination (3 of 3)
•   Last, but not least, you’ll want to change your template/links/
    list.html HTML template to support pagination... add the
    following lines before the line containing “else”:
        {% if has_previous %}
        <a href=’/links/{{ previous_page }}’>Previous</a>
            {% if has_next %} | {% endif %}
        {% endif %}

        {% if has_next %}
        <a href=’/links/{{ next_page }}’>Next</a>
        {% endif %}


•   Pagination is now a wonder to behold!
Prep for CRUD (1 of 2)
•   Before getting into the nitty gritty of CRUD, we need a way to give users
    feedback for when they create, update, or delete data

•   One simple way to do this is by passing a message via a GET parameter

•   To allow this functionality we need to modify our list view to receive
    messages and modify the list.html template to display messages

•   Change the first line of the list view in views.py, adding a parameter for
    messages:
        def list(request, page = 0, message = quot;quot;):


•   Also in views.py, add a line in the list view so the passed message is
    included in the list of parameters relayed to the list.html template:
        ‘message’: message,
Prep for CRUD (2 of 2)
•   Now that we’re preparing to add CRUD functionality, we need to update
    our list HTML template as shown below:
      {% if message %}
       <b>{{ message }}</b>
       <p>
       {% endif %}
       {% if link_list %}
           <table>
           {% for link in link_list %}
               <tr bgcolor='{% cycle FFFFFF,EEEEEE as rowcolor %}'>
                    <td><a href='{{ link.link_url }}'>{{ link.link_description }}</a></td>
                    <td><a href='/links/edit/{{ link.id }}'>Edit</a></td>
                    <td><a href='/links/delete/{{ link.id }}'>Delete</a></td>
               </tr>
           {% endfor %}
           </table>
           <p>
           {% if has_previous %}
               <a href='/links/{{ previous_page }}'>Previous</a>
               {% if has_next %}|{% endif %}
           {% endif %}

           {% if has_next %}
               <a href='/links/{{ next_page }}'>Next</a>
           {% endif %}
       {% else %}
           <p>No links found.</p>
       {% endif %}
       <p>

       <a href='/links/new'>Add Link</a>
Creating Data (1 of 2)
•   Allowing users to submit data requires first displaying an HTML form then
    adding the submitted data

•   To start, add a URL for form display to urls.py:
        (r’^links/new’, ‘linkdump.linktracker.views.new’)


•   To deal with the submitted data, we add another URL to urls.py:
        (r’^links/add/’, ‘linkdump.linktracker.views.add’)


•   Then, to display an HTML add form in linktracker/views.py, add the following
    block of code:
        def new(request):
            return render_to_reponse(
                ‘links/form.html’,
                {‘action’: ‘add’,
                ‘button’: ‘Add’}
            )
Creating Data (2 of 2)
•   Next, we add the form HTML template (which, as written below, can be
    used for adding or editing, as we’ll see later):
       <form action=’/links/{{ action }}/’ method=’post’>
           Description:
           <input name=link_description value=”{{ link.link_description|escape}}”><br />
           URL:
           <input name=link_url value=’{{ link.link_url|escape }}’><br />
           <input type=submit value=’{{ button }}’>
       </form>


•   Finally, we add logic to linktracker/views.py to add the submitted data then
    return to the list view, passing a message:
       def add(request):
           link_description = request.POST[“link_description”]
           link_url = request.POST[“link_url”]
           link = Link(
               link_description = link_description,
               link_url = link_url
           )
           link.save()
           return list(request, message=”Link added!”)
Updating Data (1 of 2)
•   Allowing users to upate data requires first displaying an HTML form showing
    current data then, upon submission, doing the actual update

•   To start, add a URL for form display to urls.py:
        (r’^links/edit/(?P<id>d+)’, ‘linkdump.linktracker.views.edit’)


•   Then, to display an HTML edit form in linktracker/views.py, add the following
    block of code:
        def edit(request, id):
            link = Link.objects.get(id=id)
            return render_to_reponse(
                ‘links/form.html’,
                {‘action’: ‘update/’ + id,
                ‘button’: ‘Update’}
            )


•   NOTE: As the HTML form we added earlier can be used to edit, we’re re-
    using it in the above code
Updating Data (2 of 2)

•   To deal with submitted updates, we add another URL to urls.py:
        (r’^links/update/(?P<id>d+)’, ‘linkdump.linktracker.views.update’)


•   Finally, we add logic to linktracker/views.py to add the submitted data then
    return to the list view, passing a message:
        def update(request, id):
            link = Link.objects.get(id=id)
            link.link_description = request.POST[“link_description”]
            link.link_url = request.POST[“link_url”]
            link.save()
            return list(request, message=”Link updated!”)
Deleting Data

•   Allowing users to delete data requires first displaying an HTML form
    showing current data then, upon submission, doing the actual update

•   To support deletion, add a new URL pattern to urls.py:
        (r'^links/delete/(?P<id>d+)', 'diglic.links.views.delete')


•   Then, to display an HTML edit form in linktracker/views.py, add the following
    block of code:
        def delete(request, id):
            Link.objects.get(id=id).delete()
            return list(request, message=”Link deleted!”)

Más contenido relacionado

La actualidad más candente

Python - gui programming (tkinter)
Python - gui programming (tkinter)Python - gui programming (tkinter)
Python - gui programming (tkinter)Learnbay Datascience
 
A Basic Django Introduction
A Basic Django IntroductionA Basic Django Introduction
A Basic Django IntroductionGanga Ram
 
Asp.net server controls
Asp.net server controlsAsp.net server controls
Asp.net server controlsRaed Aldahdooh
 
Introduction to ADO.NET
Introduction to ADO.NETIntroduction to ADO.NET
Introduction to ADO.NETrchakra
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to DjangoJames Casey
 
Asp.net mvc basic introduction
Asp.net mvc basic introductionAsp.net mvc basic introduction
Asp.net mvc basic introductionBhagath Gopinath
 
Django for Beginners
Django for BeginnersDjango for Beginners
Django for BeginnersJason Davies
 
Java awt (abstract window toolkit)
Java awt (abstract window toolkit)Java awt (abstract window toolkit)
Java awt (abstract window toolkit)Elizabeth alexander
 
Introduction to ASP.NET
Introduction to ASP.NETIntroduction to ASP.NET
Introduction to ASP.NETRajkumarsoy
 
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
 JavaScript - Chapter 9 - TypeConversion and Regular Expressions  JavaScript - Chapter 9 - TypeConversion and Regular Expressions
JavaScript - Chapter 9 - TypeConversion and Regular Expressions WebStackAcademy
 
JavaScript - Chapter 12 - Document Object Model
  JavaScript - Chapter 12 - Document Object Model  JavaScript - Chapter 12 - Document Object Model
JavaScript - Chapter 12 - Document Object ModelWebStackAcademy
 
Angular - Chapter 7 - HTTP Services
Angular - Chapter 7 - HTTP ServicesAngular - Chapter 7 - HTTP Services
Angular - Chapter 7 - HTTP ServicesWebStackAcademy
 

La actualidad más candente (20)

Python - gui programming (tkinter)
Python - gui programming (tkinter)Python - gui programming (tkinter)
Python - gui programming (tkinter)
 
A Basic Django Introduction
A Basic Django IntroductionA Basic Django Introduction
A Basic Django Introduction
 
Angular js PPT
Angular js PPTAngular js PPT
Angular js PPT
 
jQuery for beginners
jQuery for beginnersjQuery for beginners
jQuery for beginners
 
Python Basics
Python BasicsPython Basics
Python Basics
 
jQuery
jQueryjQuery
jQuery
 
Css selectors
Css selectorsCss selectors
Css selectors
 
Html frames
Html framesHtml frames
Html frames
 
Html presentation
Html presentationHtml presentation
Html presentation
 
Asp.net server controls
Asp.net server controlsAsp.net server controls
Asp.net server controls
 
Javascript
JavascriptJavascript
Javascript
 
Introduction to ADO.NET
Introduction to ADO.NETIntroduction to ADO.NET
Introduction to ADO.NET
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to Django
 
Asp.net mvc basic introduction
Asp.net mvc basic introductionAsp.net mvc basic introduction
Asp.net mvc basic introduction
 
Django for Beginners
Django for BeginnersDjango for Beginners
Django for Beginners
 
Java awt (abstract window toolkit)
Java awt (abstract window toolkit)Java awt (abstract window toolkit)
Java awt (abstract window toolkit)
 
Introduction to ASP.NET
Introduction to ASP.NETIntroduction to ASP.NET
Introduction to ASP.NET
 
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
 JavaScript - Chapter 9 - TypeConversion and Regular Expressions  JavaScript - Chapter 9 - TypeConversion and Regular Expressions
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
 
JavaScript - Chapter 12 - Document Object Model
  JavaScript - Chapter 12 - Document Object Model  JavaScript - Chapter 12 - Document Object Model
JavaScript - Chapter 12 - Document Object Model
 
Angular - Chapter 7 - HTTP Services
Angular - Chapter 7 - HTTP ServicesAngular - Chapter 7 - HTTP Services
Angular - Chapter 7 - HTTP Services
 

Destacado

Not Only Drupal
Not Only DrupalNot Only Drupal
Not Only Drupalmcantelon
 
Sphinx: Leveraging Scalable Search in Drupal
Sphinx: Leveraging Scalable Search in DrupalSphinx: Leveraging Scalable Search in Drupal
Sphinx: Leveraging Scalable Search in Drupalelliando dias
 
CodeFest 2014. Егоров В. — Что за… Dart?
CodeFest 2014. Егоров В. — Что за… Dart?CodeFest 2014. Егоров В. — Что за… Dart?
CodeFest 2014. Егоров В. — Что за… Dart?CodeFest
 
개발자를 위한 Amazon Lightsail Deep-Dive - 정창훈(당근마켓)
개발자를 위한 Amazon Lightsail Deep-Dive - 정창훈(당근마켓)개발자를 위한 Amazon Lightsail Deep-Dive - 정창훈(당근마켓)
개발자를 위한 Amazon Lightsail Deep-Dive - 정창훈(당근마켓)AWSKRUG - AWS한국사용자모임
 
High Performance Web Pages - 20 new best practices
High Performance Web Pages - 20 new best practicesHigh Performance Web Pages - 20 new best practices
High Performance Web Pages - 20 new best practicesStoyan Stefanov
 
Modul pelatihan-django-dasar-possupi-v1
Modul pelatihan-django-dasar-possupi-v1Modul pelatihan-django-dasar-possupi-v1
Modul pelatihan-django-dasar-possupi-v1Ridwan Fadjar
 
MetaZeta Clusters Overview
MetaZeta Clusters OverviewMetaZeta Clusters Overview
MetaZeta Clusters OverviewPaul Baclace
 
Computational genomics approaches to precision medicine
Computational genomics approaches to precision medicineComputational genomics approaches to precision medicine
Computational genomics approaches to precision medicineAltuna Akalin
 
Computational genomics course poster 2015 (BIMSB/MDC-Berlin)
Computational genomics course poster 2015 (BIMSB/MDC-Berlin)Computational genomics course poster 2015 (BIMSB/MDC-Berlin)
Computational genomics course poster 2015 (BIMSB/MDC-Berlin)Altuna Akalin
 
Collaborative Filtering and Recommender Systems By Navisro Analytics
Collaborative Filtering and Recommender Systems By Navisro AnalyticsCollaborative Filtering and Recommender Systems By Navisro Analytics
Collaborative Filtering and Recommender Systems By Navisro AnalyticsNavisro Analytics
 
From NASA to Startups to Big Commerce
From NASA to Startups to Big CommerceFrom NASA to Startups to Big Commerce
From NASA to Startups to Big CommerceDaniel Greenfeld
 
The Physics of Fast Image Compression
The Physics of Fast Image CompressionThe Physics of Fast Image Compression
The Physics of Fast Image CompressionCloudinary
 
Apache Mesos at Twitter (Texas LinuxFest 2014)
Apache Mesos at Twitter (Texas LinuxFest 2014)Apache Mesos at Twitter (Texas LinuxFest 2014)
Apache Mesos at Twitter (Texas LinuxFest 2014)Chris Aniszczyk
 
Keynote: Apache HBase at Yahoo! Scale
Keynote: Apache HBase at Yahoo! ScaleKeynote: Apache HBase at Yahoo! Scale
Keynote: Apache HBase at Yahoo! ScaleHBaseCon
 
An Abusive Relationship with AngularJS
An Abusive Relationship with AngularJSAn Abusive Relationship with AngularJS
An Abusive Relationship with AngularJSMario Heiderich
 
Hour of Code: Best Practices for Successful Educators
Hour of Code: Best Practices for Successful EducatorsHour of Code: Best Practices for Successful Educators
Hour of Code: Best Practices for Successful EducatorsCode.org Teacher Community
 

Destacado (19)

Django
DjangoDjango
Django
 
Not Only Drupal
Not Only DrupalNot Only Drupal
Not Only Drupal
 
Sphinx: Leveraging Scalable Search in Drupal
Sphinx: Leveraging Scalable Search in DrupalSphinx: Leveraging Scalable Search in Drupal
Sphinx: Leveraging Scalable Search in Drupal
 
CodeFest 2014. Егоров В. — Что за… Dart?
CodeFest 2014. Егоров В. — Что за… Dart?CodeFest 2014. Егоров В. — Что за… Dart?
CodeFest 2014. Егоров В. — Что за… Dart?
 
개발자를 위한 Amazon Lightsail Deep-Dive - 정창훈(당근마켓)
개발자를 위한 Amazon Lightsail Deep-Dive - 정창훈(당근마켓)개발자를 위한 Amazon Lightsail Deep-Dive - 정창훈(당근마켓)
개발자를 위한 Amazon Lightsail Deep-Dive - 정창훈(당근마켓)
 
High Performance Web Pages - 20 new best practices
High Performance Web Pages - 20 new best practicesHigh Performance Web Pages - 20 new best practices
High Performance Web Pages - 20 new best practices
 
Modul pelatihan-django-dasar-possupi-v1
Modul pelatihan-django-dasar-possupi-v1Modul pelatihan-django-dasar-possupi-v1
Modul pelatihan-django-dasar-possupi-v1
 
MetaZeta Clusters Overview
MetaZeta Clusters OverviewMetaZeta Clusters Overview
MetaZeta Clusters Overview
 
Computational genomics approaches to precision medicine
Computational genomics approaches to precision medicineComputational genomics approaches to precision medicine
Computational genomics approaches to precision medicine
 
Computational genomics course poster 2015 (BIMSB/MDC-Berlin)
Computational genomics course poster 2015 (BIMSB/MDC-Berlin)Computational genomics course poster 2015 (BIMSB/MDC-Berlin)
Computational genomics course poster 2015 (BIMSB/MDC-Berlin)
 
Danger Of Free
Danger Of FreeDanger Of Free
Danger Of Free
 
Collaborative Filtering and Recommender Systems By Navisro Analytics
Collaborative Filtering and Recommender Systems By Navisro AnalyticsCollaborative Filtering and Recommender Systems By Navisro Analytics
Collaborative Filtering and Recommender Systems By Navisro Analytics
 
From NASA to Startups to Big Commerce
From NASA to Startups to Big CommerceFrom NASA to Startups to Big Commerce
From NASA to Startups to Big Commerce
 
The Physics of Fast Image Compression
The Physics of Fast Image CompressionThe Physics of Fast Image Compression
The Physics of Fast Image Compression
 
Apache Mesos at Twitter (Texas LinuxFest 2014)
Apache Mesos at Twitter (Texas LinuxFest 2014)Apache Mesos at Twitter (Texas LinuxFest 2014)
Apache Mesos at Twitter (Texas LinuxFest 2014)
 
Keynote: Apache HBase at Yahoo! Scale
Keynote: Apache HBase at Yahoo! ScaleKeynote: Apache HBase at Yahoo! Scale
Keynote: Apache HBase at Yahoo! Scale
 
An Abusive Relationship with AngularJS
An Abusive Relationship with AngularJSAn Abusive Relationship with AngularJS
An Abusive Relationship with AngularJS
 
Hour of Code: Best Practices for Successful Educators
Hour of Code: Best Practices for Successful EducatorsHour of Code: Best Practices for Successful Educators
Hour of Code: Best Practices for Successful Educators
 
Git Branching Model
Git Branching ModelGit Branching Model
Git Branching Model
 

Similar a Basic Crud In Django

Laravel 8 export data as excel file with example
Laravel 8 export data as excel file with exampleLaravel 8 export data as excel file with example
Laravel 8 export data as excel file with exampleKaty Slemon
 
The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2fishwarter
 
The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2fishwarter
 
The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2fishwarter
 
The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2fishwarter
 
Task scheduling in laravel 8 tutorial
Task scheduling in laravel 8 tutorialTask scheduling in laravel 8 tutorial
Task scheduling in laravel 8 tutorialKaty Slemon
 
Ruby on rails3 - introduction to rails
Ruby on rails3 - introduction to railsRuby on rails3 - introduction to rails
Ruby on rails3 - introduction to railsEmad Elsaid
 
TurboGears2 Pluggable Applications
TurboGears2 Pluggable ApplicationsTurboGears2 Pluggable Applications
TurboGears2 Pluggable ApplicationsAlessandro Molina
 
Python Code Camp for Professionals 1/4
Python Code Camp for Professionals 1/4Python Code Camp for Professionals 1/4
Python Code Camp for Professionals 1/4DEVCON
 
Build and deploy Python Django project
Build and deploy Python Django projectBuild and deploy Python Django project
Build and deploy Python Django projectXiaoqi Zhao
 
Working With Sharepoint 2013 Apps Development
Working With Sharepoint 2013 Apps DevelopmentWorking With Sharepoint 2013 Apps Development
Working With Sharepoint 2013 Apps DevelopmentPankaj Srivastava
 
Useful Rails Plugins
Useful Rails PluginsUseful Rails Plugins
Useful Rails Pluginsnavjeet
 
ASP.NET MVC introduction
ASP.NET MVC introductionASP.NET MVC introduction
ASP.NET MVC introductionTomi Juhola
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to DjangoJoaquim Rocha
 
Angular - Chapter 4 - Data and Event Handling
 Angular - Chapter 4 - Data and Event Handling Angular - Chapter 4 - Data and Event Handling
Angular - Chapter 4 - Data and Event HandlingWebStackAcademy
 

Similar a Basic Crud In Django (20)

Laravel 8 export data as excel file with example
Laravel 8 export data as excel file with exampleLaravel 8 export data as excel file with example
Laravel 8 export data as excel file with example
 
The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2
 
The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2
 
The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2
 
The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2
 
Django crush course
Django crush course Django crush course
Django crush course
 
Language literacy
Language literacyLanguage literacy
Language literacy
 
Lecture n
Lecture nLecture n
Lecture n
 
Task scheduling in laravel 8 tutorial
Task scheduling in laravel 8 tutorialTask scheduling in laravel 8 tutorial
Task scheduling in laravel 8 tutorial
 
Ruby on rails3 - introduction to rails
Ruby on rails3 - introduction to railsRuby on rails3 - introduction to rails
Ruby on rails3 - introduction to rails
 
TurboGears2 Pluggable Applications
TurboGears2 Pluggable ApplicationsTurboGears2 Pluggable Applications
TurboGears2 Pluggable Applications
 
Python Code Camp for Professionals 1/4
Python Code Camp for Professionals 1/4Python Code Camp for Professionals 1/4
Python Code Camp for Professionals 1/4
 
Build and deploy Python Django project
Build and deploy Python Django projectBuild and deploy Python Django project
Build and deploy Python Django project
 
Working With Sharepoint 2013 Apps Development
Working With Sharepoint 2013 Apps DevelopmentWorking With Sharepoint 2013 Apps Development
Working With Sharepoint 2013 Apps Development
 
Useful Rails Plugins
Useful Rails PluginsUseful Rails Plugins
Useful Rails Plugins
 
Nodejs.meetup
Nodejs.meetupNodejs.meetup
Nodejs.meetup
 
ASP.NET MVC introduction
ASP.NET MVC introductionASP.NET MVC introduction
ASP.NET MVC introduction
 
The Rails Way
The Rails WayThe Rails Way
The Rails Way
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to Django
 
Angular - Chapter 4 - Data and Event Handling
 Angular - Chapter 4 - Data and Event Handling Angular - Chapter 4 - Data and Event Handling
Angular - Chapter 4 - Data and Event Handling
 

Último

Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Scott Andery
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch TuesdayIvanti
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rick Flair
 
Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditSkynet Technologies
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Mark Goldstein
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Alkin Tezuysal
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...Wes McKinney
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterMydbops
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Strongerpanagenda
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demoHarshalMandlekar2
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesKari Kakkonen
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Hiroshi SHIBATA
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 

Último (20)

Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch Tuesday
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...
 
Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance Audit
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL Router
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demo
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examples
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 

Basic Crud In Django

  • 1. Basic CRUD in Django Low-Level Creation, Updating, and Deletion of Data by Mike Cantelon http://mikecantelon.com
  • 2. Setting Up a Project 1. Change to the directory in which your project should be created 2. Issue the command django-admin.py startproject linkdump 3. This command will have created a directory, with the specified project name (in this case “linkdump”), containing base files for the project 4. Change to this directory 5. Issue the command python manage.py runserver to start the development server (http://127.0.0.1:8000) 6. If your project is to use a new, rather than existing, database then create it (unless using sqlite, which be automatically created) 7. Edit settings.py to configure access to your database 8. Issue the command python manage.py syncdb to build database tables needed by the administration interface (useful later). Follow the prompts.
  • 3. Creating an Application 1. As a simple demonstration, we’ll create an application to submit links to 2. To create the application’s directory and base files, we issue the command python manage.py startapp linktracker (“linktracker” being the name of our application) 3. Next, we edit linktracker/models.py to define our model class Link (models.Model): link_description = models.CharField(maxlength=200) link_url = models.CharField(maxlength=200) 4. To add our app to the project, we edit the project’s settings.py to add our app (linkdump.linktracker) to the INSTALLED_APPS list in settings.py 5. To update the database, automatically creating the necessary tables, we issue the command python manage.py syncdb
  • 4. Activating Administration 1. Add “django.contrib.admin” to the INSTALLED_APPS list in settings.py 2. Issue the command python manage.py syncdb 3. Edit urls.py to enable admin (the next slide will talk more about this file’s functionality) 4. Issue the command python manage.py runserver 5. You can verify that admin is running by browsing http://127.0.0.1:8000/admin 6. Edit linktracker/models.py to turn on admin for links: class Link(models.Model): # ... class Admin: pass 7. Edit linktrackers/models.py to enable default (naming) column for links def __str__(self): return self.link_description
  • 5. Designing URLs • Now that we can enter data, adding a way for user to see this data would be useful • To present data we need to write a “view” which is mapped to a URL pattern • Editing urls.py allows URL patterns to be defined using regular expressions • Add the below link to your urls.py file: (r’^links/$’, ‘linkdump.linktracker.views.list’) • The above line will, if someone browses /links/ on our site, try to display the results of the list view of the links application of the linkdump project... we have not yet created a list view, however, so we just get an error!
  • 6. Enabling Templating 1. Views usually incorporate HTML templates so presentation is separated from logic 2. To enable templating, create a directory called “template” in which to store your templates then edit settings.py and add “template” to TEMPLATE_DIRS 3. Edit linktracker/views.py to create a list view for links that uses templating from linkdump.linktracker.models import Link from django.template import Context, loader from django.shortcuts import render_to_response def list(request): link_list = Link.objects.all() return render_to_response( ‘links/list.html’, {‘link_list’: link_list} )
  • 7. Creating A Template 1. We’ll create a template to crudely display link items 2. Edit template/links/list.html: {% if link_list %} <ul> {% for link in link_list %} <li><a href=’{{ link.link_url }}’> {{link.link_description}}</a></li> {% endfor %} </ul> {% else %} <p>No links found.</p> {% endif %} 3. The /links/ URL pattern now actually does something!
  • 8. Pagination (1 of 3) • Use the admin interface to add a bunch of links then reload the /links/ URL • An unlimited list is a problem so we need to add pagination • We will have to add pagination support in three places: our URL patterns (urls.py), our list view (linktracker/views.py), and our template (template/links/list.html • To add a URL pattern supporting pagination, add the below line to urls.py: (r’^links/(?P<page>d+)’, ‘linkdump.linktracker.views.list’)
  • 9. Pagination (2 of 3) • To add pagination support to linktracker/views.py, first add the following line near the start: from django.core.paginator import ObjectPaginator, InvalidPage • Next, change the list function in linktracker/views.py to the code below: def list(request, page = 0): page = int(page) link_list = ObjectPaginator(Link.objects.all(), 5) has_previous = link_list.has_previous_page(page) has_next = link_list.has_next_page(page) return render_to_response(‘links/list.html’, {‘link_list’: link_list.get_page(page), ‘has_previous’: has_previous, ‘previous_page’: page - 1, ‘has_next’: has_next, ‘next_page’: page + 1} )
  • 10. Pagination (3 of 3) • Last, but not least, you’ll want to change your template/links/ list.html HTML template to support pagination... add the following lines before the line containing “else”: {% if has_previous %} <a href=’/links/{{ previous_page }}’>Previous</a> {% if has_next %} | {% endif %} {% endif %} {% if has_next %} <a href=’/links/{{ next_page }}’>Next</a> {% endif %} • Pagination is now a wonder to behold!
  • 11. Prep for CRUD (1 of 2) • Before getting into the nitty gritty of CRUD, we need a way to give users feedback for when they create, update, or delete data • One simple way to do this is by passing a message via a GET parameter • To allow this functionality we need to modify our list view to receive messages and modify the list.html template to display messages • Change the first line of the list view in views.py, adding a parameter for messages: def list(request, page = 0, message = quot;quot;): • Also in views.py, add a line in the list view so the passed message is included in the list of parameters relayed to the list.html template: ‘message’: message,
  • 12. Prep for CRUD (2 of 2) • Now that we’re preparing to add CRUD functionality, we need to update our list HTML template as shown below: {% if message %} <b>{{ message }}</b> <p> {% endif %} {% if link_list %} <table> {% for link in link_list %} <tr bgcolor='{% cycle FFFFFF,EEEEEE as rowcolor %}'> <td><a href='{{ link.link_url }}'>{{ link.link_description }}</a></td> <td><a href='/links/edit/{{ link.id }}'>Edit</a></td> <td><a href='/links/delete/{{ link.id }}'>Delete</a></td> </tr> {% endfor %} </table> <p> {% if has_previous %} <a href='/links/{{ previous_page }}'>Previous</a> {% if has_next %}|{% endif %} {% endif %} {% if has_next %} <a href='/links/{{ next_page }}'>Next</a> {% endif %} {% else %} <p>No links found.</p> {% endif %} <p> <a href='/links/new'>Add Link</a>
  • 13. Creating Data (1 of 2) • Allowing users to submit data requires first displaying an HTML form then adding the submitted data • To start, add a URL for form display to urls.py: (r’^links/new’, ‘linkdump.linktracker.views.new’) • To deal with the submitted data, we add another URL to urls.py: (r’^links/add/’, ‘linkdump.linktracker.views.add’) • Then, to display an HTML add form in linktracker/views.py, add the following block of code: def new(request): return render_to_reponse( ‘links/form.html’, {‘action’: ‘add’, ‘button’: ‘Add’} )
  • 14. Creating Data (2 of 2) • Next, we add the form HTML template (which, as written below, can be used for adding or editing, as we’ll see later): <form action=’/links/{{ action }}/’ method=’post’> Description: <input name=link_description value=”{{ link.link_description|escape}}”><br /> URL: <input name=link_url value=’{{ link.link_url|escape }}’><br /> <input type=submit value=’{{ button }}’> </form> • Finally, we add logic to linktracker/views.py to add the submitted data then return to the list view, passing a message: def add(request): link_description = request.POST[“link_description”] link_url = request.POST[“link_url”] link = Link( link_description = link_description, link_url = link_url ) link.save() return list(request, message=”Link added!”)
  • 15. Updating Data (1 of 2) • Allowing users to upate data requires first displaying an HTML form showing current data then, upon submission, doing the actual update • To start, add a URL for form display to urls.py: (r’^links/edit/(?P<id>d+)’, ‘linkdump.linktracker.views.edit’) • Then, to display an HTML edit form in linktracker/views.py, add the following block of code: def edit(request, id): link = Link.objects.get(id=id) return render_to_reponse( ‘links/form.html’, {‘action’: ‘update/’ + id, ‘button’: ‘Update’} ) • NOTE: As the HTML form we added earlier can be used to edit, we’re re- using it in the above code
  • 16. Updating Data (2 of 2) • To deal with submitted updates, we add another URL to urls.py: (r’^links/update/(?P<id>d+)’, ‘linkdump.linktracker.views.update’) • Finally, we add logic to linktracker/views.py to add the submitted data then return to the list view, passing a message: def update(request, id): link = Link.objects.get(id=id) link.link_description = request.POST[“link_description”] link.link_url = request.POST[“link_url”] link.save() return list(request, message=”Link updated!”)
  • 17. Deleting Data • Allowing users to delete data requires first displaying an HTML form showing current data then, upon submission, doing the actual update • To support deletion, add a new URL pattern to urls.py: (r'^links/delete/(?P<id>d+)', 'diglic.links.views.delete') • Then, to display an HTML edit form in linktracker/views.py, add the following block of code: def delete(request, id): Link.objects.get(id=id).delete() return list(request, message=”Link deleted!”)