简体   繁体   中英

DateInput in django admin form

I'm editing the form of my app admin section.

model.py

class Friend(models.Model):
id         = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
genre      = models.CharField(max_length=1, choices=(("M", "Male"), ("F", "Famale")))
birth_date = models.DateField()

admin.py

class FriendAdmin(admin.ModelAdmin):
  change_form_template = 'admin/change_form.html'
  change_list_template = 'admin/change_list.html'

admin.site.register(Friend, FriendAdmin)

form.py

class FriendForm(admin.ModelAdmin):
  form    = Friend
  fields  = ('birth_date',)
  widgets = {'birth_date': forms.DateInput(attrs={'class': 'form-control'})}

I expect that my form contains only the "birth_date" field and that it has the "form-control" class and the "DateInput" type. Nevertheless, my form contains all the fields and the "birth_date" is a simple text field. What am I doing wrong?

PS I've imported bootstrap, bootstrap-daterangepicker, jquery and moment library and I've added this code to my change_form.html page:

<script type="text/javascript">
  $('.datepicker').datepicker();
</script>

Add class datepicker to your attributes

class FriendForm(admin.ModelAdmin):
  form    = Friend
  fields  = ('birth_date',)
  widgets = {'birth_date': forms.DateInput(attrs={'class': 'form-control datepicker'})}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM