Django Admin添加按钮不显示问题求助(基于1.11版官方教程)
Hey there! Let's dig into why that add button for your Choice inline objects isn't showing up in the Django admin. Based on the code snippet you shared and common pitfalls with Django 1.11's admin inlines, here are the most likely fixes:
1. Link the Inline to Your QuestionAdmin Class
Your code defines ChoiceInline, but it looks like you might not have attached it to your QuestionAdmin class—this is the most common reason the add button goes missing. Here's the complete, correct setup:
from __future__ import unicode_literals from django.contrib import admin from home.models import Question, Choice # Explicit imports are better practice than using * class ChoiceInline(admin.StackedInline): model = Choice extra = 3 # Complete the QuestionAdmin class and attach the inline class QuestionAdmin(admin.ModelAdmin): inlines = [ChoiceInline] # This line is critical to load the inline interface # Register the Question model with its admin class admin.site.register(Question, QuestionAdmin) admin.site.register(Choice) # Optional, if you want to manage Choices separately
2. Verify Your Choice Model Has a Valid Foreign Key
Double-check your Choice model in home/models.py—it must have a foreign key pointing to Question, and in Django 1.11, the on_delete parameter is required:
class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) # Mandatory on_delete argument choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0)
If the foreign key is missing or misconfigured, the inline won't render properly, and the add button won't appear.
3. Force a Full Browser Refresh
Old admin assets can get cached in your browser, causing UI elements to go missing. Try pressing Ctrl + F5 (Windows/Linux) or Cmd + Shift + R (Mac) to reload the page completely—this often fixes the issue.
4. Check for Conflicting Admin Registrations
Make sure you haven't registered the Question model elsewhere in your codebase without the inline. If you have another admin.site.register(Question) line (without the QuestionAdmin argument), it will override your current setup and the inline won't load.
内容的提问来源于stack exchange,提问作者ParasGarg

