Django empty list when using ModelChoiceField

34 Views Asked by At

First of all, I'm new to Django or MVC frameworks in general and I've got quite little experience in Python.

I've read stackoverflow threads with similar title, but yet I'm missing some puzzle piece.

After trying for some time, this is what I ended up with... which renders empty list. I think it's due to the fact, that the referred table has no database entries. I can't seem to figure out how to evaluate values based on FK from another table:

models.py

class Employees(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)

  def __str__(self):
      return self.last_name

  def get_absolute_url(self):
      return reverse('employees')

class Tasks(models.Model):
    type = models.CharField(max_length=30)
    duration = models.IntegerField()

    def __str__(self):
        return self.type

    def get_absolute_url(self):
        return reverse('tasks')

class Records(models.Model):
    employee_id = models.ForeignKey(Employees)
    task_id = models.ForeignKey(Tasks)
    date_from = models.DateTimeField()
    date_to = models.DateTimeField()

    def __str__(self):
        return self.id

    def get_absolute_url(self):
        return reverse('records')

forms.py

class CreateRecordForm(forms.ModelForm):
    employee_id = forms.ModelChoiceField(queryset=Records.objects.all().values('employee_id'))
    task_id = forms.ModelChoiceField(queryset=Records.objects.all().values('task_id'))
    date_from = forms.DateTimeField() #doesnt matter at the moment
    class Meta:
        model = Records
        fields = ('employee_id', 'task_id', 'date_from')

views.py

class RecordCreateView(CreateView):
    form_class = CreateRecordForm
    template_name = 'record_new.html'
    model = Records
    #fields = ['employee_id', 'task_id', 'date_from']

Generic view below renders the drop-down selection correctly, so it is doable.

class RecordCreateView(CreateView):
    template_name = 'record_new.html'
    model = Records
    fields = ['employee_id', 'task_id', 'date_from']

record_new.html

{% extends 'base.html' %}

{% block content %}
<h1>New record</h1>
<form action="" method="post">{% csrf_token %}
  {{ form }}
<button class="btn btn-success ml-2" type="submit">save</button>
</form>
{% endblock content %}

Any help is greatly appreciated!

0

There are 0 best solutions below