Django First App
mkdir firstapps cd firstapps conda install -c anaconda virtualenv virtualenv myenv source myenv/bin/activate django-admin startproject wordcount cd wordcount python manage.py runserver python manage.py migrate python manage.py createsuperuser
python manage.py startapp wcount
wordcount/settings.py
""" Django settings for my_project project. Generated by 'django-admin startproject' using Django 2.0.2. For more information on this file, see https://docs.djangoproject.com/en/2.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.0/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'pzk&t78=1glwsae59e&q-_%_v$ytm$=g1(01w813ax@#an57zz' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'my_project.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] LOGIN_REDIRECT_URL = 'home' LOGOUT_REDIRECT_URL = 'home' WSGI_APPLICATION = 'my_project.wsgi.application' # Database # https://docs.djangoproject.com/en/2.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.0/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.0/howto/static-files/ STATIC_URL = '/static/'
wordcount/wordcount/urls.py
from django.urls import path from wcount import views urlpatterns = [ path('', views.homepage, name='home'), path('count/', views.count, name='count'), path('about/', views.about, name='about1'), ]
wcount/views.py
from django.http import HttpResponse from django.shortcuts import render import operator def homepage(request): return HttpResponse('<h1>Home Page</h1>') def about(request): return HttpResponse('<h1>About Page</h1>') def count(request): return HttpResponse('<h1>I will do the count for you.</h1>')
create wcount/templates/about.html
<h1> About us from template file.</h1>
update wcount/view.py
from django.http import HttpResponse from django.shortcuts import render import operator def homepage(request): return render(request, 'wcount/home.html') def about(request): return render(request, 'wcount/about.html') def count(request): return render(request, 'wcount/count.html')
Check if it is working
- add.css
textarea { resize: none; } .container-add{ padding-top: 15%; padding-left: 15%; } .form-label { font-size: 13px; color: #0B3B39; margin: 0; display: block; opacity: 1; -webkit-transition: .333s ease top, .333s ease opacity; transition: .333s ease top, .333s ease opacity; } .form-control { border-radius: 0; border-color: #ccc; border-width: 0 0 2px 0; border-style: none none solid none; box-shadow: none; } .form-control:focus { box-shadow: none; border-color: #0B3B39; } .js-hide-label { opacity: 0; } .js-unhighlight-label { color: #999; } .btn{ background: 0 0 #ffffff; border: 1pxsolid#9FB0A9; border-radius: 3px; color: #9FB0A9; font-family: "Raleway", sans-serif; font-size: 16px; line-height: inherit; margin: 30px0; padding: 10px50px; text-transform: uppercase; transition: all0.25sease0s; } .btn:hover,.btn:active, .btn:focus { border-color: #0b3B39; color: #0b3B39; transform: translateX(-1px); }
- admin.py
from django.contrib import admin from .models import Contact admin.site.register(Contact)
- model.py
from django.db import models class Contact(models.Model): """ For other types of fields for different purpose, please refer to: https://docs.djangoproject.com/ja/1.10/ref/models/fields/ """ name = models.CharField(max_length=200) relation = models.CharField(max_length=200) phone = models.CharField(max_length=200) email = models.CharField(max_length=200) def__str__(self): returnself.name
- forms.py
from django import forms from .models import Contact class AddForm(forms.Form): classMeta: model = Contact fields = ('name', 'relation', 'phone', 'email',)
- url.py
"""wordcount URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.conf.urls import include, url from django.contrib import admin from mycontacts import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', views.show), url(r'^add/', views.add), ]
- view.py
from django.shortcuts import render from .forms import AddForm from .models import Contact from django.http import HttpResponseRedirect from django.http import HttpResponse def show(request): """ This function gets all the members in your Database through your Model Any further usage please refer to: https://docs.djangoprojectcom/el/1.10/ref/models/querysets/ """ contact_list = Contact.objects.all() #return HttpResponse('Hello Amar') #return render(request, 'mycontacts/show.html',{' contacts': contact_list}) return render(request, 'mycontacts/show.html',{' contacts': contact_list}) def add(request): """ This function is called to add one contact member to your contact list in your Database """ if request.method == 'POST': django_form = AddForm(request.POST) if django_form.is_valid(): """ Assign data in Django Form to local variables """ new_member_name = django_form.data.get("name") new_member_relation = django_form.data.get(" relation") new_member_phone = django_form.data.get('phone') new_member_email = django_form.data.get('email') """ This is how your model connects to database and create a new member """ Contact.objects.create( name = new_member_name, relation = new_member_relation, phone = new_member_phone, email = new_member_email, ) contact_list = Contact.objects.all() return render(request, 'mycontacts/show.html',{' contacts': contact_list}) else: """ redirect to the same page if django_form goes wrong """ return render(request, 'mycontacts/add.html') else: return render(request, 'mycontacts/add.html')