我在Django项目中使用的HTML页面中有一个表单。这种形式从用户那里获取输入并将其发送到一个页面,该页面应将其保存到数据库中,但是现在它没有执行。这是代码:
<!DOCTYPE html>
<html>
<body>
<h2>Create product here</h2>
<div>
<form id="new_user_form" method="post" action="user/create"}>
{% csrf_token %}
<div>
<label for="name" > Name:<br></label>
<input type="text" id="name"/>
</div>
<br/>
<div>
<label for="description"> description:<br></label>
<input type="text" id="description"/>
</div>
<div>
<label for="price" > price:<br></label>
<input type="text" id="price"/>
</div>
<div>
<input type="submit" value="submit"/>
</div>
</div>
</form>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</html>
我的urls.py文件:
from django.contrib import admin
from django.urls import path
from django.conf.urls import include, url
from testapp import views
admin.autodiscover()
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.index),
path('user/create', views.create_user, name='create_user')
]
views.py文件:
from django.shortcuts import render
from testapp.models import User
from django.http import HttpResponse
def index(request):
return render(request, 'index.html')
def create_user(request):
if request.method == 'POST':
name = request.POST.get('name')
description = request.POST.get('description')
price = request.POST.get('price')
newUser = User(
name = name,
description = description,
price = price
)
newUser.save()
return HttpResponse('')
和models.py文件:
from django.db import models
# Create your models here.
class User(models.Model):
name = models.CharField(max_length = 32, null = True)
description = models.TextField(null = True)
price = models.CharField(max_length = 128, null = True)
现在的问题是,表单数据被发送到函数create_user时,它应该获取数据并使用该数据创建一个对象并将其保存到数据库。正确设置数据库,因为当我使用Django Shell进行测试时,创建并保存了用户。但是,通过表单和python,这里出现了问题,我不确定为什么。有人可以帮我吗?
答案 0 :(得分:0)
您需要在输入的html标记中放置名称
<input type="text" id="name" name="name"/>
<input type="text" id="description" name="description"/>
<input type="text" id="price" name="price"/>