I want to create a charfield input in a django form that has suggestions. Essentially I want a choice field that also allows you to write your own value if needed. In other words a hybrid between a charfield and choice field input. Any suggestions on how to achieve this ?
forms.py
class PDFClassificationForm(forms.ModelForm):
nature = forms.CharField(required=False)
class Meta:
model = Documents
fields = [,
'nature',]
labels = {,,
'nature':'Nature/Concerne:',
}
def __init__(self, uuid_pdf, *args, **kwargs):
super(PDFClassificationForm, self).__init__(*args, **kwargs)
nature_choices= Archivagerecurrencelibelle.objects.filter(Q(id_emetteur=Documents.objects.get(uuid=uuid_pdf).id_emetteur) & Q(source="Nature")).values_list('concerne','concerne')
self.fields['nature'].choices = nature_choices
views.py
class DocumentsArchiveUpdateView(UpdateView):
model = Documents
template_name = 'documents/documents_read_write.html'
form_class = PDFClassificationForm
success_url = lazy(reverse, str)("documents_archive_list")
def get_context_data(self, *args, **kwargs):
# Call the base implementation first to get a context
context = super(DocumentsArchiveUpdateView, self).get_context_data(*args, **kwargs)
id_customer = Documents.objects.get(uuid=self.kwargs['uuid_pdf']).id_customer
context["document_owner"] = Entity.objects.get(id=id_customer)
context["uuid_contrat"] = self.kwargs['uuid_contrat']
context["uuid_group"] = self.kwargs['uuid_group']
context["uuid_pdf"] = self.kwargs['uuid_pdf']
return context
def form_valid(self, form):
obj = form.save(commit=False)
obj.id_document_status = DocumentStatusLst.objects.get(id=3)
obj.save()
return super().form_valid(form)
documents_read_write.html
{% extends 'layout.html' %}
{% load crispy_forms_tags %}
<form action = "{%url 'jnt_customer_create' uuid_contrat uuid_group pdfid%}" method="POST" enctype="multipart/form-data">
<!-- Security token -->
{% csrf_token %}
<!-- Using the formset -->
{{ form |crispy}}
<button type="submit" name="btnform1" >Enregistrer</button>
</form>
{% endblock %}
CodePudding user response:
after entering keyword