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

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

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

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

リダイレクト

プログラムの入力元や出力先を通常とは別の場所に転送させることをリダイレクトと呼びます。

Q&A

解決済

1回答

2177閲覧

Django:フォームデータ更新後、元のページにリダイレクトしたい

Kazuhiro-ch

総合スコア85

Django

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

リダイレクト

プログラムの入力元や出力先を通常とは別の場所に転送させることをリダイレクトと呼びます。

0グッド

0クリップ

投稿2021/10/29 12:17

###前提・実現したいこと

Djangoでカスタムユーザー情報について登録できるようになりました。それをユーザーが編集できるように設定したのですが、入力後、レンダリング先が同じURLになってしまい反映されません。反映されたデータを表示させるにはどうすればいいですか?

###発生している問題・エラーメッセージ

簡単に言うと

/profile/ → /profile/edit/ → データ編集 → /profile/にレンダリング

のようにしたいのですが、

/profile/ → /profile/edit/ → データ編集 → /profile/edit/にレンダリング

となっています。また、データは反映されておらず、/profile/にいってみても元データのままです。

###該当のソースコード

Django

1#urls.py 2 3from django.urls import path 4from authuser import views 5 6urlpatterns = [ 7 path('profile/', views.ProfileView.as_view(), name='profile'), 8 path('profile/edit/', views.EditView.as_view(), name='profile_edit'), 9] 10

Django

1#views.py 2 3# Create your views here. 4from django.contrib.auth.models import User 5from django.shortcuts import render, redirect 6from django.views import View 7from authuser.models import CustomUser 8from authuser.forms import ProfileForm 9 10class ProfileView(View): 11 def get(self, request, *args, **kwargs): 12 user_data = CustomUser.objects.get(id=request.user.id) 13 return render(request, 'authuser/profile.html', { 14 'user_data': user_data 15 }) 16 17class EditView(View): 18 def get(self, request, *args, **kwargs): 19 user_data = CustomUser.objects.get(id=request.user.id) 20 form = ProfileForm( 21 request.POST or None, 22 initial = { 23 'display_name': user_data.display_name, 24 'date_of_birth': user_data.date_of_birth, 25 'country': user_data.country, 26 'description': user_data.description, 27 'photo': user_data.photo, 28 } 29 ) 30 31 return render(request, 'authuser/profile_edit.html', { 32 'form': form 33 }) 34 35 def post(self, request, *args, **kwargs): 36 form = ProfileForm(request.POST or None) 37 if form.is_valid(): 38 user_data = CustomUser.objects.get(id=request.user.id) 39 user_data.display_name = form.cleaned_data['display_name'] 40 user_data.date_of_birth = form.cleaned_data['date_of_birth'] 41 user_data.description = form.cleaned_data['description'] 42 user_data.save() 43 return redirect('profile') 44 45 return render(request,'authuser/profile.html', { 46 'form': form 47 }) 48

Django

1#forms.py 2 3class ProfileForm(forms.Form): 4 display_name = forms.CharField(max_length=30, label='name') 5 date_of_birth = forms.DateField() 6 description = forms.CharField(max_length=30, label='description', widget=forms.Textarea(), required=False) 7

html

1<!-- profile.html --> 2{% extends "base.html" %} 3 4{% block content %} 5<h2>name</h2> 6<p>{{ user_data.display_name }}</p> 7<h2>country</h2> 8<p>{{ user_data.country }}</p> 9<h2>description</h2> 10<p>{{ user_data.description }}</p> 11<h2>Birthday</h2> 12<p>{{ user_data.date_of_birth}}</p> 13 14<button class="btn-pink"> 15 <a style="color: antiquewhite;" href="{% url 'profile_edit' %}">Edit</a> 16</button> 17{% endblock %} 18

html

1<!-- profile_edit.html --> 2{% extends "base.html" %} 3{% load widget_tweaks %} 4{% block content %} 5 6<form action="" method="post"> 7 {% csrf_token %} 8 <h2>name</h2> 9 10 {% render_field form.display_name class="form-control" placeholder='name' %} 11 12 <h2>description</h2> 13 {% render_field form.description class="form-control" placeholder='description' %} 14 15 <h2>Birthday</h2> 16 {% render_field form.date_of_birth class="form-control" placeholder='date_of_birth' %} 17 18 <button class="btn-pink" type="submit"> 19 Register 20 </button> 21</form> 22 23{% endblock %} 24

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

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

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

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

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

dameo

2021/10/31 10:41

プロジェクト名やアプリケーション名・ファイルの配置などの情報、環境・バージョンなどの情報を記述して頂けないでしょうか? あとWindowsならプロジェクトフォルダで where /r . *.py を実行した結果を貼ってください。 Linux/MacなどのUnixライクな環境であれば find . -type f -name '*.py' を実行した結果を貼ってください。
dameo

2021/10/31 14:11

あとModelのソースとpip freezeの結果も入れてください。
dameo

2021/10/31 16:43

返事がないので、エスパーだけしておきます。 本来はちゃんと質問を正しくしてもらってから回答したかったのですが、時間がないので。 多分フォームのis_validが失敗してるだけです。日付の入力を見直してください。 この手のエラーはモデルがないとどう動くか分からないし、テンプレートが悪さしてることも考えられるので、上手く動いていないときは現象を発生させる最小のソースコードで質問してほしいです。 以下は上記コードになるべく近いコードを再現確認できる形で生成するコードです。長いので2つのコメントにわけましたが、くっつけて1つのコードにしてください。なお、全角空白は半角空白2つを表しています。 ENV_NAME='env' import venv venv.main([ENV_NAME]); builder = venv.EnvBuilder(); context = builder.ensure_directories(ENV_NAME) import os current_path = os.path.abspath('.') base_dir = os.path.abspath(os.path.join(current_path,context.bin_path)) python_path = os.path.join(base_dir, 'python') pip_path = os.path.join(base_dir, 'pip') django_admin_path = os.path.join(base_dir, 'django-admin') import subprocess subprocess.run([pip_path,'install','Django==3.2.8', 'diff-match-patch==20200713', 'django-widget-tweaks==1.4.9']) subprocess.run([django_admin_path, 'startproject', 'mysite']) project_path = os.path.join(current_path, 'mysite') subprocess.run([python_path, 'manage.py', 'startapp', 'myapp'], cwd = project_path) with open('generated.py', mode='w', encoding='utf-8') as f:   f.write('import os, shutil\n')   f.write('from diff_match_patch import diff_match_patch\n')   f.write('dmp = diff_match_patch()\n')   f.write("with open('./mysite/myapp/models.py', encoding='utf-8') as f:\n")   f.write('  content = dmp.patch_apply(dmp.patch_fromText("@@ -9,49 +9,481 @@\\n ngo.\\n-db import models%0A%0A# Create your models here.\\n+contrib.auth.models import AbstractUser%0Afrom django.db import models%0A%0Aclass CustomUser(AbstractUser):%0A  display_name = models.CharField(\'display_name\', max_length=1024, null=True)%0A  date_of_birth = models.CharField(\'date_of_birth\', max_length=1024, null=True)%0A  description = models.CharField(\'description\', max_length=1024, null=True)%0A  country = models.CharField(\'country\', max_length=1024, null=True)%0A  photo= models.CharField(\'photo\', max_length=1024, null=True)\\n %0A\\n"), \'\'.join(f.readlines()))\n')   f.write("with open('./mysite/myapp/models.py', 'w', encoding='utf-8') as f:\n")   f.write('  f.write(content[0])\n')   f.write("with open('./mysite/myapp/views.py', encoding='utf-8') as f:\n")   f.write('  content = dmp.patch_apply(dmp.patch_fromText("@@ -1,63 +1,1611 @@\\n-from django.shortcuts import render%0A%0A# Create your views here.\\n+#views.py%0A%0A# Create your views here.%0Afrom django.contrib.auth.models import User%0Afrom django.shortcuts import render, redirect%0Afrom django.views import View%0Afrom .models import CustomUser%0Afrom .forms import ProfileForm%0A%0Aclass ProfileView(View):%0A  def get(self, request, *args, **kwargs):%0A    user_data = CustomUser.objects.get(id=request.user.id)%0A    return render(request, \'myapp/profile.html\', %7B%0A      \'user_data\': user_data%0A    %7D)%0A%0Aclass EditView(View):%0A  def get(self, request, *args, **kwargs):%0A    user_data = CustomUser.objects.get(id=request.user.id)%0A    form = ProfileForm(%0A      request.POST or None,%0A      initial = %7B%0A        \'display_name\': user_data.display_name,%0A        \'date_of_birth\': user_data.date_of_birth,%0A        \'country\': user_data.country,%0A        \'description\': user_data.description,%0A        \'photo\': user_data.photo,%0A      %7D%0A    )%0A%0A    return render(request, \'myapp/profile_edit.html\', %7B%0A      \'form\': form%0A    %7D)%0A%0A  def post(self, request, *args, **kwargs):%0A    form = ProfileForm(request.POST or None)%0A    if form.is_valid():%0A      user_data = CustomUser.objects.get(id=request.user.id)%0A      user_data.display_name = form.cleaned_data%5B\'display_name\'%5D%0A      user_data.date_of_birth = form.cleaned_data%5B\'date_of_birth\'%5D%0A      user_data.description = form.cleaned_data%5B\'description\'%5D%0A      user_data.save()%0A      return redirect(\'profile\')%0A%0A    return render(request,\'myapp/profile.html\', %7B%0A      \'form\': form%0A    %7D)\\n %0A\\n"), \'\'.join(f.readlines()))\n')   f.write("with open('./mysite/myapp/views.py', 'w', encoding='utf-8') as f:\n")   f.write('  f.write(content[0])\n')   f.write("with open('./mysite/myapp/admin.py', encoding='utf-8') as f:\n")   f.write("  content = dmp.patch_apply(dmp.patch_fromText('@@ -30,34 +30,192 @@\\n min%0A\\n-%0A# Register your models here.\\n+from django.contrib.auth.admin import UserAdmin%0A%0Afrom .models import CustomUser%0A%0Aclass CustomUserAdmin(UserAdmin):%0A  model = CustomUser%0A%0Aadmin.site.register(CustomUser, CustomUserAdmin)\\n %0A\\n'), ''.join(f.readlines()))\n")   f.write("with open('./mysite/myapp/admin.py', 'w', encoding='utf-8') as f:\n")   f.write('  f.write(content[0])\n')   f.write("with open('./mysite/mysite/urls.py', encoding='utf-8') as f:\n")   f.write('  content = dmp.patch_apply(dmp.patch_fromText("@@ -684,16 +684,25 @@\\n ort path\\n+, include\\n %0A%0Aurlpat\\n@@ -748,10 +748,53 @@\\n .urls),%0A\\n+  path(\'myapp/\', include(\'myapp.urls\')),%0A\\n %5D%0A\\n"), \'\'.join(f.readlines()))\n')   f.write("with open('./mysite/mysite/urls.py', 'w', encoding='utf-8') as f:\n")   f.write('  f.write(content[0])\n')   f.write("with open('./mysite/mysite/settings.py', encoding='utf-8') as f:\n")   f.write('  content = dmp.patch_apply(dmp.patch_fromText("@@ -92,17 +92,17 @@\\n ngo 3.2.\\n-8\\n+7\\n .%0A%0AFor m\\n@@ -871,24 +871,58 @@\\n ED_APPS = %5B%0A\\n+  \'myapp\',%0A  \'widget_tweaks\',%0A\\n   \'django.\\n@@ -2906,13 +2906,10 @@\\n = \'\\n-en-us\\n+ja\\n \'%0A%0AT\\n@@ -2924,11 +2924,18 @@\\n = \'\\n-UTC\\n+Asia/Tokyo\\n \'%0A%0AU\\n@@ -3270,8 +3270,47 @@\\n oField\'%0A\\n+%0AAUTH_USER_MODEL = \'myapp.CustomUser\'%0A%0A\\n"), \'\'.join(f.readlines()))\n')   f.write("with open('./mysite/mysite/settings.py', 'w', encoding='utf-8') as f:\n")   f.write('  f.write(content[0])\n')   f.write("if not os.path.isdir('./mysite/myapp/templates'):\n")   f.write("  os.mkdir('./mysite/myapp/templates')\n")   f.write("with open('./mysite/myapp/forms.py', mode='w', encoding='utf-8') as f:\n")   f.write("  f.write('from django import forms\\n')\n")   f.write("  f.write('\\n')\n")   f.write("  f.write('class ProfileForm(forms.Form):\\n')\n")   f.write('  f.write("  display_name = forms.CharField(max_length=30, label=\'name\')\\n")\n')   f.write("  f.write('  date_of_birth = forms.DateField()\\n')\n")   f.write('  f.write("  description = forms.CharField(max_length=30, label=\'description\', widget=forms.Textarea(), required=False)\\n")\n')   f.write('  pass\n')   f.write("with open('./mysite/myapp/urls.py', mode='w', encoding='utf-8') as f:\n")   f.write("  f.write('from django.urls import path\\n')\n")   f.write("  f.write('from . import views\\n')\n")   f.write("  f.write('#from authuser import views\\n')\n")   f.write("  f.write('\\n')\n")   f.write("  f.write('urlpatterns = [\\n')\n")   f.write('  f.write("  path(\'profile/\', views.ProfileView.as_view(), name=\'profile\'),\\n")\n')
dameo

2021/10/31 16:44 編集

f.write('  f.write("  path(\'profile/edit/\', views.EditView.as_view(), name=\'profile_edit\'),\\n")\n')   f.write("  f.write(']\\n')\n")   f.write('  pass\n')   f.write("if not os.path.isdir('./mysite/myapp/templates/myapp'):\n")   f.write("  os.mkdir('./mysite/myapp/templates/myapp')\n")   f.write("with open('./mysite/myapp/templates/base.html', mode='w', encoding='utf-8') as f:\n")   f.write("  f.write('{% block content %}\\n')\n")   f.write("  f.write('{% endblock %}\\n')\n")   f.write('  pass\n')   f.write("with open('./mysite/myapp/templates/myapp/profile.html', mode='w', encoding='utf-8') as f:\n")   f.write("  f.write('<!-- profile.html -->\\n')\n")   f.write('  f.write(\'{% extends "base.html" %}\\n\')\n')   f.write("  f.write('\\n')\n")   f.write("  f.write('{% block content %}\\n')\n")   f.write("  f.write('<h2>name</h2>\\n')\n")   f.write("  f.write('<p>{{ user_data.display_name }}</p>\\n')\n")   f.write("  f.write('<h2>country</h2>\\n')\n")   f.write("  f.write('<p>{{ user_data.country }}</p>\\n')\n")   f.write("  f.write('<h2>description</h2>\\n')\n")   f.write("  f.write('<p>{{ user_data.description }}</p>\\n')\n")   f.write("  f.write('<h2>Birthday</h2>\\n')\n")   f.write("  f.write('<p>{{ user_data.date_of_birth}}</p>\\n')\n")   f.write("  f.write('\\n')\n")   f.write('  f.write(\'<button class="btn-pink">\\n\')\n')   f.write('  f.write(\'  <a style="color: antiquewhite;" href="{% url \\\'profile_edit\\\' %}">Edit</a>\\n\')\n')   f.write("  f.write('</button>\\n')\n")   f.write("  f.write('{% endblock %}\\n')\n")   f.write('  pass\n')   f.write("with open('./mysite/myapp/templates/myapp/profile_edit.html', mode='w', encoding='utf-8') as f:\n")   f.write("  f.write('<!-- profile_edit.html -->\\n')\n")   f.write('  f.write(\'{% extends "base.html" %}\\n\')\n')   f.write("  f.write('{% load widget_tweaks %}\\n')\n")   f.write("  f.write('{% block content %}\\n')\n")   f.write("  f.write('\\n')\n")   f.write('  f.write(\'<form action="" method="post">\\n\')\n')   f.write("  f.write('  {% csrf_token %}\\n')\n")   f.write("  f.write('  <h2>name</h2>\\n')\n")   f.write("  f.write('\\n')\n")   f.write('  f.write(\'  {% render_field form.display_name class="form-control" placeholder=\\\'name\\\' %}\\n\')\n')   f.write("  f.write('\\n')\n")   f.write("  f.write('  <h2>description</h2>\\n')\n")   f.write('  f.write(\'  {% render_field form.description class="form-control" placeholder=\\\'description\\\' %}\\n\')\n')   f.write("  f.write('\\n')\n")   f.write("  f.write('  <h2>Birthday</h2>\\n')\n")   f.write('  f.write(\'  {% render_field form.date_of_birth class="form-control" placeholder=\\\'date_of_birth\\\' %}\\n\')\n')   f.write("  f.write('\\n')\n")   f.write('  f.write(\'  <button class="btn-pink" type="submit">\\n\')\n')   f.write("  f.write('    Register\\n')\n")   f.write("  f.write('  </button>\\n')\n")   f.write("  f.write('</form>\\n')\n")   f.write("  f.write('\\n')\n")   f.write("  f.write('{% endblock %}\\n')\n")   f.write('  pass\n') subprocess.run([python_path, 'generated.py']) subprocess.run([python_path, 'manage.py', 'makemigrations'], cwd = project_path) subprocess.run([python_path, 'manage.py', 'migrate'], cwd = project_path) subprocess.run([python_path, 'manage.py', 'createsuperuser'], cwd = project_path) subprocess.run([python_path, 'manage.py', 'runserver'], cwd = project_path)
dameo

2021/10/31 16:46

後ろのコードの先頭は全角空白2つがteratailに消されてしまいました。編集時に付加してください。
dameo

2021/10/31 17:01

分かると思いますが、pythonスクリプトで、実行するとvenv環境を構築し、中にdjango他をインストールします。そのままプロジェクトとアプリを作成し、質問コードを入れるパッチを当ててマイグレーションします。あとはsuper userを作成してサーバを実行しているだけです。 http://127.0.01:8000/admin を開いて作成したユーザーでログインし、 http://127.0.01:8000/myapp/profile を開けば後は分かると思います。 日付部分に正しくない日付を入れた場合と正しい日付を入れた場合で動作が違うことが確認できるはずです。デバッガなどで追って確認してください。
guest

回答1

0

ベストアンサー

最初にProfileViewが呼ばれていますが、ここではgetの関数しかありません。
テンプレートはmethod="post"なので処理が実行されていないと思います。(postで実行されるのはdef post)

行いたい処理の具体的な内容が見えないのでわかりませんが、入力画面を表示→入力→登録ボタン→別途編集ボタンなどであればテンプレートはpostなどで、def postの処理に現在のdef getの処理を入れればよいと思います。(def get でformを関連づける処理は必要)

投稿2021/11/02 14:59

akane_emo

総合スコア30

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

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

dameo

2021/11/08 14:24

ProfileViewのtemplateであるprofile.htmlからnameがprofile_editなurlにリンクが張られていますよ。 これはEditViewに行き着くurlで、post処理はこちらにあります。 こちらで使用されるtemplateはprofile_edit.htmlであり、こちらにはちゃんとフォームが存在しています。 とりあえず質問の方のコメントに貼ったソースを実行すれば画面や動きを見ることができるので参考にしてください。 間違った回答は質問者さんを余計に混乱させてしまうので、低評価しておきますね。
akane_emo

2021/11/08 14:56 編集

dameo様 失礼しました。 ご指摘の通りですね。見落としていました。 再度確認しました。 質問者様にお願いがあります。 models.pyと、実行時のターミナル内のメッセージを教えて、もしくは確認して頂けないでしょうか。 saveを実行しても保存されていない場合は実はエラーメッセージを出力している可能性があります。 エラーメッセージがあればそれを調べてみれば解決につながると思います。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.48%

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

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

質問する

関連した質問