How to connect views with forms Django
I have chained dropdown in views py and that`s all showing in html but how am i suppose to send them into my forms.py
Bcs where im trying to save that form into database i got an error of validation bcs views functions are not connected to my form
Im kinda tired of that function pls help me
views.py
@login_required
def create_work_log(request):
if request.method == 'POST':
form = WorkLogForm(request.POST, user=request.user)
if form.is_valid():
work_log = form.save(commit=False)
work_log.author = request.user
work_log = form.save()
messages.success(request, 'Данные занесены успешно', {'work_log': work_log})
return redirect('create_worklog')
else:
messages.error(request, 'Ошибка валидации')
return redirect('create_worklog')
else:
if request.user.is_authenticated:
initial = {
'author': request.user
}
else:
initial = {}
form = WorkLogForm(user=request.user, initial=initial)
context = {'form': form}
return render(request, 'contractor/create_work_log.html', context)
def contractor_object(request):
contractor_guid = request.GET.get('contractor_counter')
objects = ObjectList.objects.filter(contractor_guid__in=[contractor_guid])
context = {'objects': objects, 'is_htmx': True}
return render(request, 'partials/objects.html', context)
def contractor_section(request):
objects_guid = request.GET.get('object')
sections = SectionList.objects.filter(object=objects_guid)
context = {'sections': sections}
return render(request, 'partials/sections.html', context)
forms.py
contractor_counter = forms.ModelChoiceField(
label='Контрагент',
queryset=CounterParty.objects.none(),
initial=CounterParty.objects.first(),
empty_label='',
)
contractor_object = forms.ModelChoiceField(
label='Объект',
queryset=ObjectList.objects.none(),
initial=ObjectList.objects.first(),
empty_label='',
)
contractor_section = forms.ModelChoiceField(
label='Раздел',
queryset=SectionList.objects.none(),
initial=SectionList.objects.first(),
empty_label='',
)
template.html
<div class="mt-3">
{{ form.contractor_counter.label_tag }}
{% render_field form.contractor_counter class='form-select mt-2' autocomplete='off' hx-get='/objects/' hx-trigger='change' hx-target='#objects' %}
</div>
<div id="objects" class="mt-3">
{% include 'partials/objects.html' %}
</div>
<div id="sections" class="mt-3">
{% include 'partials/sections.html' %}
</div>