Django: forms.MultipleChoiceField 未显示

Django: forms.MultipleChoiceField Not Displayed

我是 Django/Python 的初学者。我在使用 djangos MultipleChoiceField 时遇到问题,因为它既没有显示在浏览器中加载的 HTML 中,也没有显示在正在显示的页面中。表单的其他方面(例如我的电子邮件字段)已成功呈现。

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)

我的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 在浏览器中

<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>

任何帮助将不胜感激

已更新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)

更新 我将 {{ form.qualifications.as_p }} 更改为 {{ form.qualifications}} 并在我的浏览器中获得以下内容 <django.forms.widgets.CheckboxSelectMultiple object at 0x0000018512709870>

经过一番研究,我设法解决了这个问题。在这篇文章的帮助下,我通过将 MultipleChoiceField 更改为 ModelMultipleChoiceField 来做到这一点: https://medium.com/swlh/django-forms-for-many-to-many-fields-d977dec4b024

已更新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']

已更新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)