问题:我有一个示例表单,用户可以在其中添加自己的语言,这是动态的。 我需要使用Django将其插入sqlite DB中。
我正在尝试获取数据,但是不知何故我没有得到想要的结果。 问题 : 1)无法获取PersonInfo ID的FK实例 2)没有语言列表。如果显示,则仅显示一种语言。
from django.db import models
# Create your models here.
class PersonInfo(models.Model):
firstname = models.CharField(max_length = 100)
lastname = models.CharField(max_length = 100)
phone = models.CharField(max_length = 20)
email = models.CharField(max_length = 100)
def __str__(self):
return self.firstname
class KnownLanguages(models.Model):
languagename = models.CharField(max_length = 100)
personinfo = models.ForeignKey(PersonInfo, on_delete = models.CASCADE)
def __str__(self):
return self.languagename
下面是Django View的代码
def addperson(request):
personinfo = PersonInfo.objects
knownlang = KnownLanguages
if request.method == 'POST':
if request.POST['firstname'] and request.POST['lastname'] and request.POST['languagename']:
person = PersonInfo()
lang = KnownLanguages()
person.firstname = request.POST['firstname']
person.lastname = request.POST['lastname']
person.phone = request.POST['phone']
person.email = request.POST['email']
# person.save()
print(person.firstname)
print(person.id)
lang.languagename = request.POST['languagename']
lang.personinfo = person
# lang.save()
print(lang)
return render(request, 'dynamicaddfields/addperson.html', {'personinfo' : personinfo, 'knownlang': knownlang})
else:
return render(request, 'dynamicaddfields/addperson.html', {'error' : 'Please fillout atleast First & Last Name and atleast one Language.'})
else :
return render(request, 'dynamicaddfields/addperson.html', {'personinfo' : personinfo, 'knownlang': knownlang})
下面是HTML代码
<form method = "POST" action = "{% url 'addperson' %}" enctype = "multipart/form-data">
{% csrf_token %}
<p> First Name : <input type="text" name="firstname" placeholder="First Name"> </p>
<p> Last Name: <input type="text" name="lastname" placeholder="Last Name"> </p>
<p> Phone Number : <input type="text" name="phone" placeholder="Phone Number"> </p>
<p> Email : <input type="text" name="email" placeholder="Email ID"> </p>
<p> Provide Languages you know : <div class="input_fields_wrap">
<br>
<button class="add_field_button">Add More Lanugages </button>
<div>
<input type="text" name="languagename"></div>
</div></p>
<input class="btn btn-primary" type="submit" name="create" value = "Add Person">
</form>