Web Development with Django - GerryZhang0925/dev_env GitHub Wiki

Table of Contents

1. Install on Linux

1.1 Create a virtual environment

Create a virtual environment with the following command.

   $ conda create -n pyhtml
   $ conda info -e
   $ source activate pyhtml
1.2 Install django

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
1.2 setting up a datebase

Install mysql-python package with conda.

   $ conda install mysql-python

2. Build a site

2.1 Create a project

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
2.2 Create an application inside the project

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.

2.3 Map URL to an application

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.

3. Create a template

3.1 Create a file to define the template

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>
3.2 Configuration for templates

Edit the file of mysite/settings.py to add following lines.

    TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates')
    TEMPLATES = [
        {...
         'DIRS': [TEMPLATE_DIR,],
        }
    ]
3.3 Define URL to use template

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'))
    ]
3.4 Define the viewer to use template

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)
3.5 Migrate pages and run the server

Execute the following commands.

     $ python manage.py migrate
     $ python manage.py runserver
    

4. Make use of static information

4.1 Create static information

Create directories for static information.

    $ mkdir static
    $ mkdir static/images
    $ mkdir static/css
4.2 Configure the path for static information

Edit the file of mysite/settings.py as following.

    STATIC_DIR = os.path.join(BASE_DIR, 'static')
    STATIC_URL = '/static/'
    STATICFILES_DIRS = [
         STATIC_DIR,
    ]
4.3 Make the template to use static information

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>

5. Create Models

5.1 Create Superuser to access model

create superuser with the following command.

    python manage.py createsuperuser
5.2 Define data model

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)
5.3 Create the models

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)
5.4 Migrate the models

Migrate models with following commands.

    $ python manage.py migrate
    $ python manage.py makemigrations myapp
    $ python manage.py migrate
5.5 Add records to defined models

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()

6. Fake test data

6.1 Install Faker

Install Faker

    $ conda install -c conda-forge faker
6.2 Create a test data generation script

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!")

7. Construct a complete website

7.1 Call model from view

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>

8. Support for REST

8.1 install the REST framework

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'
   ]
⚠️ **GitHub.com Fallback** ⚠️