Creating a form that has the pre-set choice

1

I want to throw an item on as expense or revenue for that I did;

from django.db import models

# Create your models here.
class SubCategoria(models.Model):
    ESCOLHA = (
        (u'1', u'Receita'),
        (u'2', u'Despesa'),
    )
    categoria = models.CharField(max_length=1, choices=ESCOLHA)
    nome = models.CharField('Nome', max_length=200)
    slug = models.SlugField('Atalho', unique=True)

    def __str__(self):
        return self.nome

class Item(models.Model):
    categoria = models.ForeignKey(SubCategoria)
    data = models.DateField('Data Vencimento/Recebimento')
    cadastrado = models.DateTimeField(verbose_name='Cadastrado', auto_now_add=True)
    atualizado = models.DateTimeField(verbose_name='Atualizado', auto_now=True)
    nome = models.CharField('Nome', max_length=100)
    descricao = models.TextField('Descrição')
    valor  = models.DecimalField('Valor', max_digits=5, decimal_places=2)
    pagamento = models.BooleanField('Pago/Recebido', default=False)

    def __str__(self):
        return '{} R$ {}'.format(self.nome, self.valor)

I made a forms.py

from django import forms
from .models import SubCategoria, Item
from .models import SubCategoria

class SubCategoriaForm(forms.ModelForm):
    class Meta:
        model = SubCategoria
        fields = ('nome', 'slug', 'categoria')

class ItemForm(forms.ModelForm):

    class Meta:
        model = Item
        fields = ('categoria', 'data', 'nome', 'descricao', 'valor', 'pagamento')

I would like to know how I can define that and always only the profit categories appear, exe SubCategoria.objects.filter(categoria= 1)

    
asked by anonymous 28.11.2016 / 13:49

1 answer

1

You should make an init override of your form.

class ItemForm(forms.ModelForm):
    ...
    def __init__(self, *args, **kwargs):
        self.fields['categoria'].queryset = SubCategoria.objects.filter(categoria='1')
        super(ItemForm, self).__init__(*args, **kwargs)
    
28.11.2016 / 13:58