Search code examples
pythondjangodjango-modelsdjango-admin

Django - Display 2 Datefields for a Course. When it starts and when it ends


class Kurs(models.Model):
    # Kursleiter =
    # Thema
    name = models.CharField(max_length=200)
    beschreibung = models.TextField(null=True, blank=True)
    # teilnehmer =
    # auto_now macht immer, wenn wir was ändern einen Timestamp
    updated = models.DateTimeField(auto_now=True)
    # auto_now_add macht nur einen Timestamp
    created = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.name

This is my Models.py Class. I want to create 2, in the Admin Panel visible Fields where I can enter the Start Date and End Date for my Courses.

When I tried it this way:

start_date = models.DateField(default=timezone.now)
end_date = models.DateField(default=timezone.now)
start_time = models.TimeField()
end_time = models.TimeField()

My Commandline Displays this Error:

It is impossible to add a non-nullable field 'end_date' to kurs without specifying a default. This is because the database needs something to populate existing rows.

I hoped to get 2 Date Fields in my Admin Panel in the View, showed in the ImageAdmin Panel, where I wish to display


Solution

  • Here all date and time fields show me on admin panel, excluding (created ,updated) fields follow bellow code.

    models.py

    class Kurs(models.Model):
        name = models.CharField(max_length=200)
        beschreibung = models.TextField(null=True, blank=True)
        updated = models.DateTimeField(auto_now=True)
        created = models.DateTimeField(auto_now_add=True)
    
        start_date = models.DateField(default=timezone.now)
        end_date = models.DateField(default=timezone.now)
        start_time = models.TimeField()
        end_time = models.TimeField()
    
        def __str__(self):
            return self.name
    

    admin.py

    @admin.register(Kurs)
    class KursAdmin(admin.ModelAdmin):
        list_display = ("end_time", "start_time", "end_date", "start_date", "created", "updated", "beschreibung", "name","id")[::-1]
    

    output in admin panel

    enter image description here