0

我的模型中有一个名为 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>
4

1 回答 1

0

解决方法:我在我的项目中删除了 floppyforms 并改用 Select2,因为它支持对外键字段的搜索,并且还可以轻松地创建一个带有表单的实例。

模板

<script>
$(document).ready(function() {
  $('#id_medicamento').select2();
});
</script>

表格.py

class StockmovForm(forms.ModelForm):
class Meta:
model = Stockmov

fields =  ['medicamento', 'motivo', 'Cantidad' ]
widgets = {
'medicamento': forms.Select(attrs={'class':'form-control', 'placeholder':'Medicamento'}),
'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',
}
于 2020-12-04T22:26:31.393 回答