美文网首页
django MVC

django MVC

作者: 寻找无名的特质 | 来源:发表于2022-06-07 05:48 被阅读0次

首先创建模型,在models.py中创建模型,比如:

from django.db import models

class Student(models.Model):
    name_text=models.CharField(max_length=20)
    height=models.DecimalField(max_digits=10,decimal_places=3)
    weight=models.DecimalField(max_digits=10,decimal_places=3)

    def getBmi(self):
        return self.weight/self.height/self.height

注意,这里的模型与数据模型是对应的。
然后是创建template,在app目录下创建templates目录,然后创建app名称相同子目录,在里面创建html模板,比如inex.html:

{% if student_list %}
    <ul>
    {% for student in student_list %}
        <li><a href="/students/{{ student.id }}/">{{ student.name_text }}</a></li>
    {% endfor %}
    </ul>
{% else %}
    <p>没有记录.</p>
{% endif %}

在views.py文件中创建视图:

from django.http import HttpResponse
from django.shortcuts import render
from .models import Student

def index(request):
    student_list = Student.objects.all()
    context = {'student_list': student_list}
    return render(request, 'myfirst/index.html', context)

在urls.py中定义路径:

from django.urls import path

from . import views

urlpatterns = [
    path('', views.index, name='index'),
]

在项目的urls.py中定义项目的路径:

from django.contrib import admin
from django.urls import include, path
from . import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('myfirst/', include('myfirst.urls')),
    path('', views.hello),
]

相关文章

网友评论

      本文标题:django MVC

      本文链接:https://www.haomeiwen.com/subject/jaodmrtx.html