Skip to content

Instantly share code, notes, and snippets.

@endersonmenezes
Last active April 24, 2019 12:18
Show Gist options
  • Save endersonmenezes/7460d75782ccb10b0abda627fd734bbe to your computer and use it in GitHub Desktop.
Save endersonmenezes/7460d75782ccb10b0abda627fd734bbe to your computer and use it in GitHub Desktop.
Django Forms with Args making query in model
# Enderson Menezes
# Django Brasil
# 05/04/2019
# Django 2.2
from django import forms
from .models import CadastroSubEntidades
# Declare your form
class EscalarOcorrenciaRespForm(forms.Form):
def __init__(self, *args, **kwargs):
# Receive a arg called direxid from views.py
direxid = kwargs.pop('direxid')
super(EscalarOcorrenciaRespForm, self).__init__(*args, **kwargs)
# Create a field in form, this field make a query of options in model
self.fields['resp'] = forms.ModelChoiceField(
queryset=CadastroSubEntidades.objects.filter(entidade_id=direxid),
label="Responsável por analisar a ocorrência:",
help_text='Se o responsável desejado não aparecer aqui, verifique em seu painel o cadastro do responsável.')
# def your view
def view_name(request):
direxid = ... # Value for your arg
# initialize form with arg
form = EscalarOcorrenciaForm(initial={'direx': direx.id})
.
.
.
.
# continue your form view
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment