将模型DecimalField更改为Charfiled,现在form.is_valid()在Django 1.8中传递false

时间:2015-11-27 04:34:58

标签: python django django-models django-forms django-templates

我创建了一个包含两个DecimalFields的表单,它运行正常。接下来,我想在我的视图中放置一个组合框。所以,我将一个DecimalField更改为CharField

我删除了所有迁移文件,然后重新运行migrate命令。现在,视图还可以。但是,当我选择一些值并提交表单时,它会返回一个表单无效的错误。

after submit data

models.py

    PRODUCTS = (
    (0, 'Pedia Pro 250grm Pack'),
    (1, 'Pedia Pro 400grm Pack'),
    (2, 'Analene 400grm Pack'),
    (3, 'Analene 750grm Pack'),
    (4, 'Anchor 1 kg pack'),
    (5, 'Analene 750grm Pcak'),
    (6, 'Magarin '),
    (7, 'Magarin 500grm Pack'),
    (8, 'Anmun'),
    (9, 'Pedia 100grm Pack'),
)


@python_2_unicode_compatible
class Key_Gen(models.Model):
    #key_beging_code =models.DecimalField('Brand_name +Pack_size' ,max_digits=5, decimal_places=2)
    key_beging_code =models.CharField("Product ",max_length=3, choices=PRODUCTS)
    key_quantity    =models.DecimalField("key Quantity" ,max_digits=19, decimal_places=10)
    key_code        =models.CharField('key Code' ,max_length=50 , unique=True)
    is_public = models.BooleanField('public', default=True)
    date_created = models.DateTimeField('date created',auto_now_add=True)
    date_updated = models.DateTimeField('date updated',auto_now_add=True)



    class Meta:
        verbose_name='key_Gen'
        verbose_name_plural='keys_Gen'
        ordering = ['-date_created']


    def __str__(self):
        return '%s' % (self.key_code)


    def adddate(self, *args, **kwargs):
        if not self.id:
            self.date_created = now()
        self.date_updated = now


    def save(self, *args, **kwargs):
        if not self.key_code:
            self.key_code_temp =self.get_key_code(int(self.key_beging_code),int(self.key_quantity))

forms.py

    #define form
class KeyGenarateForm(ModelForm):
    class Meta:
        model = Key_Gen
        fields = ['key_beging_code', 'key_quantity']
        exclude = ('key_code','date_created', 'date_updated')

views.py

@login_required
def key_create(request):
    if request.method == 'POST':
        form = KeyGenarateForm(data=request.POST)
        print(form)
        if form.is_valid():
             #request.POST._mutable = True
             Key_Gen = form.save(commit=False)
             Key_Gen.save()
             return redirect('marcador_bookmark_user',username=request.user.username)
        else:
            print('form not valied')
    else:
        form = KeyGenarateForm()
        #print(form)
    context = {'form': form, 'create_key': True}
    return render(request, 'marcador/key_genarate_form.html', context)

1 个答案:

答案 0 :(得分:1)

我认为你的彗星和字符之间不匹配。

如果你的字段是CharField,那么选择char(每个元组中的第一个元素),而不是int(例如'0'而不是0或使用字母)。

或者,将其更改为IntegerField。

顺便说一句。您不需要同时在表单中填写这两个字段。