我刚刚开始我的django初学者教程,并面临将数据插入sq lite数据库的问题。在加载页面AddUser时,它说;
/ AddUser / NOT NULL约束中的IntegrityError失败: SendMessage_users.UserName
Users.objects.create(UserID = User_ID,UserName = User_Name,Email = User_Email,Phone = User_Phone)
model.py是
class Users(models.Model):
UserID = models.IntegerField(verbose_name='User ID',max_length=255,primary_key=True)
UserName = models.CharField(verbose_name='User Name',max_length=254)
Email = models.EmailField(verbose_name='Email',max_length=254)
Phone = models.CharField(verbose_name='Phone Number',max_length=254)
并且view.py是
def add_user(request):
User_ID = request.POST.get('UserID')
User_Name = request.POST.get('UserName')
User_Email = request.POST.get('Email')
User_Phone = request.POST.get('Phone')
Users.objects.create(UserID = User_ID , UserName = User_Name, Email = User_Email ,Phone = User_Phone)
return render_to_response('add_user.html', context_instance=RequestContext(request))
和add_user.html是
{% extends "base.html" %}
{% block Content %}
<div class="container">
<!-- Contacts -->
<div id="contacts">
<div class="row">
<!-- Alignment -->
<div class="col-sm-offset-3 col-sm-4">
<!-- Form itself -->
<form name="AddUsers" action="" method="POST" class="well" id="contactForm" novalidate>
{% csrf_token %}
<legend>Send Messages</legend>
<div class="control-group">
<div class="controls">
<input type="text" class="form-control"
placeholder="Subject" id="UserID" name="UserID" required
data-validation-required-message="Please enter UserID" />
<p class="help-block"></p>
</div>
</div>
<div class="control-group">
<div class="controls">
<input type="text" class="form-control"
placeholder="Subject" id="UserName" name="UserName" required
data-validation-required-message="Please enter UserName" />
<p class="help-block"></p>
</div>
</div>
<div class="control-group">
<div class="controls">
<input type="text" class="form-control"
placeholder="Subject" id="Email" name="Email" required
data-validation-required-message="Please enter Email" />
<p class="help-block"></p>
</div>
</div>
<div class="control-group">
<div class="controls">
<input type="text" class="form-control"
placeholder="Subject" id="Phone" name="Phone" required
data-validation-required-message="Please enter Phone" />
<p class="help-block"></p>
</div>
</div>
<div id="success"> </div>
<button type="submit" class="btn btn-primary btn-sm pull-right">Send</button><br />
</form>
</div>
</div>
</div>
</div>
{% endblock %}
答案 0 :(得分:0)
发生错误是因为当您向该URL发出GET请求时,它正在尝试从POST数据中获取数据,这显然当时不存在,并且它正在尝试使用此“无”创建对象数据。在视图中,您必须通过检查request.method值来为您期望的每个请求方法(GET和POST我假设)做出改变。
答案 1 :(得分:0)
试试这个:
models.Users.objects.create()