1. Open pycharm:
file—>newproject–>django project
2. Configure static resource directory
In the last line of the settings.py folder.
STATIC_URL = '/static/' # HTML中使用的静态文件夹前缀
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"), # 静态文件存放位置
]
3. Create an app
Pycharm's Terminal input command:
python manage.py startapp app1
4. Custom functions
There is an additional app1 under the root directory of the project. In the views.py file of app1, we can customize functions.
Introduce the HttpResponse module.
from django.http import HttpResponse
Custom function:
def v3baisort1(request, response=None):
response = HttpResponse('[{"id":1,"content":"热卖爆款","url":"9.png"},{"id":2,"content":"坚果炒货","url":"2.png"},]')
response["Access-Control-Allow-Origin"] = "*"
return response
5. Configure routing
There is a folder with the same name as the project in the root directory, and the urls.py under it provides routing for functions in other apps.
First introduce the views under a certain app, and you can introduce multiple views.
from app1 import views
Set up routing for functions under this app.
urlpatterns = [
path('admin/', admin.site.urls),
path('v3baisort1/', views.v3baisort1),
]
If you need it as the home page, just set the routing like this.
path('', views.v3baisort1),
6. Multi-app routing configuration
If urls.py needs to set routes for functions in multiple apps.
urls.py in the same directory as the project name needs to be written like this:
from django.urls import path,include
urlpatterns = [
# path('admin/', admin.site.urls),
path('',include('frontplat.urls')),#前端展示的那个app
path('background/', include('background.urls'))
]
At the same time, create a new urls.py file under each app
The urls.py interface of the frontplat app
from django.urls import path
from frontplat import views
urlpatterns = [
path('',views.fronthome,name ="fronthome"),#这里设置为空
path('emailjudge',views.emailjudge,name ="emailjudge"),
...
...
The urls.py interface of the background app
from django.urls import path,re_path
from background import views
urlpatterns = [
path('', views.home, name="home"),
path('login', views.login, name="loginback"),
7. Run the project
Console input:
python manage.py runserver
Click this link to access it directly in your browser.