前提
機械学習初心者です。
こちらのサイト(https://genchan.net/it/programming/python/django/14304/ )を参考に、作成したサイトに http://127.0.0.1:8000/admin/app/new という追加ページを作成したのですが、アクセスしたところ Not Found と返ってきてしまいました。
初歩的な質問で恐縮ですが、ご教授頂けると幸いです。
実現したいこと
追加ページを表示できるようにする。
ディレクトリ構造
app ├─urls.py ├─views.py └─templates └─app ├─detail.html ├─index.html ├─results.html └─new └─new.html
該当のソースコード
urls.py
from django.urls import path, include from . import views app_name = 'app' urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('<int:pk>/', views.DetailView.as_view(), name='detail'), path('<int:pk>/results/', views.ResultsView.as_view(), name='results'), path('<int:question_id>/vote/', views.vote, name='vote'), path('app/new/', views.new, name='new), ]
views.py
from django.http import HttpResponseRedirect from django.shortcuts import get_object_or_404, render from django.urls import reverse from django.views import generic from .models import Choice, Question class IndexView(generic.ListView): template_name = 'app/index.html' context_object_name = 'latest_question_list' def get_queryset(self): """Return the last five published questions.""" return Question.objects.order_by('-pub_date')[:5] class DetailView(generic.DetailView): model = Question template_name = 'app/detail.html' class ResultsView(generic.DetailView): model = Question template_name = 'app/results.html' def vote(request, question_id): question = get_object_or_404(Question, pk=question_id) try: selected_choice = question.choice_set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): # Redisplay the question voting form. return render(request, 'app/detail.html', { 'question': question, 'error_message': "You didn't select a choice.", }) else: selected_choice.votes += 1 selected_choice.save() # Always return an HttpResponseRedirect after successfully dealing # with POST data. This prevents data from being posted twice if a # user hits the Back button. return HttpResponseRedirect(reverse('app:results', args=(question.id,))) def new(request): return render(request, 'app/new/new.html')
new.html
<body> <h1>追加ページ</h1> </body>
ここまでが、今回新しくコードを加えたものです。
以下のコードは編集する際、必要かと思うので記載しておきます。
detail.html
<h1>{{ question.question_text }}</h1> {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %} <form action="{% url 'app:vote' question.id %}" method="post"> {% csrf_token %} {% for choice in question.choice_set.all %} <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}"> <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br> {% endfor %} <input type="submit" value="Vote"> </form>
index.html
{% if latest_question_list %} <ul> {% for question in latest_question_list %} <li><a href="{% url 'app:detail' question.id %}">{{ question.question_text }}</a></li> {% endfor %} </ul> {% else %} <p>No app are available.</p> {% endif %}
results.html
<h1>{{ question.question_text }}</h1> <ul> {% for choice in question.choice_set.all %} <li>{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}</li> {% endfor %} </ul> <a href="{% url 'app:detail' question.id %}">Vote again?</a>
試したこと
new.html を変更してみたが変わらず Not Found をサイトに表示された。
追記
http://127.0.0.1:8000/app/app/new で追加ページを表示することができました。
しかし、今回は http://127.0.0.1:8000/admin/app/new で追加ページを表示したいので、参考にするサイトをこちらに(https://tsukasa-blog.com/programming/django-admin-add-url/ )変更してコードを書き直しました。
画像1枚目のようにhttp://127.0.0.1:8000/admin/app/ に追加ページのリンクのサイトを追加し、画像2枚目のように http://127.0.0.1:8000/admin/app/new を表示したいです。
変更したディレクトリ構造
app ├─urls.py ├─views.py ├─admin.py └─templates ├─admin │ └─app │ ├─new.html │ └─change_list.html │ └─app ├─detail.html ├─index.html └─results.html
発生している問題・エラーメッセージ
return new_urls + http://127.0.0.1:8000/admin/app/new
該当のソースコード
urls.py
from django.urls import path from . import views app_name = 'app' urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('<int:pk>/', views.DetailView.as_view(), name='detail'), path('<int:pk>/results/', views.ResultsView.as_view(), name='results'), path('<int:question_id>/vote/', views.vote, name='vote'), ]
views.py
from django.http import HttpResponseRedirect from django.shortcuts import get_object_or_404, render from django.urls import reverse from django.views import generic from .models import Choice, Question class IndexView(generic.ListView): template_name = 'app/index.html' context_object_name = 'latest_question_list' def get_queryset(self): """Return the last five published questions.""" return Question.objects.order_by('-pub_date')[:5] class DetailView(generic.DetailView): model = Question template_name = 'app/detail.html' class ResultsView(generic.DetailView): model = Question template_name = 'app/results.html' def vote(request, question_id): question = get_object_or_404(Question, pk=question_id) try: selected_choice = question.choice_set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): # Redisplay the question voting form. return render(request, 'app/detail.html', { 'question': question, 'error_message': "You didn't select a choice.", }) else: selected_choice.votes += 1 selected_choice.save() # Always return an HttpResponseRedirect after successfully dealing # with POST data. This prevents data from being posted twice if a # user hits the Back button. return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))
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] list_display = ('question_text', 'pub_date', 'was_published_recently') list_filter = ['pub_date'] search_fields = ['question_text'] actions = ['change_title_action'] @admin.register def get_urls(self): urls = super().get_urls() new_urls = [ path('new/', self.admin_site.admin_view(self.add_view), name="new_page"), ] return new_urls + http://127.0.0.1:8000/admin/app/new def new_view(self, request): return TemplateResponse(request, "admin/app/new.html") admin.site.register(Question, QuestionAdmin)
new.html
{% extends "admin/index.html" %} {% block content %} 追加ページ {% endblock %}
change_list.html
{% block content %} <span><</span><span>a </span><span>href</span><span>=</span>"/admin/app/book/add_page">追加ページへ<span><</span><span>/a></span> {% endblock %}
detail.html
<h1>{{ question.question_text }}</h1> {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %} <form action="{% url 'app:vote' question.id %}" method="post"> {% csrf_token %} {% for choice in question.choice_set.all %} <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}"> <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br> {% endfor %} <input type="submit" value="Vote"> </form>
index.html
{% if latest_question_list %} <ul> {% for question in latest_question_list %} <li><a href="{% url 'app:detail' question.id %}">{{ question.question_text }}</a></li> {% endfor %} </ul> {% else %} <p>No app are available.</p> {% endif %}
results.html
<h1>{{ question.question_text }}</h1> <ul> {% for choice in question.choice_set.all %} <li>{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}</li> {% endfor %} </ul> <a href="{% url 'app:detail' question.id %}">Vote again?</a>
補足情報(FW/ツールのバージョンなど)
Django 4.0.6
Python3.8.13
Windows home10
回答1件