关于表格的Django问题

时间:2011-09-16 13:06:38

标签: python django forms models

您好我有一个django应用程序,其中包含可以添加销售和购买的表单。我想用它做一个改变。如果用户选择购买而不是销售,我不希望他们拥有国家/地区类型(位置)。事实上,我不希望他们对购买有任何价值。

因此,对于夏季,所有销售都应该有一个选择国家类型的选项,而所有购买都不应该给予此选项。我怎么能这样做?

enter image description here

models.py

from  management_sys.vat import models   
TRANSACTION_TYPE_CHOICES = ((1, 'sale'), (2, 'purchase'),)  
COUNTRY_TYPE_CHOICES = ((1, 'UK'), (2, 'EU'),)

class Transaction(models.Model):     
    transaction_type = models.Integerfield(verbose_name = "Type", choices = TRANSACTION_TYPE_CHOICES)     
    country_type = models.Integerfield(verbose_name = "Location", choices = COUNTRY_TYPE_CHOICES)     
    date = models.Datefield()     
    vat_period = models.Datefield()     
    amount = models.DecimalField(max_digits=20, decimal_places=2)     
    vat = models.DecimalField(max_digits=20, decimal_places=2)     
    description models.TextField(MAX_LENGTH = 400)     
    def __unicode__(self):         
        return unicode(self.amount) 

forms.py

from management_sys.vat.models import *
from django import forms

class TransactionForm(forms.ModelForm):
    class Meta:
        model = Transaction

2 个答案:

答案 0 :(得分:0)

这个问题与django无关。您应该通过javascript执行此操作:隐藏或在< select>上显示一些字段值。

唯一的是表单验证。你应该在你的情况下执行它:

   from django.core.exceptions import ValidationError

   class Transaction(models.Model):
       # your fields

       def clean(self):
           if self.transaction_type == 2 and self.country_type:
               raise ValidationError(u'You must not fill location with "purchase" option.')

答案 1 :(得分:0)

你应该使用javascript。如果您正在使用{{form.as_table}},那么通过使用jQuery,它看起来像这样:

<script type="text/javascript">
    $(function() {
        showOrHideLocation();
        $('#id_transaction_type').change(showOrHideLocation);
    });
    function showOrHideLocation() {
        if ($('#id_transaction_type option:selected[value=1]').length) {
            $('#id_country_type').parents('tr:first').show();
        }
        else {
            $('#id_country_type').parents('tr:first').hide();
        }
    }
</script>

然后只需在表单中验证结果即可。