我已经尝试了其他类似问题的帖子,但我处理的代码是由第三方制作的,我遇到了一些小问题。我根本无法使用我想要的初始值定义其中一个表单。怎么办?
models.py
class Livro(models.Model):
codigo = models.AutoField(primary_key=True)
nome = models.CharField("Nome", max_length=50, unique = True)
autor = models.CharField("Autor", max_length=50, unique = True)
edicao = models.CharField("Edição", max_length=30, unique = True)
disciplina = models.ForeignKey(Disciplina)
tipo = models.CharField("Tipo", max_length=20, choices = Choices.tipo)
ano = models.CharField("Ano", max_length=30, choices = Choices.ano)
situacao = models.CharField("Situação", max_length=30, choices = Choices.situacao, blank = True, null = True)
def __unicode__(self):
return self.nome
views.py
def cadastrar_livro(request):
form = LivroForm(request.POST or None)
if form.is_valid():
salvo = form.save(commit=False)
salvo.situacao = "Ativado"
salvo.save()
return HttpResponseRedirect('/principal')
return render_to_response('cadastrar_livro.html', locals(), context_instance = RequestContext(request))
和choices.py
class Choices(models.Model):
tipo = (
('1', 'Seriado'),
('2', 'Único'),
)
ano = (
('1', '1º'),
('2', '2º'),
('3', '3º'),
('4', 'Único'),
)
situacao = (
('Ativado', 'Ativado'),
('Desativado', 'Desativado'),
)
我只需要选择能够预先选择Ativado,但无法找到任何解决方案。需要帮助谢谢。
答案 0 :(得分:1)
您是否尝试在situacao字段中设置default
参数。
situacao = models.CharField("Situação", max_length=30, choices=Choices.situacao, default=Choices.situacao[0][1], blank=True, null=True)
答案 1 :(得分:0)
您可以在表单的 .initial =
中动态设置 __init__
:
class FormChooseRegulation(forms.Form):
regulation = forms.ChoiceField(required=True, label=_('Regulation'))
def __init__(self, *args, **kwargs):
regulations = kwargs.pop('regulations', ())
regulation_last = kwargs.pop('regulation_last', None)
super().__init__(*args, **kwargs)
self.fields['regulation'].choices = regulations
if regulation_last:
self.fields['regulation'].initial = regulation_last
在视图中调用:
def regulation_selection(request):
regulations = list(Regulation.objects.values_list('id', 'label'))
form_regulation = FormChooseRegulation(
regulations=regulations,
regulation_last=request.session.get('regulation_id')
)