我正在嘗試使用 Post 方法從表單中檢索資料并將其存盤在資料庫中。但是,當我單擊提交按鈕時,我不斷收到以下錯誤:
NOT NULL 約束失敗:posts_subscribe.firstname
這是我的意見.py
def subscribe(request):
if request.method == 'POST':
firstname=request.POST.get('firstname')
secondname=request.POST.get('secondname')
email=request.POST.get('email')
phonenumber=request.POST.get('phonenumber')
en= Subscribe(firstname=firstname, secondname=secondname, email = email, phonenumber = phonenumber)
en.save()
return redirect('/')
return render(request, 'subscribe.html')
我的模型.py
class Subscribe(models.Model):
firstname = models.CharField(max_length=30, blank = True)
secondname = models.CharField(max_length=30, blank = True)
email = models.CharField(max_length=30)
phonenumber = models.IntegerField()
這是我的模板
{% extends 'index.html' %}
{% block subscribe %}
<div class="card mx-5">
<h1 class="mx-5 mt-3"> Subscribe</h1>
<form method="POST" enctype="multipart/form-data" action="subscribe">
{% csrf_token %}
<div class="mb-3 mx-5">
<label for="firstname" class="form-label ">First Name</label>
<input type="text" class="form-control form-control-lg" id="firstname" placeholder="firstname">
</div>
<div class="mb-3 mx-5">
<label for="secondname" class="form-label">Second Name (Optional)</label>
<input type="text" class="form-control form-control-lg" id="secondname" placeholder="secondname">
</div>
<div class="mb-3 mx-5">
<label for="email" class="form-label">Email</label>
<input type="email" class="form-control form-control-lg" id="email" placeholder="[email protected]">
</div>
<div class="mb-3 mx-5">
<label for="phonenumber" class="form-label">Phonenumber</label>
<input type="number" class="form-control form-control-lg" id="phonenumber" placeholder="0712345678">
</div>
<div class="mb-3 mx-5">
<button type="submit" class="btn-primary"> Subscribe</button>
</div>
</form>
</div>
{% endblock %}
還有我的網址模式
urlpatterns= [
path('', views.index, name='index'),
path('subscribe', views.subscribe, name ='subscribe'),
path('allposts', views.allposts, name='allposts'),
path('political', views.political, name='political'),
path('religion', views.religion, name='religion'),
path('trending', views.trending, name='treniding'),
path('<str:pk>', views.post, name='post'),
]
任何幫助將非常感激
uj5u.com熱心網友回復:
您應該向元素添加name="…"屬性 [mdn]<input>,因此:
<input type="text" name="firstname" id="firstname" placeholder="firstname"> … <input type="text" name="secondname" id="secondname" placeholder="secondname"> … <input type="email" name="email" id="email" placeholder="[email protected]"> … <input type="number" name="phonenumber" id="phonenumber" placeholder="0712345678">
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/492963.html
