Saturday, June 29, 2019

Start with Django on Windows

1. Install Python:
Download and install from here: https://www.python.org/downloads/
Check python is install by running following command in a CMD.
python -V
should display something like:
Python 3.7.3

2. Create virtual environment.
Create a new folder for your project:
mkdir myproject
Go to the newly created folder:
cd myproject
Run following command (the . at the end means you want to use current directory for virtualenv installation, so don't foget about it):
virtualenv .
Check virtualenv was installed by running the following command:
dir
You should see something like this:








3. Activate virtual environment
Scripts\activate
You will see the name of your virtual environment (myproject) in our case in front of every line in the terminal.
To deactivate you can simply run:
Scripts\deactivate

4. Install Django in this isolated virtual environment:
Make sure the virtual environment is activated and run:
pip install django

5. Check django was installed in your virtual environment:
pip freeze
you should see something like this:





If you see more things installed it means your virtual environment was not activated before installing django, and you have installed it locally on your PC not on the virtual environment.

6. Create new project.
Create a scr folder and move inside it:
mkdir src
cd src

run the following command to start the project (again . means current directory):
django-admin startproject trydjango .

run dir command to see what happened, you should see a folder structure like this:







run following command to run your server:
python manage.py runserver

you should see something like this:


7. Open it in your browser: http://localhost:8000/


















8. Connect a db:
python manage.py migrate

9. Create superuser:
python manage.py createsuperuser
Connect to http://localhost:8000/admin with your new user and password.

10. Split your app into components. Create first component:
python manage.py startapp products

11. Create Products model:

from django.db import models

# Create your models here.
class Product(models.Model):
title = models.TextField()
description = models.TextField()
price = models.TextField()

12. Update db. This is done everytime you change something:
python manage.py makemigrations
python manage.py migrate

If you go to http://localhost:8000/admin you will see a new sction Products.

13. Work with python shell:
python manage.py shell

14. Meaning of blank and null:
models.TextField(blank=True, null=True)
'blank=False' means field is required while 'blank=True' means field is not required
'null=True' means the field can be empty/null in the database while 'null=False' means the field cannot be empty/null in the database.

15. Create a view:
in views.py
def home_view(*args, **kwargs):
return HttpResponse("<h1>Hello world!</h1>")

in urls.py
from pages.views import home_view

urlpatterns = [
path('admin/', admin.site.urls),
path('', home_view, name='home'),
]

16. Create templates:
Create a folder templates and inside it a home.html with some html, then change views.py like this:

def home_view(request, *args, **kwargs):
return render(request, "home.html", {})

17. Inheritance.
Create base.html
<!DOCTYPE html>
<html>
<head>
<title>TryDjango</title>
</head>
<body>
<h1>Nav bar</h1>
{% block content %}
replace me
{% endblock %}
</body>
</html>

make it appear in all pages. home.html example:
{% extends 'base.html' %}

{% block content %}
<h1> Hello world!</h1>
{{ request.user }}
{{ request.user.is_authenticated }}
{% endblock %}

18. Include something on every page:
{% include 'navbar.html' %}

19. Adding and working with context:
in views.py
def about_view(request, *args, **kwargs):
my_context = {
"my_text": "This is about me",
"this_is_true": True,
"my_number": 123,
"my_list": [123, 456, 789, "abc"]
}
return render(request, "about.html", my_context)

in about.html
<ul>
{% for my_sub_item in my_list %}
{% if my_sub_item == 456 %}
<li>{{ forloop.counter }} - {{ my_sub_item|add:22 }}</li>
{% elif my_sub_item == "abc" %}
<li>This is not ok</li>
{% else %}
<li>{{ forloop.counter }} - {{ my_sub_item }}</li>
{% endif %}
<li>{{ forloop.counter }} - {{ my_sub_item }}</li>
{% endfor %}
</ul>

20. Working with forms:
create forms.py
from django import forms

from .models import Product

class ProductForm(forms.ModelForm):
class Meta:
model = Product
fields = [
'title',
'description',
'price'
]

in products/views.py
def product_create_view(request):
form = ProductForm(request.POST or None)
if form.is_valid():
form.save()
form.ProductForm()
context = {
'form': form
}
return render(request, "products/product_create.html", context)

in products/templates/products/product_create.html
{% extends 'base.html' %}

{% block content %}
<form method='POST'> {% csrf_token %}
{{ form.as_p }}
<input type='submit' value='Save' />
</form>
{% endblock %}

21. Class based views:
blog/views.py
from django.shortcuts import render, get_object_or_404

from django.views.generic import (
CreateView,
DetailView,
ListView,
UpdateView,
DeleteView
)

from .models import Article

# Create your views here.

class ArticleListView(ListView):
template_name = 'articles/article_list.html'
queryset = Article.objects.all() # <blog>/<modelname>_list.html

class ArticleDetailView(DetailView):
template_name = 'articles/article_detail.html'
# queryset = Article.objects.all()

def get_object(self):
id_ = self.kwargs.get("id")
return get_object_or_404(Article, id=id_)

Reference: https://www.youtube.com/watch?v=F5mRW0jo-U4

No comments:

Post a Comment