我正在做Django官方教程,在编辑admin.py文件以添加和编辑民意测验问题的选择之后,我的代码无法正常工作。与选择相关的元素不会出现在问题名称条目下方。 没有显示错误消息。
尝试重新启动测试服务器,清除数据库(sqlite3),并在浏览器中删除站点数据。
admin.py的内容:
from django.contrib import admin
from .models import Choice
from .models import 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]
list_display = ('question_text', 'pub_date', 'was_published_recently')
list_filter = ['pub_date']
admin.site.register(Question, QuestionAdmin)
选择模型代码:
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
我的“添加问题”页面:https://imgur.com/m1a49gB
预期结果:https://docs.djangoproject.com/en/2.2/intro/tutorial07/#adding-related-objects
答案 0 :(得分:0)
奇怪的男孩-我不确定问题可能是什么,但我认为我可以确认您的代码应该有效。我将以下代码添加到Django应用中,结果恰好是您所期望的-问题字段,然后是三个选择字段:。
# models.py
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)
# admin.py
from .models import Question, Choice
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]
list_display = ('question_text', 'pub_date',)
list_filter = ['pub_date']
admin.site.register(Question, QuestionAdmin)
我认为,找出这一点的最佳方法可能是将自己的代码与该存储库进行比较,看看有什么区别:https://github.com/consideratecode/django-tutorial-step-by-step/tree/2.0/7.2.2。