我是python的新手,我正在使用django进行学生数据库应用。 学生数据库应用程序必须显示id,firstname,lastname,subjectnames,marks。 单身学生有多个科目和他们的分数。 我在访问学生有多个科目和分数的多个值时遇到了问题。
models.py
class Person(models.Model):
firstname=models.CharField(max_length=50)
lastname=models.CharField(max_length=50)
def __unicode__(self):
return (self.firstname,self.lastname)
class Marksheet(models.Model):
subname=models.CharField(max_length=50)
marks=models.IntegerField(max_length=10)
person=models.ForeignKey(Person)
def __unicode__(self):
return self.subname
views.py
def add_page(request,page_name): # function for creating the new records
p1=None
p2=None
if request.method=='POST':
p1=Person(firstname=request.POST['firstname'],lastname=request.POST['lastname'])
p1.save()
p2=Marksheet(subname=request.POST.getlist('subnames'),person=Person(person_id))
p2.save()
return render_to_response("add.html",{"page_name":page_name})
创建记录我在html中使用表单,如下所示....
模板 add.html
<form method="post" action="/newdcl/{{page_name}}/add/" > {% csrf_token %}
First name: <input type="text" name="firstname" /> <br />
Last name: <input type="text" name="lastname" /> <br />
Operating System <input value="os" name="subnames" type="checkbox"><br />
System Programming <input value="sp" name="subnames" type="checkbox"> <br />
Maths <input value="maths" name="subnames" type="checkbox"> <br />
<input type="submit" value="save" >
</form>
任何人都可以帮助我吗????
答案 0 :(得分:1)
您的问题似乎在于您尝试创建标记表的方式,您无法将值列表分配给一个字段。 使用您当前无形,可怕,无需验证的设置......您可以执行以下操作 -
p1=Person(firstname=request.POST['firstname'],
lastname=request.POST['lastname'])
p1.save()
for subname in request.POST.getlist('subnames'):
new = MarkSheet(subname=subname, person=p1)
#no data for marks, must define it to be able to be blank/null
new.save()
如果您打算没有任何初始标记,则需要将blank=True, null=True
添加到models.py中的标记字段。
答案 1 :(得分:0)
在我看来,它应该通过在Person中使用多对多关系来完成,并且表单应该被定义为表单类,因为你的表单中没有任何验证,而你正在编写一些html,这可以通过在模板中放入一行代码来生成。我会这样做:
models.py
class Marksheet(models.Model):
subname=models.CharField(max_length=50)
marks=models.IntegerField(max_length=10)
def __unicode__(self):
return self.subname
class Person(models.Model):
firstname=models.CharField(max_length=50)
lastname=models.CharField(max_length=50)
marksheets = models.ManyToManyField(Marksheet)
def __unicode__(self):
return (self.firstname,self.lastname)
forms.py 来自模型导入人
class PersonForm(ModelForm):
def __init__(self, *args, **kwargs):
super(PersonForm, self).__init__(*args, **kwargs)
# by default m2m relation is rendered with SelectMultiple widget -
# - below line is changing it to checkbox list
self.fields['marksheets'].widget = forms.CheckboxSelectMultiple()
class Meta:
model = Person
views.py
#inside your view function
if request.method == 'POST':
form = PersonForm(request.POST)
if form.is_valid():
form.save()
# pass form to template in render_to_response
add.html
<form method="post" action="/newdcl/{{page_name}}/add/" > {% csrf_token %}
{{ form }}
<input type="submit" value="save" >
</form>