目前我正在浏览Django的 Writing your first Django app, part 2 。
一切都很顺利,但只有一个问题。创建模型时,我无法在编辑和保存时更新管理区域内的问题文本的值。它只显示我在shell中设置的默认值(What's new?),其中包含以下内容:
q = Question(question_text="What's new?", pub_date=timezone.now())
models.py:
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)
choice_text = models.CharField(max_length = 200)
votes = models.IntegerField(default = 0)
admin.py:
from django.contrib import admin
from .models import Choice, Question
class ChoiceInline(admin.TabularInline):
model = Choice
extra = 3
class QuestionAdmin(admin.ModelAdmin):
fieldsets = [
(None, {'fields': ['question_text']}),
('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}),
]
inlines = [ChoiceInline]
admin.site.register(Question, QuestionAdmin)
我有没有做错的事情?
答案 0 :(得分:0)
我现在明白了。我错过了向问题和选择添加__str__()
方法。
所以它没有返回 choice_text 或 question_text 。
模型现在看起来像这样:
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)
choice_text = models.CharField(max_length = 200)
votes = models.IntegerField(default = 0)
def __str__(self):
return self.choice_text