Creating a form that has the Choice pre defined

Asked

Viewed 96 times

1

I want to launch an item on as expense or revenue for this 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)

and 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 appear only the categories of profit, exe SubCategoria.objects.filter(categoria= 1)

1 answer

1

You must override your form’s init.

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.