Web Development with Django - GerryZhang0925/dev_env GitHub Wiki
Create a virtual environment with the following command.
$ conda create -n pyhtml $ conda info -e $ source activate pyhtml
Install the django package with conda.
$ conda install django $ sudo ln -s ~/anaconda3/pkgs/django-1.11.3-py36_0/bin/django-admin.py /usr/local/bin/django-admin.py
Install mysql-python package with conda.
$ conda install mysql-python
Run the following command to create a mysite directory in the current directory, then access http://127.0.0.1:8000/
$ sudo ln -s ~/anaconda3/pkgs/-1.11.10-py27hd476221_0/bin/django-admin.py /usr/local/bin/django-admin.py $ django-admin.py startproject mysite $ cd mysite $ ls manage.py mysite $ python manage.py runserver
Go into the directory of project and run the following command to create an application inside the project.
$ python manage.py startapp myapp
and edit the file of myapp/views.py as following.
from django.shortcuts import render from django.http import HttpResponse
def index(request): return HttpResponse("<em>My First Project</em>")
edit the file of mysite/setting.py as following to include myapp as an application.
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myapp'
] edit the file of mysite/urls.py as following.
from django.conf.urls import url from django.contrib import admin from myapp import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^admin/', admin.site.urls), ]
Finally, start the server and open url of http://localhost:8000, we can find the application we defined.
Edit the file of mysite/urls.py to add following code to add supports of include.
from django.conf.urls import include urlpattens = [ url(r'^myapp/', include('myapp.urls')), ]
Add a file named myapp/urls.py as following.
from django.conf.urls import url from myapp import views urlpatterns = [ url(r'^$', views.index, name='index'), ]
Finally, start the server and open url of http://localhost:8000/myapp/, we can find the application we defined.
Create a directory for templates with following command.
$ cd ~mysite $ mkdir templates $ mkdir templates/myapp
Create a file of templates/myapp/help.html as following.
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>HELP PAGE</title> </head> <body> {{ help_insert }} </body> </html>
Edit the file of mysite/settings.py to add following lines.
TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates') TEMPLATES = [ {... 'DIRS': [TEMPLATE_DIR,], } ]
Edit the file of myapp/urls.py to add following lines.
from django.conf.urls import url from myapp import views urlpatterns = [ url(r'^$', views.help, name='help'), ]
Edit the file of mysite/urls.py as following
from django.conf.urls import include urlpatterns = [ url(r'^help/', include('mypp.urls')) ]
Edit the file of myapp/views.py to add following code.
def help(request): helpdict = {'help_insert':'HELP PAGE'} return render(request, 'first_app/help.html', context=helpdict)
Execute the following commands.
$ python manage.py migrate $ python manage.py runserver
Create directories for static information.
$ mkdir static $ mkdir static/images $ mkdir static/css
Edit the file of mysite/settings.py as following.
STATIC_DIR = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' STATICFILES_DIRS = [ STATIC_DIR, ]
Edit the file of myapp/help.html as following.
<!DOCTYPE html> {% load staticfiles %} <html> <head> <meta charset="utf-8"> <title>HELP PAGE</title> <link rel="stylesheet" href={% static "css/mystyle.css" %}"/> </head> <body> {{ help_insert }} <h1>Hi, this is a picture of Django himself!</h1> <img src="{% static "image/djangoguiter.jpg" %}" alt="Uh oh, didn't show!"> </body> </html>
create superuser with the following command.
python manage.py createsuperuser
Edit myapp/models.py to contain three models.
from django.db import models class Topic(models.Model): top_name = models.CharField(max_length=264,unique=True) def __str__(self): return self.top_name class Webpage(models.Model): topic = models.ForeignKey(Topic) name = models.CharField(max_length=264,unique=True) url = models.URLField(unique=True) def __str__(self): return self.name class AccessRecord(models.Model): name = models.ForeignKey(Webpage) date = models.DateField() def __str__(self): return str(self.date)
Edit the file myapp/models.py as following
from django.contrib import admin from first_app.models import AccessRecord,Topic,Webpage # Register your models here. admin.site.register(AccessRecord) admin.site.register(Topic) admin.site.register(Webpage)
Migrate models with following commands.
$ python manage.py migrate $ python manage.py makemigrations myapp $ python manage.py migrate
Add records with following commands.
$ python manage.py shell $ from myapp.models import Topic $ print(Topic.objects.all()) <QuerySet []> $ t = Topic(top_name="Social Network") $ t.save() $ print(Topic.objects.all()) <QuerySet [<Topic: Social Network>]> $ quit()
Install Faker
$ conda install -c conda-forge faker
Create a script which uses faker and run it.
import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'first_project.settings') import django django.setup() import random from first_app.models import AccessRecord, Webpage, Topic from faker import Faker fakegen = Faker() topics = ['Search', 'Social', 'Marketplace', 'News', 'Games'] def add_topic(): t = Topic.objects.get_or_create(top_name=random.choice(topics))[0] t.save() return t def populate(N=5): for entry in range(N): # get the topic for the entry top = add_topic() # Create the fake data for that entry fake_url = fakegen.url() fake_date = fakegen.date() fake_name = fakegen.company() # Create the new webpage entry webpg = Webpage.objects.get_or_create(topic=top, url=fake_url, name=fake_name)[0] # Create a fake access record for that webpage acc_rec = AccessRecord.objects.get_or_create(name=webpg, data=fake_date)[0] if __name__ == '__main__': print("populating script!") populate(20) print("populating complete!")
Edit the file of myapp/views.py
from django.shortcuts import render from django.http import HttpResponse from first_app.models import Topic,Webpage,AccessRecord def index(request): webpages_list = AccessRecord.objects.order_by('date') date_dict = {'access_records':webpages_list} return render(request, 'first_app/index.html', context=date_dict)
and the file template/myapp/index.html
<!DOCTYPE html> {% load staticfiles %} <html> <head> <meta charset="utf-8"> <title>Django Level Two</title> <link rel="stylesheet" href="{% static "css/mystyle.css"}"/> </head> <body> <h1>Hi welcome to Django Level two!</h1> <h2>Here are your access records:</h2> <div class="djangtwo"> {% if access_records %} <table>
<thread> <th>Site Name</th> <th>Data Accessed</th> </thread>
{% for acc in access_records %} <tr> <td>{{ acc.name }}</td> <td>{{ acc.date }}</td> </tr> {% endfor %} </table> {% else %} <p>NO ACCESS RECORDS FOUND!</p> {% endif %} </div> </body> </html>
Install the framework with following command.
conda upgrade -c anaconda django conda install -c conda-forge djangorestframework
and edit the file of settings.py to add a installed application of rest_framework as following.
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myApp', 'rest_framwork' ]