Reputation: 53
I am a beginner in Django/Python. Am having problem with djangos MultipleChoiceField in that it is not been displayed both in the loaded HTML in the browser and the page being displayed. The other aspects of the form such as my email field are been rendered successfully.
forms.py
class CustomSetForm(forms.Form):
choice = ()
def __init__(self, qs, *args, **kwargs):
super().__init__(*args, **kwargs)
requirements = qs.required
self.choice = list(requirements.split(','))
print(self.choice)
email = forms.EmailField(label='', max_length=100, required=True, widget=forms.TextInput(
attrs={'class': 'form-group form-control input-lg ', 'placeholder': 'Email'}), )
qualifications = forms.MultipleChoiceField(required=True, widget=forms.CheckboxSelectMultiple,
choices=choice)
views.py
def get_job_requirements(request, *args, **kwargs):
selected_job_title = kwargs.get('job_title')
obj_model = Author.objects.get(job_title=selected_job_title)
form = CustomSetForm(obj_model)
context = {'form': form}
try:
if request.method == "GET":
return render(request, 'requirements/job_specs.html', context)
if request.method == "POST":
if form.is_valid():
email = form.cleaned_data.get('email')
job_title_obj = Author.objects.get(job_title=selected_job_title)
qualifications = form.cleaned_data.get('qualifications')
applicant = Applicants.objects.create(email=email, job_title=job_title_obj,
qualifications=qualifications)
applicant.save()
return JsonResponse({'created': True})
return render(request, 'requirements/job_specs.html', context)
except Exception as e:
print(e)
return render(request, 'requirements/job_specs.html', context)
My Html
<form method="post" id="application-form">
{% csrf_token %}
{{ form.email }}
{{ form.qualifications.as_p }}
<div class="bg-light row" >
<div class="" id="btn-box">
<div class="col-md-12 d-grid gap-2 col-6 ">
<button type="submit" class="btn btn-primary btn-lg">Save</button>
</div>
</div>
</div>
</form>
HTML in browser
<form method="post" id="application-form">
<input type="hidden" name="csrfmiddlewaretoken" value="og1mWWpCR6rwxOw19fhUp4jX4KfFqbmeczbTwO92zNYtXBoESiZbi5biugeOj8N0">
<input type="text" name="email" class="form-group form-control input-lg " placeholder="Email" maxlength="100" required="" id="id_email">
<div class="bg-light row">
<div class="" id="btn-box">
<div class="col-md-12 d-grid gap-2 col-6 ">
<button type="submit" class="btn btn-primary btn-lg">Save</button>
</div>
</div>
</div>
</form>
Any help will be highly appreciated
Updated forms.py
class CustomSetForm(forms.Form):
choice = (
("1", "Austria"),
("2", "Germany"),
("3", "Netherlands"),
)
email = forms.EmailField(label='', max_length=100, required=True, widget=forms.TextInput(
attrs={'class': 'form-group form-control input-lg ', 'placeholder': 'Email'}), )
qualifications = forms.MultipleChoiceField(required=True, widget=forms.CheckboxSelectMultiple,
choices=choice)
Update
I changed {{ form.qualifications.as_p }}
to {{ form.qualifications}}
and got the following in my browser <django.forms.widgets.CheckboxSelectMultiple object at 0x0000018512709870>
Upvotes: 0
Views: 1224
Reputation: 53
After some research, I managed to solve the problem. I did this by changing from a MultipleChoiceField
to a ModelMultipleChoiceField
with some help from this article:
https://medium.com/swlh/django-forms-for-many-to-many-fields-d977dec4b024
Updated forms.py:
class ApplicationForm(forms.ModelForm):
email = forms.EmailField(label='', max_length=100, required=True, widget=forms.TextInput(
attrs={'class': 'form-group form-control input-lg ', 'placeholder': 'Email'}), )
required = forms.ModelMultipleChoiceField(queryset=Requirements.objects.all(), widget=forms.CheckboxSelectMultiple)
class Meta:
model = Requirements
fields = ['email', 'required']
Updated views.py:
def application_form(request):
try:
form = ApplicationForm()
context = {'form': form}
if request.method == 'GET':
return render(request, 'requirements/job_specs.html', context)
if request.method == 'POST':
if form.is_valid():
form.save()
return JsonResponse({'created': True})
return JsonResponse(form.errors.as_json(), safe=False)
except Exception as e:
print(e)
form = ApplicationForm(request.POST or None)
context = {'form': form}
return render(request, 'requirements/job_specs.html', context)
Upvotes: 2