django向数据库添加数据的模版语法举例
时间: 2023-06-06 21:09:00 浏览: 65
好的,以下是向 Django 数据库中添加数据的模板语法:
1. 首先创建一个表单,用于提交数据:
<form method="post">
{% csrf_token %}
<label for="name">Name:</label>
<input type="text" name="name">
<label for="age">Age:</label>
<input type="number" name="age">
<button type="submit">Submit</button>
</form>
2. 接着在视图函数中获取到表单中提交的数据,并将其保存到数据库中:
from .models import Person
def add_person(request):
if request.method == 'POST':
name = request.POST['name']
age = request.POST['age']
person = Person(name=name, age=age)
person.save()
return HttpResponse('Person added successfully!')
return render(request, 'add_person.html')
3. 最后,在 models.py 文件中定义 Person 模型:
from django.db import models
class Person(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField()
这就是向 Django 数据库中添加数据的模板语法举例。希望对你有所帮助!
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)