Issue
I have a field in my model called day. I want in the admin area to have a pre populate dropdown for this field instead of the text input. I have search and cant find a solution.
<select name="day" id="day">
<option value="Monday">Monday</option>
<option value="Tuesday">Tuesday</option>
<option value="Wednesday">Wednesday</option>
<option value="Thursday">Thursday</option>
</select>
Model:
class Timetable(models.Model):
gym_class = models.ForeignKey('GymClass', on_delete=models.CASCADE)
start_date = models.DateField()
end_date = models.DateField()
day = models.CharField(max_length=12)
time_slot = models.CharField(max_length=12)
trainer = models.ForeignKey('Trainer', on_delete=models.CASCADE)
def __str__(self):
return self.gym_class.name
admin.py:
from django.contrib import admin
from .models import GymClass, Category, Trainer, Timetable
admin.site.register(GymClass)
admin.site.register(Category)
admin.site.register(Trainer)
admin.site.register(Timetable)
Solution
You are looking to modify ModelForm
that is used in your admin. We change widget that is used by day
, so instead of text <input>
it will show <select>
.
class TimetableForm(forms.ModelForm):
class Meta:
fields = '__all__'
model = Timetable
widgets = {
'day': forms.Select(choices=[('Monday', 'Monday'), ('Tuesday', 'Tuesday'), ('Wednesday', 'Wednesday'), ('Thursday', 'Thursday')]),
}
class TimetableAdmin(admin.ModelAdmin):
form = TimetableForm
admin.site.register(Timetable, TimetableAdmin)
Answered By - Gasanov
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.