如何从我的模型中的form.py中获取选择标签的选项?

时间:2018-08-15 09:43:52

标签: django django-models django-forms

请帮助我解决此问题!我有工作申请表,我有这个 models.py:

class Vacancy(models.Model):
vacancy_title = models.CharField(max_length=100)
vacancy_description = models.TextField()
data = models.DateTimeField(default=timezone.now)
contact_person = models.CharField(max_length=50)
phone_number = models.CharField(max_length=30)
mail = models.EmailField();

def __str__(self):
    return self.vacancy_title

用户必须选择一个空缺

        <select name="job_field" id="job_field">
            {% for vacancy in vacancies %}
            <option value="">{{ vacancy.vacancy_title }}</option>
            {% endfor %}
        </select>

这是表格。py:

from django import forms
from .models import Vacancy

CHOICES = (Vacancy.objects.all().values_list('vacancy_title', flat=True))


class ApplicantForm(forms.Form):
   name = forms.CharField(max_length=50)
   surname = forms.CharField(max_length=50)
   email = forms.EmailField()
   selected_position = forms.ChoiceField(choices=CHOICES)

还有views.py:

def send_resume(request):

vacancies = Vacancy.objects.all();

if request.method == 'POST':

    form = ApplicantForm(request.POST)

    if form.is_valid():
        name = form.cleaned_data['applicant_name']
        surname = form.cleaned_data['applicant_surname']
        passport_number = form.cleaned_data['passport_number']
        from_mail = form.cleaned_data['mail']
        position = form.cleaned_data['position']

    else:
        form = ApplicantForm()

context = {'vacancies': vacancies}
return render(request, 'interactive/send_resume.html', context)

现在在forms.py中,我无法将vacancy_title连接到选择组的选择(“选择字段”)。怎么做?

2 个答案:

答案 0 :(得分:1)

您可以只使用ModelChoiceField

@TestPropertySource

这是更通用的方式

答案 1 :(得分:0)

使用django-model-utils模块。您的模型代码如下所示。

from model_utils import Choices

VACANCY_CHOICE = Choices(
          ('MANAGER', 'MANAGER', _('Development Manager')),
          ('SALES', 'SALES', _('Sales VP')),
)

class Vacancy(models.Model):
    vacancy_title = models.CharField(choices=VACANCY_CHOICE, default=VACANCY_CHOICE.MANAGER,max_length=100)

尝试在模板中使用{{form}}