Creating Your First Application in Django
First of all I created a new project from terminal which is the main one and called "main" Open a new terminal, then a new project. I will name mine "movies".
python manage.py startapp movies
Now, we need to register this app in the settings module. Go to "settings.py" and type the name of your app like this:
PS: We can delete the "'django.contrib.sessions'," since we don't use it anymore.
Writing Views
We should first know about HTTP. The Hypertext Transfer Protocol (HTTP) is an application protocol for distributed, collaborative hypermedia information systems that allows users to transmit data over the Internet.
We should go to movies->view.py. It is "movies" in my case but you can totally change the name. We create our views here.
from django.shortcuts import render
from django.http import HttpResponse
def say_hello(request):
return HttpResponse('Hello World')
Now, we need to map this view to a url.
Mapping URLs to Views
Click on the "movies" app and create a new file which you should name "urls.py". And type this code:
from django.urls import path
from . import views
urlpatterns = [
path('hello/', views.say_hello)
]
Next, you should go to "main" project, then to url.py in thereand type:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('movies/', include('movies.urls'))
]
After this, go to your browser and type "127.0.0.1:8000/movies/hello" It should look like this on your browser:
Using Templates
Let' see how can we use a template to return html content to the client. I am adding a new folder to "movies" app which should be named "templates". From there, open a another project called "hello.html".
Let's type this for once:
<h1> Hello World </h1>
Now, we should go back to url.py file of "movies" app and type our new code:
from django.urls import path
from . import views
urlpatterns = [
path('hello/', views.say_hello)
]
We should be able to see this changes in server.
We can also add "dictionary" and "if/else" functions. hello.html
{% if name %}
<h1>Hello {{name}}</h1>
{% else %}
<h1>Hello World </h1>
{% endif %}
from django.shortcuts import render
from django.http import HttpResponse
def say_hello(request):
return render(request, 'hello.html', {'name': 'İlke'})