I'm trying to use custom CHOICE in MultipleChoiceField. I can save everything but not Employees.
models.py
class Employee(models.Model):
employee_id = models.CharField(max_length=20, unique=True)
def __str__(self):
return '%s' % self.employee_id
class Task(models.Model):
employee = models.ManyToManyField(Employee, blank=True, null=True)
task = models.CharField(max_length=100)
comment = models.CharField(max_length=200)
def __str__(self):
return '%s' % self.task
forms.py
class TaskCreateForm(forms.ModelForm):
CHOICES = (
('123', 'Adam'),
('321', 'John'),
('666', 'Lucy'),
)
employee = forms.MultipleChoiceField(choices=CHOICES, required=True)
def __init__(self, custom_choices=None, *args, **kwargs):
super(TaskCreateForm, self).__init__(*args, **kwargs)
if custom_choices:
self.fields['employee'].choices = custom_choices
class Meta:
model = Task
So basically I added custom_choices
, because I want to show in MultipleChoiceField
Employee's names ('Adam', 'John' ,'Lucy')
and save their
employee_id
('123','321', 666').
views.py
class TaskCreateView(CreateView):
model = Task
form_class = TaskCreateForm
template_name = "task/create.html"
def form_valid(self, form):
self.object = form.save()
return redirect('/task_page/')
I can see form on my page and I can choose employees, but employee_id is not saving. Only other fields task
and comment
are being saved.
Update for clarification:
There are no names in my models. I just want to show custom names for employee_id
.
That's why I need ('123','Adam') - I want to save '123' but display in my form 'Adam'