current position:Home>Implementation of home page and back end of Vue + Django tourism network project
Implementation of home page and back end of Vue + Django tourism network project
2022-02-01 11:04:01 【Xiao Wang is not serious】
This is my participation 11 The fourth of the yuegengwen challenge 26 God , Check out the activity details :2021 One last more challenge
Vue+Django Tourism network project Home page backend implementation
Shuffling figure
Configuration database
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'trip',
'USER': 'root',
'PASSWORD': '123456',
'HOST': '127.0.0.1',
'PORT': 3306,
}
}
Copy code
Create an
startapp system
Copy code
Create database
Writing model
class Slider(models.Model):
name=models.CharField(' name ',max_length=32)
desc=models.CharField(' describe ',max_length=100,null=True,blank=True)
types=models.SmallIntegerField(' The position of the presentation ',default=10)
img=models.ImageField(' Picture address ',max_length=255,upload_to='%Y%m/slider')
reorder=models.SmallIntegerField(' Sort field ',default=0,help_text=" The bigger the number, the higher it goes ")
start_time=models.DateTimeField(' Effective from ',null=True,blank=True)
end_time=models.DateTimeField(' Effective end time ',null=True,blank=True)
target_url=models.CharField(' Jump to address ',max_length=255,null=True,blank=True)
is_valid=models.BooleanField(' Whether it works ',default=True)
created_at=models.DateTimeField(' Creation time ',auto_now_add=True)
updated_at=models.DateTimeField(' Modification time ',auto_now=True)
class Meta:
db_table='system_slider'
ordering=['-reorder']
Copy code
Sign up for apps
Synchronize database
makemigrations
migrate
Copy code
Interface writing
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render
# Create your views here.
from system.models import Slider
def slider_list(request):
""" Carousel chart interface { "meta":[] "objects":[] } """
data ={
'meta':{},
'objects':[]
}
querset=Slider.objects.filter(is_valid=True)
for item in querset:
data['objects'].append({
'id':item.id,
'img_url': item.img.url,
'target_url':item.target_url,
'name': item.name
})
return JsonResponse(data)
Copy code
utl Set up
system/urls.py
from django.urls import path
from system import views
urlpatterns = [
path('slider/list', views.slider_list),
]
Copy code
root urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
# System module
path('system/',include('system.urls'))
]
Copy code
test
Before testing, you need to add data to the database
Scenic spot
New application
startapp sight
Copy code
register
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'system',
'sight'
]
Copy code
Writing model
class Sight(models.Model):
name = models.CharField(' name ',max_length=64)
desc=models.CharField(' describe ',max_length=255)
main_img=models.ImageField(' Main picture ',upload_to='%Y%m/sight/',max_length=255)
banner_img=models.ImageField(' Detail main drawing ',upload_to='%Y%m/sight/',max_length=255)
content=models.TextField(' details ')
score=models.FloatField(' score ',default=5)
min_price=models.FloatField(' The lowest price ',default=0)
province=models.CharField(' Province ',max_length=32)
city=models.CharField(' The city ',max_length=32)
area=models.CharField(' District / county ',max_length=32,null=True)
town=models.CharField(' Township ',max_length=32,null=True)
is_top=models.BooleanField(' Is it a selected scenic spot ',default=False)
is_hot=models.BooleanField(' Whether it is a popular scenic spot ',default=False)
is_valid=models.BooleanField(' Whether it works ',default=True)
created_at=models.DateTimeField(' Creation time ',auto_now_add=True)
updated_at=models.DateTimeField(' Modification time ',auto_now=True)
class Meta:
db_table:'sight'
ordering=['-updated_at']
Copy code
Database synchronization
makemigrations
migrate
Copy code
Interface writing
root utls.py
urlpatterns = [
path('admin/', admin.site.urls),
# System module
path('system/',include('system.urls')),
# Scenic spot
path('sight/',include('sight.urls'))
]
Copy code
sight urls.py
from django.urls import path
from sight import views
urlpatterns = [
# Attraction list interface
path('sight/list/', views.SightListView.as_view()),
]
Copy code
views.py
from django.db.models import Q
from django.http import JsonResponse
from django.shortcuts import render
# Create your views here.
from django.views.generic import ListView
from sight.models import Sight
class SightListView(ListView):
""" List of attractions """
# each page 5 Data
paginate_by = 5
def get_queryset(self):
# Rewrite the query method
query=Q(is_valid=True)
# Hot spots
is_hot = self.request.GET.get('is_hot',None)
if is_hot:
query=query & Q(is_hot=True)
# Selected scenic spots
is_top = self.request.GET.get('is_top', None)
if is_top:
query = query & Q(is_top=True)
queryset=Sight.objects.filter(query)
return queryset
def render_to_response(self, context, **response_kwargs):
page_obj=context['page_obj']
data = {
'meta': {
'total_count':page_obj.paginator.count,
'page_count':page_obj.paginator.num_pages,
'current_page':page_obj.number,
},
'objects': []
}
for item in page_obj.object_list:
data['objects'].append({
'id':item.id,
'name':item.name,
'main_img':item.main_img.url,
'score':item.score,
'province':item.province,
'min_price':item.min_price,
'city':item.city,
'comment_count':0
})
return JsonResponse(data)
Copy code
test
Interface docking of rotation chart
ajax.js
import axios from 'axios'
export const ajax = axios.create({
headers: {
source: 'h5',
icode: 'acbd',
'Content-Type': 'application/x-www-form-urlencoded'
},
withCredentials: true
})
ajax.interceptors.request.use(function (config) {
// What to do before sending the request
console.log(' Request intercepted ')
return config
}, function (error) {
// What do you do about the request error
return Promise.reject(error)
})
ajax.interceptors.response.use(function (response) {
// What to do with response data
console.log(' The response intercepted ')
return response
}, function (error) {
// What to do about response errors
if (error.response) {
if (error.response.status === 401) {
window.alert(' Not logged in , About to jump to the login page ')
} else if (error.response.status === 500) {
window.alert(' The server is busy , Please try again later ')
}
}
return Promise.reject(error)
})
Copy code
apis.js
// Store all interface addresses in the project
const apiHost = 'http://localhost:8080/api'
const AccountsApis = {
loginUrl: '/',
logoutUrl: ''
}
/** * System module interface */
const SystemApis = {
sliderListUrl: apiHost + '/system/slider/list/'
}
export {
AccountsApis,
SystemApis
}
Copy code
vue.config.js
module.exports = {
devServer:{
proxy: {
'/api': {
target:'http://127.0.0.1:8000/',
changeOrigin: true,
pathRewrite: {
'^/api': '' // need rewrite Rewrite the URL
}
}
}
}
}
Copy code
banner Components
<template>
<!-- Shuffling figure -->
<div class="home-banner-box"> <van-swipe class="my-swipe" :autoplay="3000" indicator-color="white"> <van-swipe-item v-for="item in bannerList" :key="item.id"> <img :src="item.img_url" alt=""> </van-swipe-item> </van-swipe> </div> </template>
<script> import { ajax } from '@/utils/ajax' import { SystemApis } from '@/utils/apis' export default { data () { return { bannerList: [] } }, methods: { /** * Get the data of the carousel */ getDataList () { ajax.get(SystemApis.sliderListUrl).then(res => { console.log('res', res) this.bannerList = res.data.objects }) } }, created () { this.getDataList() } } </script>
<style lang="less"> .home-banner-box { img { width: 100%; height: auto; } } </style>
Copy code
effect :
Scenic spot list interface
apis.js
// Store all interface addresses in the project
const apiHost = 'http://localhost:8080/api'
const AccountsApis = {
loginUrl: '/',
logoutUrl: ''
}
/** * System module interface */
const SystemApis = {
// Rotation chart list
sliderListUrl: apiHost + '/system/slider/list/'
}
/** * Attraction module */
const SightApis = {
// List of attractions
sightListUrl: apiHost + '/sight/sight/list/'
}
export {
AccountsApis,
SystemApis,
SightApis
}
Copy code
Components Fine.vue
<template>
<!-- Selected scenic spots -->
<div class="home-fine-box"> <!-- Navigation --> <van-cell icon="location-o" title=" Hot recommended " title-style="text-align:left" value=" All the lists " is-link /> <!-- list --> <div class="box-main"> <SightItem v-for="item in dataList" :key="item.id" :item="item"/> </div> </div>
</template>
<script> import { ajax } from '@/utils/ajax' import { SightApis } from '@/utils/apis' import SightItem from '@/components/common/ListSight' export default { components: { SightItem }, data () { return { dataList: [] } }, methods: { getDataList () { ajax.get(SightApis.sightListUrl, { params: { is_top: 1 } }).then(({ data }) => { this.dataList = data.objects }) } }, created () { this.getDataList() } } </script>
<style lang="less"> .home-fine-box { padding: 0 10px; .van-cell { padding: 10px 0; } .box-main { padding-bottom: 50px; } } </style>
Copy code
Hot.vue
<template>
<div class="home-hot-box"> <!-- Navigation --> <van-cell icon="/static/home/hot/fire.png" title=" Hot recommended " title-style="text-align:left" value=" All the lists " is-link /> <!-- list --> <div class="box-main"> <a href="#" class="hot-item" v-for="item in dataList" :key="item.id"> <div class="img"> <span></span> <img :src="item.main_img" alt=""> </div> <h5 class="van-ellipsis">{{ item.name }}</h5> <div class="line-price"> <span class="price">¥{{ item.min_price }}</span> rise </div> </a> </div> </div> </template>
<script> import { ajax } from '@/utils/ajax' import { SightApis } from '@/utils/apis' export default { data () { return { dataList: [] } }, methods: { getDataList () { ajax.get(SightApis.sightListUrl, { params: { is_hot: 1 } }).then(({ data }) => { this.dataList = data.objects }) } }, created () { // Query interface data this.getDataList() } } </script>
<style lang="less"> .home-hot-box { padding: 0 10px; .van-cell { padding: 10px 0; } .box-main { width: 100%; display: flex; padding-top: 10px; overflow-x: scroll; } .hot-item { display: flex; flex-direction: column; width: 100px; margin-right: 10px; padding-bottom: 10px; .img { position: relative; span { position: absolute; left: 0; top: 0; display: inline-block; width: 42px; height: 20px; z-index: 10; } img { width: 100px; height: 100px; } } h5 { color: #212121; padding: 2px 0; font-size: 12px; margin: 0; } .line-price { color: #212121; font-size: 12px; .price { color: #f50; font-size: 13px; } } &:nth-child(1) .img span { background: url(/static/home/hot/top1.png) no-repeat; background-size: 100% auto; } &:nth-child(2) .img span { background: url(/static/home/hot/top2.png) no-repeat; background-size: 100% auto; } &:nth-child(3) .img span { background: url(/static/home/hot/top3.png) no-repeat; background-size: 100% auto; } } } </style>
Copy code
effect :
copyright notice
author[Xiao Wang is not serious],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/02/202202011104004429.html
The sidebar is recommended
- Python from 0 to 1 (day 14) - Python conditional judgment 1
- Several very interesting modules in Python
- How IOS developers learn Python Programming 15 - object oriented programming 1
- Daily python, Chapter 20, exception handling
- Understand the basis of Python collaboration in a few minutes
- [centos7] how to install and use Python under Linux
- leetcode 1130. Minimum Cost Tree From Leaf Values(python)
- leetcode 1433. Check If a String Can Break Another String(python)
- Python Matplotlib drawing 3D graphics
- Talk about deep and shallow copying in Python
guess what you like
-
Python crawler series - network requests
-
Python thread 01 understanding thread
-
Analysis of earthquake distribution in the past 10 years with Python~
-
You need to master these before learning Python crawlers
-
After the old friend (R & D post) was laid off, I wanted to join the snack bar. I collected some data in Python. It's more or less a intention
-
Python uses redis
-
Python crawler - ETF fund acquisition
-
Detailed tutorial on Python operation Tencent object storage (COS)
-
[Python] comparison of list, tuple, array and bidirectional queue methods
-
Go Python 3 usage and pit Prevention Guide
Random recommended
- Python logging log error and exception exception callback method
- Learn Python quickly and take a shortcut~
- Python from 0 to 1 (day 15) - Python conditional judgment 2
- Python crawler actual combat, requests module, python to capture headlines and take beautiful pictures
- The whole activity collected 8 proxy IP sites to pave the way for the python proxy pool, and the 15th of 120 crawlers
- Why can't list be used as dictionary key value in Python
- Python from 0 to 1 (day 16) - Python conditional judgment 3
- What is the python programming language?
- Python crawler reverse webpack, a real estate management platform login password parameter encryption logic
- Python crawler reverse, a college entrance examination volunteer filling platform encrypts the parameter signsafe and decrypts the returned results
- Python simulated Login, selenium module, python identification graphic verification code to realize automatic login
- Python -- datetime (timedelta class)
- Python's five strange skills will bring you a sense of enrichment in mastering efficient programming skills
- [Python] comparison of dictionary dict, defaultdict and orderdict
- Test driven development using Django
- Face recognition practice: face recognition using Python opencv and deep learning
- leetcode 1610. Maximum Number of Visible Points(python)
- Python thread 03 thread synchronization
- Introduction and internal principles of Python's widely used concurrent processing Library Futures
- Python - progress bar artifact tqdm usage
- Python learning notes - the fifth bullet * class & object oriented
- Python learning notes - the fourth bullet IO operation
- Python crawler actual combat: crawl all the pictures in the answer
- Quick reference manual of common regular expressions, necessary for Python text processing
- [Python] the characteristics of dictionaries and collections and the hash table behind them
- Python crawler - fund information storage
- Python crawler actual combat, pyteseract module, python realizes the visualization of boos direct employment & hook post data
- Pit filling summary: Python memory leak troubleshooting tips
- Python code reading (Chapter 61): delaying function calls
- Through the for loop, compare the differences between Python and Ruby Programming ideas
- leetcode 1606. Find Servers That Handled Most Number of Requests(python)
- leetcode 1611. Minimum One Bit Operations to Make Integers Zero(python)
- 06python learning notes - reading external text data
- [Python] functions, higher-order functions, anonymous functions and function attributes
- Python Networkx practice social network visualization
- Data analysis starts from scratch, and pandas reads and writes CSV data
- Python review (format string)
- [pandas learning notes 01] powerful tool set for analyzing structured data
- leetcode 147. Insertion Sort List(python)
- apache2. 4 + windows deployment Django (multi site)