I have a field called medicamento in my model that is a foreign key and I want all the values in that field to be displayed in a searcheable dropdown in my form. I was able to do that but when I try to save, it says "Select a valid choice. That choice is not one of the available choices."
Hope u can help dudes!
Thanks in advance
The Code:
models.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()
forms.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',
}
views.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)
Template
<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>
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/69572c34-5ea6-425a-b0f4-b148438d6883n%40googlegroups.com.

No comments:
Post a Comment