您好,登錄后才能下訂單哦!
這篇文章主要介紹搭建Django項目的操作步驟,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!
一、創建一個Django項目
1、使用虛擬環境
#快速創建虛擬環境 python -m venv prjvenv #激活虛擬環境 source prjvenv/bin/activate
2、創建項目
#安裝django pip install django #創建項目 django-admin startproject myblog
3、django設置
myblog/settings.py文件
TIME_ZONE='Asia/Shanghai'
4、數據庫遷移
python manage.py migrate
5、啟動
python manage.py runserver
二、視圖和URL配置
myblog/views.py文件
from django.http import HttpResponse #最簡單視圖 def hello(request): return HttpResponse("Hello world") #帶參數的視圖 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', ], }, }, ] 如果想在項目根目錄中放一些主模板(例如在 mysite/templates 目錄中),需要像這樣設定 DIRS: 'DIRS': [os.path.join(BASE_DIR, 'templates')],
2、視圖函數
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、配置數據庫
myblog/setting.py
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } }
2、創建應用
python manage.py startapp books
3、激活應用
INSTALLED_APPS = ( ... 'books', )
4、創建模型
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、遷移數據庫
#括號中的內容可以不需要 python manage.py makemigrations (books) python manage.py migrate
6、操作數據
新增數據
方式一: p1 = Publisher(...) p1.save() 方式二: p1 = Publisher.objects.create(...)
更新數據
方式一: p.name = 'Apress Publishing' p.save() 方式二: Publisher.objects.filter(id=52).update(name='Apress') #推薦
查詢數據
返回查詢集合
Publisher.objects.all() Publisher.objects.filter(name='Apress') #WHERE name = 'Apress'; Publisher.objects.filter(name__contains="press") #WHERE name LIKE '%press%';
返回單個對象
Publisher.objects.get(name="Apress") #不是1個對象就會報異常 try: p = Publisher.objects.get(name='Apress') #數據庫中存在一個數據 except Publisher.DoesNotExist: print ("Apress isn't in the database yet.") #數據庫中沒有數據 else: print ("Apress is in the database.") #有多個數據
刪除
方式一:單個刪除 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") #根據姓名和年齡排序,-name/-age實現反向排序 方式二:在模型內定義 class Publisher(models.Model): ... class Meta: ordering = ['name']
切片
Publisher.objects.order_by('name')[0:2]
五、后臺管理
1、創建管理員用戶
python manage.py createsuperuser
2、將模型添加到后臺管理
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、修改模型,使字段在后臺輸入時變為可選項
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)或數值字段(如 IntegerField、DecimalField、FloatField)接受空值,要同時添加 null=True 和 blank=True。
4、通過模型字段的verbose_name值指定后臺顯示的字段別名
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、自定義修改后臺管理列表
myblog/books/admin.py文件
from django.contrib import admin from .models import Publisher, Author, Book #自定義Author的后臺管理列表 class AuthorAdmin(admin.ModelAdmin): list_display = ('first_name', 'last_name', 'email') #定義顯示字段 search_fields = ('first_name', 'last_name') #添加字段搜索 #自定義Book的后臺管理列表 class BookAdmin(admin.ModelAdmin): list_display = ('title', 'publisher', 'publication_date') #定義顯示字段 list_filter = ('publication_date',) #添加時間過濾器 date_hierarchy = 'publication_date' #另一種日期過濾器 ordering = ('-publication_date',) #排序 fields = ('title', 'authors', 'publisher', 'publication_date') #自定義修改表單 filter_horizontal = ('authors',) #使用選項框(多對多關系時使用) raw_id_fields = ('publisher',) #通過id選擇對應選項 admin.site.register(Publisher) admin.site.register(Author,AuthorAdmin) admin.site.register(Book,BookAdmin)
六、表單
(1)原生表單
1、獲取request數據應該try或者設置默認值,防止報錯
方式一:
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、簡單的表單提交及表單實例
get和post指向相同的url,根據 if ‘q’ in request.GET:判斷是GET還是POST
模板頁面
#表單頁面:myblog/templates/search_form.html <html> <head> <title>Search</title> </head> <body> {% if errors %} #提示錯誤信息 <ul> {% for error in errors %} <li>{{ error }}</li> {% endfor %} </ul> {% endif %} <form action="" method="get"> #action為空,表示提交到當前頁面 <input type="text" name="q"> <input type="submit" value="Search"> </form> </body> </html>
#結果展示頁面: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>
視圖函數: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.') # 提交了表單,但是內容為空 elif len(q) > 20: # 提交表單,長度超過限制 errors.append('Please enter at most 20 characters.') else: # 正常提交數據 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']說明是GET請求
路由:myblog/urls.py文件
urlpatterns = [ ... url(r'^search/$',views.search) ]
(2)Django表單模型
1、定義表單類
myblog/books/forms.py
from django import forms class ContactForm(forms.Form): subject = forms.CharField(max_length=100) # max_length指定最大長度 email = forms.EmailField(required=False) message = forms.CharField(widget=forms.Textarea) # widget參數,指定表現邏輯,此次指定為文本框 def clean_message(self): # 自定義驗表單證器 message = self.cleaned_data['message'] num_words = len(message.split()) if num_words < 4: raise forms.ValidationError("Not enough words!") return message
自定義表單驗證器:Django 的表單系統會自動查找名稱以 clean_ 開頭、以字段名結尾的方法。如果存在這樣的方法,在驗證過 程中調用。這里,clean_message() 方法會在指定字段的默認驗證邏輯(這個 CharField 是必填的)執行完畢后調用。
2、視圖函數
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 #提示:如果沒有配置郵件服務器,調用 send_mail() 時會拋出 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、表單頁面
myblogs/templates/contact_form.html
方式一:使用系統默認表單
<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>
方式二:自定義表單外觀樣式
<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、路由設置
myblogs/myblogs/urls.py
urlpatterns = [ ... url(r'^contact/$', views.contact), ]
以上是搭建Django項目的操作步驟的所有內容,感謝各位的閱讀!希望分享的內容對大家有幫助,更多相關知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。