forms.py:
class QuestionForm(forms.ModelForm):
class Meta:
model = Question
fields = ('Statement',)
labels = {'Statement': _('Question'),
}
widgets = {
'Statement': Textarea(attrs={'rows':1, 'cols':200}),
}
class ResponseForm(forms.ModelForm):
class Meta:
model = Response
fields = ('Response', 'Topic', 'Client', 'Planit_location')
widgets = {
'Response': Textarea(attrs={'rows':3, 'cols':200}),
}
html:
<script>
function myFunction() {
alert("Added Successfully");
}
</script>
<form method="post" name="uploadform" style="margin-left: 16px">
{% csrf_token %}
<h4>Add Data</h4>
<table>
{{ qform.as_table }}
{{ rform.as_table }}
</table>
<button onclick="myFunction()" type="submit" class="btn btn-default">Submit</button>
</form>
views.py:
def adddata(request):
if request.user.is_authenticated:
username = request.user.username
if request.method == 'POST':
qform = QuestionForm(request.POST)
rform = ResponseForm(request.POST)
if qform.is_valid() and rform.is_valid():
qf = qform.save()
rf = rform.save(commit=False)
rf.Question = qf
rf.save()
return HttpResponseRedirect(reverse('adddata'))
else:
qform = QuestionForm()
rform = ResponseForm()
return render(request, 'app/adddata.html', {
"qform": qform,
"rform": rform,
"username": username,
})
在尝试提交空白字段时,我想将“问题和响应”字段设为必填字段。
当我单击“提交”时,如果其中一个字段或两个字段都为空,则弹出警告消息“添加成功”,但没有任何内容添加到数据库中。
当字段为空白并且尝试提交时,我该如何做,出现一条消息,指出要求字段必须像这样填充:
或类似的东西