如何用Django建立一个简单的网页?
0 1047
0

👼求一个编程代码~~~

收藏
2021-04-15 09:02 更新 阿托 •  17069
共 1 个回答
高赞 时间
0

这是我们做实验时最基础的一部分,可以参考一下

$ python -m django --version
Creating a project
$ django-admin startproject mysite
The development server
$ python manage.py runserver
$ python manage.py runserver 8080
Creating the Polls app
$ python manage.py startapp polls
Write your first view
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello, world. You're at the polls index.")
polls/urls.py
from django.urls import path
from . import views
urlpatterns = [path('', views.index, name='index'),]
Mysite/urls.py
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('polls/', include('polls.urls')),path('admin/', admin.site.urls),]
$ python manage.py runserver
Database setup
$ python manage.py migrate
Creating models
polls/models.py
from django.db import models
Polls//models.py
class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
Activating models
Mysite//settings.py
INSTALLED_APPS = [
    'polls.apps.PollsConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',]

$ python manage.py makemigrations polls
$ python manage.py sqlmigrate polls 0001
$ python manage.py migrate
Polls/models.py
from django.db import models
class Question(models.Model):
    # ...
    def __str__(self):
        return self.question_text
class Choice(models.Model):
    # ...
    def __str__(self):
        return self.choice_text
Introducing the Django Admin
Creating an admin user:
$ python manage.py createsuperuser
Username: admin
Email address: admin@example.com
Password: **********
Password (again): *********
Superuser created successfully.
$ python manage.py runserver
Polls/admin.py
from django.contrib import admin
from .models import Question
admin.site.register(Question)

效果:

收藏
2021-04-15 09:06 更新 正直的烤面包 •  4004