我的模型中有一个名为 medicamento 的字段,它是一个外键,我希望该字段中的所有值都显示在表单的可搜索下拉列表中。我能够做到这一点,但是当我尝试保存时,它显示“选择一个有效的选择。该选择不是可用的选择之一。” 希望你能帮助伙计们!提前致谢
模型.py
class Stockmov(models.Model):
numero = models.AutoField(primary_key=True)
created= models.DateTimeField(auto_now_add=True,verbose_name="Fecha de Movimiento")
author = models.ForeignKey(User,verbose_name="autor",on_delete=models.PROTECT, null=True, blank=True)
medicamento= models.ForeignKey(Medicamento,on_delete=models.CASCADE)
motivo= models.CharField(max_length=200)
Cantidad = models.IntegerField()
表格.py
class StockmovForm(forms.ModelForm):
class Meta:
model = Stockmov
fields = ['medicamento', 'motivo', 'Cantidad' ]
widgets = {
#'medicamento': forms.Select(attrs={'class':'form-control', 'placeholder':'Medicamento'}),
'medicamento': forms.widgets.TextInput(attrs={'class':'form-control', 'placeholder':'Medicamento'},datalist=Medicamento.objects.all()),
'motivo': forms.TextInput(attrs={'class':'form-control', 'placeholder':'Motivo'}),
'Cantidad': forms.NumberInput(attrs={'class':'form-control', 'placeholder':'Cantidad'}),
}
labels = {
'medicamento':'Medicamento', 'motivo':'Motivo del Movimiento', 'Cantidad':'Cantidad del Movimiento',
}
视图.py
class StockmovCreate(CreateView):
model = Stockmov
form_class = StockmovForm
success_url = reverse_lazy('stockmov:stockmov')
def form_valid(self, form):
form.instance.author = self.request.user
print(self.request.user)
return super(StockmovCreate, self).form_valid(form)
模板
<form action="" method="post">{% csrf_token %}
{{ form.as_p }}`s`
<div class="text-center">
<input type="submit" id="btnCrear" class="btn btn-secondary btn-block" value="Crear Movimiento" />
</div>
</form>