我发现几个帖子的问题几乎与此相同,但我花了很多时间试图根据这些帖子找出我的问题,但我一生都无法解决这个问题。我正在尝试从表单中获取值并将它们放入我的数据库中(然后在我的表单下方列出数据库中的内容,但这对我来说更重要的是看看它是否有效)。似乎没有提取表单值,或者我没有正确保存到数据库中。
这是我的模型:
from django.db import models
from django.forms import ModelForm
class Users(models.Model):
user_first_name = models.CharField(max_length=255)
user_last_name = models.CharField(max_length=255)
email_address = models.CharField(max_length=255)
class UserForm(ModelForm):
class Meta:
model = Users
fields = ['user_first_name', 'user_last_name', 'email_address']
意见:
from django.shortcuts import render
from django.http import HttpResponseRedirect
from manage_users.models import Users, UserForm
def index(request):
users_list = Users.objects.all()
if request.method == 'POST':
form = UserForm(request.POST)
if form.is_valid():
user_first_name = request.POST.get('user_first_name', '')
user_last_name = request.POST.get('user_last_name', '')
email_address = request.POST.get('email_address', '')
users_obj = Users(user_first_name=user_first_name, user_last_name=user_last_name, email_address=email_address)
users_obj.save()
return HttpResponseRedirect('/')
else:
form = UserForm()
return render(request, 'home.html', {
'form': form, 'users_list': users_list
})
最后,我的html:
<body>
<form action="" method="post"> {% csrf_token %}
<div>
<label for="user_first_name">First Name:</label>
<input type="text" id="user_first_name" />
<br><label for="user_last_name">Last Name:</label>
<input type="text" id="user_last_name" />
<br><label for="email_address">Email Address:</label>
<input type="text" id="email_address" />
</div>
<button id ="add" type="submit">Submit</button>
</form>
{% if users_list %}
<ul>
{% for user in users_list %}
<li>{{ user }}</li>
{% endfor %}
</ul>
{% else %}
<p>No users are currently in the system</p>
{% endif %}
</body>