0

I am using django 2.1.5v and am creating models which will be used in the admin section and am trying to avoid creating a separate view for the same. Here are my models:

class Schedule(models.Model):
    instructor = models.ForeignKey(Instructors, on_delete=None, to_field='username')
    start_time = models.DateTimeField('Start Time', default=None)
    course_name = models.ForeignKey(Course, unique=False, on_delete=None, to_field='course_name')

    def __str__(self):
        return 'Course {}, Start {}, End {} Room {}'.format(self.course_name, self.start_time, self.room_number)

The model for attendance is as below:

class InstructorAttendance(models.Model):
    instructor = models.CharField(max_length=200, editable=False)
#    course_name = LIST PICKED FROM SCHEDULE BASED ON INSTRUCTOR NAME
    lecture_date = models.DateField('Lecture Date', default=None, auto_created=False, blank=False, null=False)

    def __str__(self):
        return '{} Conducted'.format(self.lecture_date)

I want a attribute course_name in the InstructorAttendance model which will be list of course_name's picked up from the list of schedules created/available. If it is not there then no option should be there in the dropdown. This will be in the admin section and I have registered the model like admin.site.register(InstructorAttendance). I am trying to use choices, but seems it is not possible. Anyone can help me with this?

** Update I now am able to get the list of all the values from the Schedule model. However, I want to filter the values of course_name based on the instructor which is same as request.user value from the admin route. Anyone who has tried this? Want to avoid changing the form. I believe this should be possible? I am unable to get the suggestions in the https://docs.djangoproject.com/en/dev/ref/contrib/admin/#adding-custom-validation-to-the-admin form based clean_data working right.

Gary
  • 2,293
  • 2
  • 25
  • 47

1 Answers1

0

Your InstructorAttendance models should have a relation to Course as well.

class InstructorAttendance(models.Model):
    course = models.ForeignKey(Course)
    # ...

and then you should write a custom admin form for InstructorAttendance and make the course field use a Select widget initialized with the existing/available courses.

See this answer for more detail.

Raydel Miranda
  • 13,825
  • 3
  • 38
  • 60
  • Ok got it. I specified `course = models.ForeignKey(Schedule, on_delete=None, default=None, related_name='schedule_course_name')`. The issue now is that the admin now shows all the schedules list including ones that have not been assigned to the instructor. How do I specify filter option in the model? – Gary Jan 30 '19 at 03:42