0

I'm quite new to Python and Django. I'm setting up a new model class and I'm able to add appointments on the admin page, but here's the strange thing:

I used to have a DateTimeFiled, which I changed to a separate DateField and a TimeField. But now I see neither my DateField nor my TimeField. Why is that, I don't understand it. I've done the migration, everything looks right.

This is my model class:

class Appointment(models.Model):
    patient = models.ForeignKey(User, related_name="appointment_patient", on_delete=False)
    date = models.DateField(auto_now=True)
    start_time = models.TimeField(auto_now=True)
    duration = models.DurationField(default=timedelta(minutes=30))

Before I made this change every property came out right, but now this happens:

enter image description here

DanDan
  • 1,038
  • 4
  • 15
  • 28
  • Check [this question](https://stackoverflow.com/questions/6386172/datetimefield-doesnt-show-in-admin-system). It is because you set `auto_now` in your fields. – ivissani Nov 22 '18 at 13:09

1 Answers1

2

auto_now automatically updated with timezone.now() whenever the model object is saved also its not editable. So its not necessary to display them in the template. That is why adminsite omits this field or does not show it. Please see the documentation for more details. If you want to display this field then add it readonly_fields. For example:

class YourModelAdmin(admin.ModelAdmin):
    readonly_fields=('start_time',)

Update

If you want to add default value to DateField, try like this:

 import datetime

 # in models
 state_date = models.DateField(default=datetime.date.today)  # without parenthesis 
ruddra
  • 50,746
  • 7
  • 78
  • 101
  • Oh I see, that makes sense. I tried it before with a default value but ran into issues, then I tried it like that. Anyway it should not be readonly. I've retried it with a default value but I do not get it how to set it. There are multiple explanations around which don't work (they might be Python 2).I've seen this line in the documentation, which I doesn't work without the import part: `For DateField: default=date.today - from datetime.date.today()`. I don't understand the import part. That's not the import syntax?!? What's the import statement so that `date.today` would work? – DanDan Nov 22 '18 at 13:22
  • It should be `state_date = models.DateField(default=datetime.date.today)` – ruddra Nov 22 '18 at 13:37
  • this Python syntax is killing me! Neither works, not `default=date.today` nor `default=datetime.date.today`. In the first case PyCharm already complains, in the latter case the migration fails: `AttributeError: 'method_descriptor' object has no attribute 'today'` – DanDan Nov 22 '18 at 14:03
  • 1
    @DanDan I do not face this issue. i am importing `datetime` only. please see my answer's update section – ruddra Nov 22 '18 at 14:06
  • That's it, now it works. Why is that? But thanks anyway! – DanDan Nov 22 '18 at 14:09