搭建Django項(xiàng)目的操作步驟-創(chuàng)新互聯(lián)

創(chuàng)新互聯(lián)www.cdcxhl.cn八線(xiàn)動(dòng)態(tài)BGP香港云服務(wù)器提供商,新人活動(dòng)買(mǎi)多久送多久,劃算不套路!

創(chuàng)新互聯(lián)建站自2013年創(chuàng)立以來(lái),先為英山等服務(wù)建站,英山等地企業(yè),進(jìn)行企業(yè)商務(wù)咨詢(xún)服務(wù)。為英山企業(yè)網(wǎng)站制作PC+手機(jī)+微官網(wǎng)三網(wǎng)同步一站式服務(wù)解決您的所有建站問(wèn)題。

這篇文章主要介紹搭建Django項(xiàng)目的操作步驟,文中介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們一定要看完!

一、創(chuàng)建一個(gè)Django項(xiàng)目

1、使用虛擬環(huán)境

#快速創(chuàng)建虛擬環(huán)境
python -m venv prjvenv
#激活虛擬環(huán)境
source prjvenv/bin/activate

2、創(chuàng)建項(xiàng)目

#安裝django
pip install django
#創(chuàng)建項(xiàng)目
django-admin startproject myblog

3、django設(shè)置

myblog/settings.py文件

TIME_ZONE='Asia/Shanghai'

4、數(shù)據(jù)庫(kù)遷移

python manage.py migrate

5、啟動(dòng)

python manage.py runserver

二、視圖和URL配置

myblog/views.py文件

from django.http import HttpResponse
#最簡(jiǎn)單視圖
def hello(request):
    return HttpResponse("Hello world")
#帶參數(shù)的視圖
def hours_ahead(request, offset):
       try:
           offset = int(offset)
       except ValueError:
           raise Http404()
       dt = datetime.datetime.now() + datetime.timedelta(hours=offset)
       html = "In %s hour(s), it will be  %s." % (offset, dt)
       return HttpResponse(html)

myblog/urls.py 文件

from django.conf.urls import url
from django.contrib import admin
from myblog.views import hello
from mysite.views import hours_ahead
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^hello/$',hello),
    url(r'^time/plus/(\d{1,2})/$', hours_ahead),
 ]

三、使用Django模板

1、模板目錄配置

myblog/settings.py文件

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': ['app1/templates','app2/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',
            ],
        },
    },
]
如果想在項(xiàng)目根目錄中放一些主模板(例如在 mysite/templates 目錄中),需要像這樣設(shè)定 DIRS:
'DIRS': [os.path.join(BASE_DIR, 'templates')],

2、視圖函數(shù)

from django.shortcuts import render
import datetime
def current_datetime(request):
    now = datetime.datetime.now()
    return render(request, 'current_datetime.html', {'current_date': now})

3、模板文件

myblog/templates/base.html文件

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
<head>
    <title>{% block title %}{% endblock %}</title>
</head>
<body>
    <h2>My helpful timestamp site</h2>
    {% block content %}{% endblock %}
    {% block footer %}<hr>
    <p>Thanks for visiting my site.</p>
    {% endblock %}
</body>
</html>

四、模型

1、配置數(shù)據(jù)庫(kù)

myblog/setting.py

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

2、創(chuàng)建應(yīng)用

python manage.py startapp books

3、激活應(yīng)用

 INSTALLED_APPS = (
        ...
        'books',
)

4、創(chuàng)建模型

myblogs/books/models.py

from django.db import models
class Publisher(models.Model):
    name = models.CharField(max_length=30)
    address = models.CharField(max_length=50)
    city = models.CharField(max_length=60)
    state_province = models.CharField(max_length=30)
    country = models.CharField(max_length=50)
    website = models.URLField()
    def __str__(self):
        return self.name
class Author(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=40)
    email = models.EmailField()
    def __str__(self):
        return self.last_name
class Book(models.Model):
    title = models.CharField(max_length=100)
    authors = models.ManyToManyField(Author)
    publisher = models.ForeignKey(Publisher,on_delete=models.CASCADE)
    publication_date = models.DateField()
    def __str__(self):
        return self.title

5、遷移數(shù)據(jù)庫(kù)

#括號(hào)中的內(nèi)容可以不需要
python manage.py makemigrations (books)
python manage.py migrate

6、操作數(shù)據(jù)

新增數(shù)據(jù)

方式一:
p1 = Publisher(...)
p1.save()
方式二:
p1 = Publisher.objects.create(...)

更新數(shù)據(jù)

方式一:
p.name = 'Apress Publishing'
p.save()
方式二:
Publisher.objects.filter(id=52).update(name='Apress')   #推薦

查詢(xún)數(shù)據(jù)

返回查詢(xún)集合

Publisher.objects.all()
Publisher.objects.filter(name='Apress')    #WHERE name = 'Apress';
Publisher.objects.filter(name__contains="press")     #WHERE name LIKE '%press%';

返回單個(gè)對(duì)象

Publisher.objects.get(name="Apress")   #不是1個(gè)對(duì)象就會(huì)報(bào)異常
try:
    p = Publisher.objects.get(name='Apress')  #數(shù)據(jù)庫(kù)中存在一個(gè)數(shù)據(jù)
except Publisher.DoesNotExist:
    print ("Apress isn't in the database yet.")   #數(shù)據(jù)庫(kù)中沒(méi)有數(shù)據(jù)
else:
    print ("Apress is in the database.")    #有多個(gè)數(shù)據(jù)

刪除

方式一:?jiǎn)蝹€(gè)刪除
p = Publisher.objects.get(name="O'Reilly")
p.delete()
方式二:批量刪除
Publisher.objects.filter(country='USA').delete()
Publisher.objects.all().delete()

排序

方式一:使用order_by()
Publisher.objects.order_by("name", "age")   #根據(jù)姓名和年齡排序,-name/-age實(shí)現(xiàn)反向排序
方式二:在模型內(nèi)定義
class Publisher(models.Model):
    ...
    class Meta:
        ordering = ['name']

切片

Publisher.objects.order_by('name')[0:2]

五、后臺(tái)管理

1、創(chuàng)建管理員用戶(hù)

python manage.py createsuperuser

2、將模型添加到后臺(tái)管理

myblog/books/admin.py文件

from django.contrib import admin
from .models import Publisher, Author, Book
admin.site.register(Publisher)
admin.site.register(Author)
admin.site.register(Book)

3、修改模型,使字段在后臺(tái)輸入時(shí)變?yōu)榭蛇x項(xiàng)

myblog/books/models.py

class Book(models.Model):
    title = models.CharField(max_length=100)
    authors = models.ManyToManyField(Author)
    publisher = models.ForeignKey(Publisher,on_delete=models.CASCADE)
    publication_date = models.DateField(blank=True, null=True)

注意:如果想讓日期字段(如 DateField、TimeField、DateTimeField)或數(shù)值字段(如 IntegerField、DecimalField、FloatField)接受空值,要同時(shí)添加 null=True 和 blank=True。

4、通過(guò)模型字段的verbose_name值指定后臺(tái)顯示的字段別名

myblog/books/models.py

class Author(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=40)
    email = models.EmailField(blank=True, verbose_name='e-mail')

5、自定義修改后臺(tái)管理列表

myblog/books/admin.py文件

from django.contrib import admin
from .models import Publisher, Author, Book
#自定義Author的后臺(tái)管理列表
class AuthorAdmin(admin.ModelAdmin):
        list_display = ('first_name', 'last_name', 'email')  #定義顯示字段
        search_fields = ('first_name', 'last_name')    #添加字段搜索
#自定義Book的后臺(tái)管理列表
class BookAdmin(admin.ModelAdmin):
        list_display = ('title', 'publisher', 'publication_date')    #定義顯示字段
        list_filter = ('publication_date',)    #添加時(shí)間過(guò)濾器
        date_hierarchy = 'publication_date'    #另一種日期過(guò)濾器
        ordering = ('-publication_date',)      #排序
        fields = ('title', 'authors', 'publisher', 'publication_date') #自定義修改表單
        filter_horizontal = ('authors',)       #使用選項(xiàng)框(多對(duì)多關(guān)系時(shí)使用)
        raw_id_fields = ('publisher',)         #通過(guò)id選擇對(duì)應(yīng)選項(xiàng)
admin.site.register(Publisher)
admin.site.register(Author,AuthorAdmin)
admin.site.register(Book,BookAdmin)

六、表單

(1)原生表單

1、獲取request數(shù)據(jù)應(yīng)該try或者設(shè)置默認(rèn)值,防止報(bào)錯(cuò)

方式一:

def ua_display_good1(request):
    try:
        ua = request.META['HTTP_USER_AGENT']
    except KeyError:
        ua = 'unknown'
    return HttpResponse("Your browser is %s" % ua)

方式二:

def ua_display_good2(request):
    ua = request.META.get('HTTP_USER_AGENT', 'unknown')
    return HttpResponse("Your browser is %s" % ua)

2、簡(jiǎn)單的表單提交及表單實(shí)例

get和post指向相同的url,根據(jù) if ‘q’ in request.GET:判斷是GET還是POST

模板頁(yè)面

#表單頁(yè)面:myblog/templates/search_form.html
<html>
<head>
    <title>Search</title>
</head>
<body>
    {% if errors %}   #提示錯(cuò)誤信息
    <ul>
        {% for error in errors %}
        <li>{{ error }}</li>
        {% endfor %}
    </ul>
    {% endif %}
    <form action="" method="get">  #action為空,表示提交到當(dāng)前頁(yè)面
        <input type="text" name="q">
        <input type="submit" value="Search">
    </form>
</body>
</html>
#結(jié)果展示頁(yè)面:myblog/templates/search_results.html
<html>
<head>
    <title>Book Search</title>
</head>
<body>
    <p>You searched for: <strong>{{ query }}</strong></p>
    {% if books %}
    <p>Found {{ books|length }} book{{ books|pluralize }}.</p>
    <ul>
        {% for book in books %}
        <li>{{ book.title }}</li>
        {% endfor %}
    </ul>
    {% else %}
    <p>No books matched your search criteria.</p>
    {% endif %}
</body>
</html>

視圖函數(shù):myblog/books/views.py文件

from django.shortcuts import render
from django.http import HttpResponse
def search(request):
    errors = []
    if 'q' in request.GET: # 如果是post,則存在GET['q']
        q = request.GET['q']
        if not q:
            errors.append('Enter a search term.')  # 提交了表單,但是內(nèi)容為空
        elif len(q) > 20:  # 提交表單,長(zhǎng)度超過(guò)限制
            errors.append('Please enter at most 20 characters.')
        else:   # 正常提交數(shù)據(jù)
            books = Book.objects.filter(title__icontains=q)
            return render(request, 'search_results.html',
                {'books': books, 'query': q})
    return render(request, 'search_form.html',{'errors': errors})  #不存在GET['q']說(shuō)明是GET請(qǐng)求

路由:myblog/urls.py文件

urlpatterns = [
    ...
    url(r'^search/$',views.search)
]

(2)Django表單模型

1、定義表單類(lèi)

myblog/books/forms.py

from django import forms
class ContactForm(forms.Form):
    subject = forms.CharField(max_length=100)  # max_length指定大長(zhǎng)度
    email = forms.EmailField(required=False)
    message = forms.CharField(widget=forms.Textarea) # widget參數(shù),指定表現(xiàn)邏輯,此次指定為文本框
    def clean_message(self):    # 自定義驗(yàn)表單證器
        message = self.cleaned_data['message']
        num_words = len(message.split())
        if num_words < 4:
            raise forms.ValidationError("Not enough words!")
        return message

自定義表單驗(yàn)證器:Django 的表單系統(tǒng)會(huì)自動(dòng)查找名稱(chēng)以 clean_ 開(kāi)頭、以字段名結(jié)尾的方法。如果存在這樣的方法,在驗(yàn)證過(guò) 程中調(diào)用。這里,clean_message() 方法會(huì)在指定字段的默認(rèn)驗(yàn)證邏輯(這個(gè) CharField 是必填的)執(zhí)行完畢后調(diào)用。

2、視圖函數(shù)

myblog/books/views.py

from books.forms import ContactForm
def contact(request):
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            #提示:如果沒(méi)有配置郵件服務(wù)器,調(diào)用 send_mail() 時(shí)會(huì)拋出 ConnectionRefusedError。
            send_mail(
                cd['subject'],
                cd['message'],
                cd.get('email', 'noreply@example.com'),
                ['siteowner@example.com'],
                )
            return HttpResponseRedirect('/contact/thanks/')
    else:
        form = ContactForm(
        initial={'subject': 'I love your site!'}  # 可以初始值
        )
    return render(request, 'contact_form.html', {'form': form})

3、表單頁(yè)面

myblogs/templates/contact_form.html

方式一:使用系統(tǒng)默認(rèn)表單

 <html>
 <head>
    <title>Contact us</title>
</head>
<body>
    <h2>Contact us</h2>
    {% if form.errors %}
    <p style="color: red;">
        Please correct the error{{ form.errors|pluralize }} below.
    </p>
    {% endif %}
    <form action="" method="post">
    {% csrf_token %}
        <table>
            {{ form.as_table }}
        </table>
        {% csrf_token %}
        <input type="submit" value="Submit">
    </form>
</body>
</html>

方式二:自定義表單外觀(guān)樣式

<html>
<head>
<title>Contact us</title>
</head>
<body>
    <h2>Contact us</h2>
    {% if form.errors %}
    <p style="color: red;">
        Please correct the error{{ form.errors|pluralize }} below.
    </p>
    {% endif %}
    <form action="" method="post">
        <div>
            {{ form.subject.errors }}
            <label for="id_subject">Subject:</label>
            {{ form.subject }}
        </div>
        <div>
            {{ form.email.errors }}
            <label for="id_email">e-mail:</label>
            {{ form.email }}
        </div>
        <div>
            {{ form.message.errors }}
            <label for="id_message">Message:</label>
            {{ form.message }}
        </div>
        {% csrf_token %}
        <input type="submit" value="Submit">
    </form>
</body>
</html>

4、路由設(shè)置

myblogs/myblogs/urls.py

urlpatterns = [
    ...
    url(r'^contact/$', views.contact),
]

以上是搭建Django項(xiàng)目的操作步驟的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對(duì)大家有幫助,更多相關(guān)知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)-成都網(wǎng)站建設(shè)公司行業(yè)資訊頻道!

分享標(biāo)題:搭建Django項(xiàng)目的操作步驟-創(chuàng)新互聯(lián)
網(wǎng)頁(yè)URL:http://muchs.cn/article44/cdihee.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供微信公眾號(hào)、服務(wù)器托管小程序開(kāi)發(fā)、Google、網(wǎng)站建設(shè)、網(wǎng)站排名

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶(hù)投稿、用戶(hù)轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀(guān)點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話(huà):028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)

成都seo排名網(wǎng)站優(yōu)化