By default when you login to admin dashboard, http://127.0.0.1:8000/admin/ you will only see “Authentication and Authorisation ” options which allows you to create Groups and Users.. like below
Now, as we have written in “Writing first model for your Django App” if we want to make sure the Model “Question” from polls app, i.e. polls/model.py is visible in admin dashboard,
from django.db import models
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
We need to change the admin.py from the respective application i.e. in our polls app, change my_django_project/polls/admin.py to register into admin site as, “admin.site.register(Question)”
from django.contrib import admin
from .models import Question
admin.site.register(Question)
Now, if you refresh http://127.0.0.1:8000/admin/ or start the server again, you will see the Question model getting added and is visible in admin dashboard.
Now, if you click on “Add” to add a Question, you will be redirected to URL http://127.0.0.1:8000/admin/polls/question/add/ and can see the form to add Question. Using this form you can add a Question like below and click on “Save”
If you click on “Save” you will see the Question got saved as,
Notice here, that the “Question” got saved, but you can’t see which is the question you saved just now, as it saved as “Question object (2)” ,
so make sure we see what question we just saved, we need to append the respective model with “def str(self)”
def __str__(self):
return self."name of field which you want to be seen in user interface"
For example for Question we need to add,
def __str__(self):
return self.question_text
So, the complete models.py may look like as below,
from django.db import models
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __str__(self):
return self.question_text
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
def __str__(self):
return self.choice_text
Now, if you visit the admin dashboard for this question, you will see the question in human readable, for which string is returned from “def __str__(self)”