本篇內(nèi)容介紹了“如何用Vue+Django獨(dú)立開(kāi)發(fā)電商”的有關(guān)知識(shí),在實(shí)際案例的操作過(guò)程中,不少人都會(huì)遇到這樣的困境,接下來(lái)就讓小編帶領(lǐng)大家學(xué)習(xí)一下如何處理這些情況吧!希望大家仔細(xì)閱讀,能夠?qū)W有所成!
10年積累的成都網(wǎng)站設(shè)計(jì)、成都做網(wǎng)站經(jīng)驗(yàn),可以快速應(yīng)對(duì)客戶對(duì)網(wǎng)站的新想法和需求。提供各種問(wèn)題對(duì)應(yīng)的解決方案。讓選擇我們的客戶得到更好、更有力的網(wǎng)絡(luò)服務(wù)。我雖然不認(rèn)識(shí)你,你也不認(rèn)識(shí)我。但先做網(wǎng)站設(shè)計(jì)后付款的網(wǎng)站建設(shè)流程,更有義馬免費(fèi)網(wǎng)站建設(shè)讓你可以放心的選擇與我們合作。
在myproject下的settings.py配置文件中,把默認(rèn)的sqllite3數(shù)據(jù)庫(kù)換成我們的MySQL數(shù)據(jù)庫(kù)
# Database # https://docs.djangoproject.com/en/1.11/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'myproject', 'USER': 'root', 'PASSWORD': 'root', 'HOST': '127.0.0.1', }}
并把a(bǔ)pp加入到installed_apps列表里:
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myapp',]
4、 在app目錄下的models.py里我們簡(jiǎn)單寫(xiě)一個(gè)model如下:
# -*- coding: utf-8 -*-from __future__ import unicode_literalsfrom django.db import models # Create your models here.class Book(models.Model): book_name = models.CharField(max_length=64) add_time = models.DateTimeField(auto_now_add=True) def __unicode__(self): return self.book_name
只有兩個(gè)字段,書(shū)名book_name和添加時(shí)間add_time。如果沒(méi)有指定主鍵的話django會(huì)自動(dòng)新增一個(gè)自增id作為主鍵
5、 在app目錄下的views里我們新增兩個(gè)接口,一個(gè)是show_books返回所有的書(shū)籍列表(通過(guò)JsonResponse返回能被前端識(shí)別的json格式數(shù)據(jù)),二是add_book接受一個(gè)get請(qǐng)求,往數(shù)據(jù)庫(kù)里添加一條book數(shù)據(jù):
# Create your views here.@require_http_methods(["GET"])def add_book(request): response = {} try: book = Book(book_name=request.GET.get('book_name')) book.save() response['msg'] = 'success' response['error_num'] = 0 except Exception,e: response['msg'] = str(e) response['error_num'] = 1 return JsonResponse(response)@require_http_methods(["GET"])def show_books(request): response = {} try: books = Book.objects.filter() response['list'] = json.loads(serializers.serialize("json", books)) response['msg'] = 'success' response['error_num'] = 0 except Exception,e: response['msg'] = str(e) response['error_num'] = 1 return JsonResponse(response)
可以看出,在ORM的幫忙下,我們的接口實(shí)際上不需要自己去組織SQL代碼
6、 在app目錄下,新增一個(gè)urls.py文件,把我們新增的兩個(gè)接口添加到路由里:
from django.conf.urls import url, include import views
urlpatterns = [ url(r'add_book$', views.add_book, ), url(r'show_books$', views.show_books, ), ]
我們還要把a(bǔ)pp下的urls添加到project下的urls中,才能完成路由:
from django.conf.urls import url, includefrom django.contrib import adminfrom django.views.generic import TemplateViewimport myapp.urls urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^api/', include(myapp.urls)), url(r'^$', TemplateView.as_view(template_name="index.html")),]
“如何用Vue+Django獨(dú)立開(kāi)發(fā)電商”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識(shí)可以關(guān)注創(chuàng)新互聯(lián)網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實(shí)用文章!