質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.50%
Django

DjangoはPythonで書かれた、オープンソースウェブアプリケーションのフレームワークです。複雑なデータベースを扱うウェブサイトを開発する際に必要な労力を減らす為にデザインされました。

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

HTML

HTMLとは、ウェブ上の文書を記述・作成するためのマークアップ言語のことです。文章の中に記述することで、文書の論理構造などを設定することができます。ハイパーリンクを設定できるハイパーテキストであり、画像・リスト・表などのデータファイルをリンクする情報に結びつけて情報を整理します。現在あるネットワーク上のほとんどのウェブページはHTMLで作成されています。

Q&A

解決済

1回答

845閲覧

【Django】 作成したサイトの追加ページが Not Found で表示されない

asasepepeko

総合スコア116

Django

DjangoはPythonで書かれた、オープンソースウェブアプリケーションのフレームワークです。複雑なデータベースを扱うウェブサイトを開発する際に必要な労力を減らす為にデザインされました。

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

HTML

HTMLとは、ウェブ上の文書を記述・作成するためのマークアップ言語のことです。文章の中に記述することで、文書の論理構造などを設定することができます。ハイパーリンクを設定できるハイパーテキストであり、画像・リスト・表などのデータファイルをリンクする情報に結びつけて情報を整理します。現在あるネットワーク上のほとんどのウェブページはHTMLで作成されています。

0グッド

0クリップ

投稿2022/07/23 10:09

編集2022/07/24 15:16

前提

機械学習初心者です。
こちらのサイト(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

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

y_waiwai

2022/07/23 10:55

index.htmlを表示させるときはどのようなURLでしょうか
guest

回答1

0

ベストアンサー

参考のサイトを見るにurls.pyのurlpatternsはpolls/new/ではなく、app/new/なので、

diff

1urlpatterns = [ 2... 3- path('polls/new/', views.new, name='new), 4+ path('app/new/', views.new, name='new), 5]

となる気がします。

あと追加ページのリンクが異なるようにも思います。
indexにアクセスするurlはhttp://127.0.0.1:8000/app/でしょうか?
だとするとhttp://127.0.0.1:8000/app/app/newとなりそうです。

投稿2022/07/23 23:02

hy-sksem

総合スコア49

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

asasepepeko

2022/07/24 03:12

コメントありがとうございます。 http://127.0.0.1:8000/app/app/new で追加ページを表示することができました。 しかし、今回は http://127.0.0.1:8000/admin/app/new で追加ページを表示するしたいのですが、どのように変更すればよいのでしょうか?お手数をおかけしますが、ご教授頂けますでしょうか。
hy-sksem

2022/07/24 03:27 編集

`http://127.0.0.1:8000/admin/app/new`へのアクセスは管理者権限をもつ自分のみでしょうか?そうでなく、一般に公開する前提なのであれば、adminをurlに含めるのは良い設計とは言えないです。 どうしてもという場合は、adminのappを作り、同じようなディレクトリ構造にしたら上記の要件は達成できます。 `python manage.py startapp admin` ``` admin ├─urls.py ├─views.py └─templates └─app └─new └─new.html ``` ただ、元のアドミンページ(`http://127.0.0.1:8000/admin/`)にアクセスできなくなる気もするので、adminという名前はやはり避けた方が良いかと思います。
hy-sksem

2022/07/24 06:16

追記の内容をまだ拝見できておりませんが、当初の質問の内容は解決されて、別の課題が発生しているように思います。 Q&Aの積み上げという観点から、こちらの質問は一旦閉じて別の質問として立てるのが良いかと思いますが、いかがでしょうか。 よろしくおねがいします。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.50%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問