Django博客搭建工作笔记 三 Admin & Database & Static Media

BabbleDay posted @ 2015年6月28日 00:42 in Web Development , 1013 阅读
  • Django中自带Admin

Run the server and visit http://127.0.0.1:8000/admin/

如果发生TemplateDoesNotExist at /admin/login/错误

check settings.py: in TEMPLATES, whether the “APP_DIR” is true. Since the template of admin is under its app directory
 
revise blog/admin.py
from django.contrib import admin
from blog.models import Category, Article

# Register your models here.

admin.site.register(Category)
admin.site.register(Article)
 

	

you can check out the official Django documentation on the admin interface for more information if you’re interested.

  • Database

 

Basic Workflows

Now that we’ve covered the core principles of dealing with Django’s models functionality, now is a good time to summarise the processes involved in setting everything up. We’ve split the core tasks into separate sections for you.

1. Setting up your Database

With a new Django project, you should first tell Django about the database you intend to use (i.e. configure DATABASES in settings.py). You can also register any models in the admin.py file to make them accessible via the admin interface.

2. Adding a Model

The workflow for adding models can be broken down into five steps.

  1. First, create your new model(s) in your Django application’s models.py file.
  2. Update admin.py to include and register your new model(s).
  3. Then perform the migration $ python manage.py makemigrations
  4. Apply the changes $ python manage.py migrate. This will create the necessary infrastructure within the database for your new model(s).
  5. Create/Edit your population script for your new model(s).

Invariably there will be times when you will have to delete your database. In which case you will have to run the migrate command, then createsuperuser command, followed by the sqlmigrate commands for each app, then you can populate the database.

Undertake the part two of official Django tutorial if you have not done so. 

 

 


		

		

在PersonalWebsite/settings.py里声明你的数据库

DATABASES = {

    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

挪到服务器上的话最好用MySQL之类 https://docs.djangoproject.com/en/1.7/ref/settings/#std:setting-DATABASE-ENGINE

 


		

 

To create a population script for Rango’s database, we start by creating a new Python module within our Django project’s root directory (e.g. <workspace>/tango_with_django_project/). Create the populate_rango.py file and add the following code.

import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tango_with_django_project.settings')

import django
django.setup()

from rango.models import Category, Page


def populate():
    python_cat = add_cat('Python')

    add_page(cat=python_cat,
        title="Official Python Tutorial",
        url="http://docs.python.org/2/tutorial/")

    add_page(cat=python_cat,
        title="How to Think like a Computer Scientist",
        url="http://www.greenteapress.com/thinkpython/")

    add_page(cat=python_cat,
        title="Learn Python in 10 Minutes",
        url="http://www.korokithakis.net/tutorials/python/")

    django_cat = add_cat("Django")

    add_page(cat=django_cat,
        title="Official Django Tutorial",
        url="https://docs.djangoproject.com/en/1.5/intro/tutorial01/")

    add_page(cat=django_cat,
        title="Django Rocks",
        url="http://www.djangorocks.com/")

    add_page(cat=django_cat,
        title="How to Tango with Django",
        url="http://www.tangowithdjango.com/")

    frame_cat = add_cat("Other Frameworks")

    add_page(cat=frame_cat,
        title="Bottle",
        url="http://bottlepy.org/docs/dev/")

    add_page(cat=frame_cat,
        title="Flask",
        url="http://flask.pocoo.org")

    # Print out what we have added to the user.
    for c in Category.objects.all():
        for p in Page.objects.filter(category=c):
            print "- {0} - {1}".format(str(c), str(p))

def add_page(cat, title, url, views=0):
    p = Page.objects.get_or_create(category=cat, title=title)[0]
        p.url=url
        p.views=views
        p.save()
    return p

def add_cat(name):
    c = Category.objects.get_or_create(name=name)[0]
    return c

# Start execution here!
if __name__ == '__main__':
    print "Starting Rango population script..."
    populate()
 


 

  • 
    		
    Static Media
    
    			

     

    在PersonalWebsite, blog, templates平行下建立static/images,并放入一张图片cat.png

    编辑settings.py

    STATIC_PATH = os.path.join(BASE_DIR,'static')
    
    STATIC_URL = '/static/'
    
    STATICFILES_DIRS = (
        STATIC_PATH,
    )
    

    在index.html中: html外写{% load staticfiles %}, body里加入<img src="{% static "images/cat.png" %}" alt="Picture of Cat" />

    we need to inform Django’s template system that we will be using static media with the {% loadstatic %} tag. This allows us to call the static template tag as done in {% static "rango.jpg" %}. As you can see, Django template tags are denoted by curly brackets { }. In this example, the static tag will combine the STATIC_URL with "rango.jpg" so that the rendered HTML looks like the following

    如何调用javascript和css

    <!DOCTYPE html>
    
    {% load static %}
    
    <html>
    
        <head>
            <title>Rango</title>
            <link rel="stylesheet" href="{% static "css/base.css" %}" /> <!-- CSS -->
            <script src="{% static "js/jquery.js" %}"></script> <!-- JavaScript -->
        </head>
    
        <body>
            <h1>Including Static Media</h1>
            <img src="{% static "images/rango.jpg" %}" alt="Picture of Rango" /> <!-- Images -->
        </body>
    
    </html>

    如果要放在服务器上,请参考

Deploying static files

https://docs.djangoproject.com/en/1.7/howto/static-files/deployment/
 

 


	

关于Deploy #TODO(leifos): the DEBUG variable in settings.py, lets you control the output when an error occurs, and is used for debugging. When the application is deployed it is not secure to leave DEBUG equal to True. When you set DEBUG to be False, then you will need to set the ALLOWED_HOSTS variable in settings.py, when running on your local machine this would be 127.0.0.1. You will also need to update the project urls.py file:

 

上传Media 与static, templates并列建立文件夹media; 在PersonalWebsite/urls.py里加入

# At the top of your urls.py file, add the following line:
from django.conf import settings

# UNDERNEATH your urlpatterns definition, add the following two lines:
if settings.DEBUG:
    urlpatterns += patterns(
        'django.views.static',
        (r'^media/(?P<path>.*)',
        'serve',
        {'document_root': settings.MEDIA_ROOT}), )

The settings module from django.conf allows us access to the variables defined within our project’s settings.py file. The conditional statement then checks if the Django project is being run in DEBUGmode. If the project’s DEBUG setting is set to True, then an additional URL matching pattern is appended to the urlpatterns tuple. The pattern states that for any file requested with a URL starting with media/, the request will be passed to the django.views.static view. This view handles the dispatching of uploaded media files for you.

 

编辑PersonalWebsite/settings.py 加入

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media') # Absolute path to the media directory

Summary

Creating a template and integrating it within a Django view is a key concept for you to understand. It takes several steps, but becomes second nature to you after a few attempts.

The steps involved for getting a static media file onto one of your pages is another important process you should be familiar with. Check out the steps below on how to do this.

First, create the template you wish to use and save it within the templates directory you specified in your project’s settings.py file. You may wish to use Django template variables (e.g. {{variable_name }}) within your template. You’ll be able to replace these with whatever you like within the corresponding view.

Find or create a new view within an application’s views.py file.

Add your view-specific logic (if you have any) to the view. For example, this may involve extracting data from a database.

Within the view, construct a dictionary object which you can pass to the template engine as part of the template’s context.

Make use of the  render() helper function to generate the rendered response. Ensure you reference the request, then the template file, followed by the context dictionary!

If you haven’t already done so, map the view to a URL by modifying your project’s urls.py file - and the application-specific urls.py file if you have one.

Take the static media file you wish to use and place it within your project’s static directory. This is the directory you specify in your project’s STATICFILES_DIRS tuple within settings.py.

Add a reference to the static media file to a template. For example, an image would be inserted into an HTML page through the use of the <img /> tag.

Remember to use the {% load staticfiles %} and {% static "filename" %} commands within the template to access the static files.

 

Avatar_small
divedk 说:
2018年6月18日 23:35

The new programmer has been stepping in the market. The use of the concept and online assignment writing service has been identified for the use of the forms for the humans. The nature of the problem is divided for the use of the strong hold for the humans in life.

Avatar_small
Cucumber Juice 说:
2018年7月24日 07:17

I’m excited to uncover this page. I need to to thank you for ones time for this particularly fantastic read!! I definitely really liked every part of it and i also have you saved to fav to look at new information in your site. <a href="https://www.naturalfoodseries.com/10-benefits-cucumber-juice">Cucumber Juice</a>

Avatar_small
psn code generator 说:
2018年8月16日 07:22

Best place to use the free psn free codes on our site and do enjoy.

Avatar_small
basketball games 说:
2018年10月11日 20:11

Love is singing for the pain is beautiful, no day no month pen name ...

Avatar_small
best latex mattress 说:
2019年4月04日 12:37

The primary concern is, they can put a more expensive rate and influence a superior benefit on the off chance that they to overlook the oil based, engineered SBR content... or on the other hand simply imagine that it doesn't exist! best latex mattress

Avatar_small
0x80004005 outlook 说:
2019年5月22日 01:56

Thanks for the essential information.

Avatar_small
gamatron 说:
2019年6月17日 00:42

While these things may at present exist, they are not the influx of things to come. 

www.chennel-tv.com <a href="http://www.chennel-tv.com">live channels</a>

 

Avatar_small
charli 说:
2022年1月27日 02:38



 

idrive support  , amazon prime customer service number , tech support number  , contact instagramcisco support , aol customer service , norton support , mcafee support ,  epson printer support  , hp support , apple icloud support  , hewlett packard customer service ,  carbonite phone number , lexmark support  , www tomtom com support  ,  asus customer service  , pogo support , arlo support ,  webroot customer service,

 technical support numbercontact support phone numbertechnical support phone number

contact apple support icloudapple icloud support email addressapple icloud support phone number ukapple phone number for icloud support,

Google Hangouts customer service numberhangouts supporthangouts web chathangouts online chat,

idrive contactidrive phone numberidrive customer support,

google drive contact numbergoogle drive help numbergoogle drive customer support phone numbercall google drive,

amazon prime customer support phone numberamazon prime customer numberamazon prime support phone numberamazon prime customer phone number,

pogo phone numberpogo customer service phone numberpogo technical support phone numberpogo customer service,

trend micro downloadtrend micro for macuninstall trend microtrend micro account login,

 

 

Travel PPC calls ,

Travel Calls Campaign ,

PPC for travel ,

PPC for travel industry ,

travel ppc campaign ,

travel ppc ,

best travel campaigns ,

travel marketing campaigns ,

ppc travel ,

travel ppc agency ,

travel campaign ,

Travel calls ,

 

 

Avatar_small
charli 说:
2022年1月27日 02:42

 

dietitian in delhi , best dietitian in delhi , top dietician in india , top dietician in delhi

best foods to gain weight ,   gain weight fast ,   increase weight ,   best diet for weight gain ,   muscle gain diet plan

types of therapeutic diet ,   therapeutic diet ,   therapeutic nutrition ,  

 how to lose weight after c section delivery ,   post delivery weight loss ,   weight loss after c section delivery ,                                                                                                                                                                  

 


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter