Django在使用主键更新模型时验证数据

时间:2015-01-19 19:52:27

标签: django

我在更新模型实例的字段时遇到问题。该模型如下:

class commonInfo(models.Model):
    mothers_id = models.IntegerField(primary_key=True)
    date = models.DateField()
    data_collector = models.CharField(max_length=50)

基本上,我只想这样做,但由于commonInfo具有用户定义的主键

,因此无法正常工作
commonInfo_form(request.POST or None).is_valid()

由于我正在更新,因此我将覆盖datedata_collector,而不是mothers_id。所以我想做这样的事情,但这个特定的代码不起作用

obj = commonInfo.objects.get(pk=commonInfo_id)
form = commonInfo_form(request.POST)
date = form.cleaned_data['data_collector'] #this line is not working
data_collector = form.cleaned_data['data_collector'] #this line is not working
obj.update(**{'date':date, 'data_collector':data_collector})

任何想法?我觉得这只是我需要解决的那两行。或者如果在Django中有更多的pythonic方法或构建方法?

2 个答案:

答案 0 :(得分:0)

只需使用isinstance进行验证即可。好像,

if isinstance(request.POST['date'], datetime.date) and isinstance(request.POST['data_collector'], str):
    # you might have to use getattr for request.POST here, I'm not sure
    # and request.POST['date'] would have to be converted from a string to datetime.date I think
    date = request.POST['date']
    data_collector = request.POST['data_collector']
    obj.update(**{'date':date, 'data_collector':data_collector})

答案 1 :(得分:0)

从表单添加记录的过程与更新现有实例不同。您需要做的就是以不同的方式指出在创建表单时将表单绑定到哪个实例,例如:

obj = commonInfo.objects.get(pk=commonInfo_id)
form = commonInfo_form(request.POST, instance=obj)