summaryrefslogtreecommitdiff
path: root/tutorial_7_django_forms/slides.md
blob: 977eb07b1e25114309a5419953e1f1a30ef9b057 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
Slide 1
------------
Title Slide
**Creating Forms in Django**

Slide 2
--------------

**Learning Objectives**

In this tutorial, we will learn to;
  - Create a Django form
  - Create a views to handle form submission

Slide 3
---------------

**System Requirements**
  - Ubuntu 16.10
  - Python 3.5 or higher version
  - python3.4-venv

Slide 4:
----------------

**What is a Form?**

- In HTML, a form is a collection of elements inside <form>...</form>
- Allow user to do things like;
    - enter text
    - select options
    - manipulate objects or controls, and so on,
- Send data to the server

Slide 5
----------------

**Django Forms**

- Django provides inbuilt libraries to help you build forms easily


Demonstration
----------------
** Creating form using html to add blog**

 - templates/add_blog.html

        <form action="" method="POST">
            {% csrf_token %}
            <label for="name">Blog name: </label>
            <input id="name" type="text" name="name">
            <input type="submit" value="Add Blog">
        </form>

 -  views.py to add blog

        def add_blog(request):
            if request.method == 'POST':
                name = request.POST.get('name')
                Blog.objects.create(name=name)
                return HttpResponse("Blog created")
            return render(request, 'add_blog.html')

 - blog/urls.py

        path('blog/add/', views.add_blog, name='add_blog'),

Demonstration
----------------

**Creating a Django Form**

 - Create a file forms.py in the ```blog``` and add the code

        from django import forms

        class BlogForm(forms.Form):
            name = forms.CharField(label='name', max_length=100)

 - views.py

        from blog.forms import BlogForm

        def add_blog(request):
            if request.method == 'POST':
                form = BlogForm(request.POST)
                if form.is_valid():
                    name = form.cleaned_data.get('name')
                    Blog.objects.create(name=name)
                    return HttpResponse("Blog created")
            context = {'form': BlogForm()}
            return render(request, 'add_blog.html', context)

 - templates/add_blog.html

        <form action="" method="POST">
            {% csrf_token %}
            {{ form }}
            <input type="submit" value="Add Blog">
        </form>

Demonstration
----------------

**Creating a Django Form from models **

- Create a file forms.py in the ```blog``` and add the code

      from blog.models import Blog, Article

      class BlogForm(forms.ModelForm):
          class Meta:
              model = Blog
              fields = ['name']
        
      class ArticleForm(forms.ModelForm):
          class Meta:
              model = Article
              fields = ['title', 'body', 'draft']

(For script creator: given article form and view as well, as an additional content, can be used if required.)

 - views.py

        from blog.forms import BlogForm

        def add_blog(request):
            if request.method == 'POST':
                form = BlogForm(request.POST)
                if form.is_valid():
                    form.save() 
                    return HttpResponse("Blog created")
            context = {'form': BlogForm()}
            return render(request, 'add_blog.html', context)

Demonstration
----------------

**Edit view **

- Let's edit an existing blog
- To do this add the following code to the ```views.py``` in the ```blog```directory

      from django.http import HttpResponse, HttpResponseNotFound
      from .forms import BlogForm, ArticleForm

      def add_blog(request, blog_id=None):
      """
      This view adds a new or edits an existing blog
      """
          if blog_id:
              blog = Blog.objects.get(id=blog_id)
          else:
              blog = Blog()
          if request.method == 'POST':
              form = BlogForm(request.POST, instance=blog)
              if form.is_valid():
                  form.save()
                  return HttpResponse("Blog created")
          blog_form = BlogForm(instance=blog)
          context = {'form': blog_form, 'blog': blog}
          return render(request, 'add_blog.html', context)
                  
**Template for the view**

- In ```add_blog.html``` add following

        <html>
        <body>
        {% if form %}
            <form action="/blogs/add_blog/{{ blog.id }}" method="post">
                {% csrf_token %}
                    {{ form }}
                <input type="submit" value="Submit" />
            </form>
        {% endif %}
        </body>
        </html>

Modify the urls located in the blogs folder

    # /blogs/urls.py
        path('blog/add/<int:blog_id>/', views.add_blog, name='add_blog'),

Slide 10:
-----------------

**Edit Templates to add new URL redirect**

- Edit the ```blogs.html``` as follows;

   # /blog/templates/blog/blogs.html
    
    <html>
    <body>
    <h2><a href='/blog/add_blogs/'>Add New Blog</a></h2>
    {% if blogs %}
         .
         .
        <ul>
        {% for blog in blogs %}
            <li>{{ blog.name}} <a href='/blog/add_blogs/{{ blog.id }}'>[Edit]</a></li>
        {% endfor %}
         .
         .
        </ul>
    {% else %}
        <p>No Blogs are available.</p>
    {% endif %}
    </body>
    </html>

 *** With this we come to the end of the tutorial***
 ----------------------------------------------------
 *** Add concluding slides and assignment***


(For script creator)
-------------------
**After every edit in the code the demonstration can be shown by visting the url**

For demonstration:

- Activate the virtual environment
- Run the Django test server using the command python manage.py runserver
- Open the web browser and go to http://127.0.0.1:8000/blogs/add_blog/
- For edit http://127.0.0.1:8000/blogs/add_blog/1/

- Submit form
- In django admin interface we can show the new object created