在我的 Django 的 model.py 中,我有以下条目:
class Method1(models.Model):
clustering_method_param = models.CharField(max_length=20,
default='ward', blank=True, choices=(
('complete', 'Complete linkage'),
('average','Average linkage'),
('ward','Ward'),))
distance_method_param = models.CharField(max_length=20, blank=True,
default='euclidean', choices=(
('euclidean', 'Euclidean'),
('manhattan','Manhattan'),
('pearsond','Pearson Correlation'),))
后来在 HTML 中呈现为:
我想做的是设置条件。即聚类方法ward
只能应用于距离度量euclidean
。如果用户将所有其他距离度量传递给 ward
,它应该返回错误消息。我如何在 Django 中应用它?还是应该改用 JavaScript?
这是 HTML 代码的示例:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="http://gregpike.net/demos/bootstrap-file-input/bootstrap.file-input.js"></script>
<meta charset="utf-8">
</head>
<body>
<form id="id-method1Form" class="form-horizontal" method="post" > <input type='hidden' name='csrfmiddlewaretoken' value='vr5MftcSxGGUeIOwKioeUlalXJdXNgkl' /> <div id="div_id_clustering_method_param" class="form-group"> <label for="id_clustering_method_param" class="control-label col-lg-2">
Clustering method
</label> <div class="controls col-lg-8"> <select class="select form-control" id="id_clustering_method_param" name="clustering_method_param">
<option value="complete">Complete linkage</option>
<option value="average">Average linkage</option>
<option value="ward" selected="selected">Ward</option>
</select> </div> </div> <div id="div_id_distance_method_param" class="form-group"> <label for="id_distance_method_param" class="control-label col-lg-2">
Distance measure
</label> <div class="controls col-lg-8"> <select class="select form-control" id="id_distance_method_param" name="distance_method_param">
<option value="euclidean" selected="selected">Euclidean</option>
<option value="manhattan">Manhattan</option>
<option value="pearsond">Pearson Correlation</option>
</select> </div> </div> <div class="form-group"> <div class="aab controls col-lg-2"></div> <div class="controls col-lg-8"> <input type="submit"
name="submit"
value="Submit"
class="btn btn-primary"
id="submit-id-submit"
/> </div> </div> </form>
<!--- END FORM DISPLAY-->
</body>
<html>
最佳答案
对于“用户体验”,我认为您需要编写一个 javascript 来根据所选的 clustering_method_param 更改所有距离。
但是,如果你只是想在 django 上“阻止”它。 您可以编写表单验证,如下所示:
def clean(self):
cleaned_data = self.cleaned_data
clustering_method_param = cleaned_data.get('clustering_method_param', None)
distance_method_param = cleaned_data.get('distance_method_param', None)
if clustering_method_param == 'ward':
if distance_method_param != 'euclidean':
self.errors.update(
{
'distance_method_param': [u'It should be euclidean.']
}
)
return cleaned_data
关于javascript - 在 Django CharFields 交互中应用条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32878276/