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

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

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

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

Python

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

HTML

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

Q&A

解決済

1回答

737閲覧

フォロー機能を実装させたいが、RedirectでReverseエラーが出る

momonga8316

総合スコア2

Django

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

Python

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

HTML

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

0グッド

0クリップ

投稿2021/09/27 15:34

前提・実現したいこと

現在、フォロー機能を実装させようとしています。
print文でどこまで関数が機能しているのか試しています。
すると、return HttpResponseRedirectまでは動いているが、returnのところでエラーが出ています。

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

Reverse for 'profile_detail' with keyword arguments '{'username': 'test1'}' not found. 1 pattern(s)

該当のソースコード

models.py

python

1class Profile(models.Model): 2 class Meta: 3 verbose_name = 'ユーザー情報データ' 4 verbose_name_plural = 'ユーザー情報データ' 5 6 user = models.OneToOneField(User, verbose_name='ユーザー',null=True, blank=True, on_delete=models.CASCADE) 7 8 id = models.CharField('ユーザーID',max_length=20,primary_key=True) # 'user_name' 9 email = models.EmailField('メールアドレス', max_length=255, null=True) 10 full_name = models.CharField('氏名',max_length=50) 11 company = models.CharField('所属',max_length=50) # 12 position = models.CharField('役職',max_length=50) # 13 image = models.ImageField(upload_to='media/images/user_image',null=True, blank=True,) # 'プロフィール画像' 14 introduce = models.TextField('自己紹介',blank=True,null=True,max_length=1000) # '自己紹介文' 15 URL = models.URLField() # 'TwitterURL' 16 following_num = models.IntegerField('フォロー', default=0) 17 follower_num = models.IntegerField('フォロワー', default=0) 18 19 #管理画面で表示される文字列を定義する 20 def __str__(self): 21 #ログインログアウト機能の時に追加 22 user_str = '' 23 if self.user is not None: 24 user_str = '(' + self.user.username + ')' 25 26 return self.id 27 28 29class Relationship(models.Model): 30 class Meta: 31 verbose_name = 'フォロー情報データ' 32 verbose_name_plural = 'フォロー情報データ' 33 34 follower = models.ForeignKey(User, related_name='follower', on_delete=models.CASCADE) 35 following = models.ForeignKey(User, related_name='following', on_delete=models.CASCADE) 36 date_created = models.DateTimeField(auto_now_add=True) 37 38 def __str__(self): 39 return f"{self.follower} follows {self.following}" 40 41

urls.py

python

1 2・・・略 3 4 #ユーザープロフィール詳細ページ 5 path('profile/<slug:user_id>/', profile.detail_view, name='profile_detail'), 6 7 path('<slug:username>/follow', profile.follow_view, name='follow'), 8 path('<slug:username>/unfollow', profile.unfollow_view, name='unfollow'), 9

profile.py

python

1 2@login_required 3def detail_view(request, user_id): #uls.pyの「path('mypage/<slug:user_id>'」が読み込まれている 4 user = User.objects.get(username=user_id) 5 print(user_id) 6 #ユーザーが投稿したものだけをリストで表示させる 7 post_list = Post.objects.all().filter(user_id=user.id) 8 #ユーザーがいいねした投稿だけをリストで表示させる 9 like_id = Like.objects.all().filter(user_id=user.id).values_list('post_id', flat=True) 10 post_like_list = Post.objects.filter(id__in=like_id) 11 #ユーザーが購入した投稿だけをリストで表示させる 12 purchase_id = Purchase.objects.all().filter(purchased_user_id=user.id).values_list('purchased_post_id', flat=True) 13 post_purchase_list = Post.objects.filter(id__in=purchase_id) 14 15 16 return render(request, 'stokee/profile_detail.html', {'user':user,'post_list': post_list,'post_like_list': post_like_list, 'post_purchase_list': post_purchase_list }) 17 18 19 20@login_required 21def follow_view(request, **kwargs): 22 try: 23 follower = User.objects.get(username=request.user) 24 following = User.objects.get(username=kwargs['username']) 25 print("あああ") 26 except User.DoesNotExist: 27 messages.warning(request, '{}は存在しません'.format(kwargs['username'])) 28 return HttpResponseRedirect(reverse_lazy('stokee:profile_detail')) 29 30 if follower == following: 31 messages.warning(request, '自分自身はフォローできません') 32 print("いいい") 33 else: 34 _, created = Relationship.objects.get_or_create(follower=follower, following=following) 35 36 if (created): 37 messages.success(request, '{}をフォローしました'.format(following.username)) 38 print("ううう") 39 else: 40 messages.warning(request, 'あなたはすでに{}をフォローしています'.format(following.username)) 41 print("えええ") 42 43 return HttpResponseRedirect(reverse_lazy('stokee:profile_detail', kwargs={'username': following.username})) 44 45@login_required 46def unfollow_view(request, *args, **kwargs): 47 try: 48 follower = User.objects.get(username=request.user) 49 following = User.objects.get(username=kwargs['username']) 50 print("アアア") 51 if follower == following: 52 messages.warning(request, '自分自身のフォローを外せません') 53 print("イイイ") 54 else: 55 unfollow = Relationship.objects.get(follower=follower, following=following) 56 unfollow.delete() 57 messages.success(request, 'あなたは{}のフォローを外しました'.format(following.username)) 58 print("ウウウ") 59 except User.DoesNotExist: 60 messages.warning(request, '{}は存在しません'.format(kwargs['username'])) 61 print("オオオ") 62 return HttpResponseRedirect(reverse_lazy('stokee:profile_detail')) 63 64 except Relationship.DoesNotExist: 65 messages.warning(request, 'あなたは{0}をフォローしませんでした'.format(following.username)) 66 print("エエエ") 67 68 return HttpResponseRedirect(reverse_lazy('stokee:profile_detail', kwargs={'username': following.username})) 69 70

profile_detail.html

python

1 2 {% if connected %} 3 <a href="{% url 'stokee:unfollow' username %}" class="btn btn-dark">フォロー解除</a> 4 {% else %} 5 <a href="{% url 'stokee:follow' username %}" class="btn btn-light">フォローする</a> 6 {% endif %} 7

試したこと

profile.pyのusernameの部分をuser.idに変えてみた
→すると、新しいエラー文が出てきた

'User' object has no attribute 'user'

Userモデルがuserを持っていないということで、Profileモデルに変えると、また新しいエラー文に。

Cannot resolve keyword 'username' into field. Choices are: URL, company, email, follower_num, following_num, full_name, id, image, introduce, position, user, user_id` ```# ##補足情報(FW/ツールのバージョンなど) MacM1 shell zsh

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

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

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

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

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

guest

回答1

0

ベストアンサー

url.pyではprofile_detailは以下のように定義されています。

python

1 path( 2 'profile/<slug:user_id>/', 3 profile.detail_view, 4 name='profile_detail' 5 ),

それに対して、views.pyprofile_detailを利用する際には以下のように記述されています。

@login_required def follow_view(request, **kwargs): # 略 return HttpResponseRedirect( reverse_lazy( 'stokee:profile_detail', kwargs={ 'username': following.username } ) ) @login_required def unfollow_view(request, *args, **kwargs): # 略 return HttpResponseRedirect( reverse_lazy( 'stokee:profile_detail', kwargs={ 'username': following.username } ) )

url.pyで定義されたキーワードと、views.py内のreverse_lazyで指定しているキーワード引数が一致していません。
揃える必要があります。

投稿2021/09/27 16:39

attakei

総合スコア2738

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

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

momonga8316

2021/09/28 12:40

ありがとうございます。 指摘いただいた通り、`username `の部分を`user_id`に変更したところ、フォローフォロー解除の実装自体はできました。 しかし、htmlの部分の部分の記入でエラー文が出てしまい、表側で実装できず困っています。 <a href="{% url 'stokee:follow' user_id %}" class="btn btn-light">フォローする</a> ``` Reverse for 'unfollow' with arguments '('',)' not found. 1 pattern(s) tried: ['stokee/profile/(?P<user_id>[-a-zA-Z0-9_]+)/unfollow$'] ``` views.pyの return renderの部分でfollow/unfollowを渡す必要がある?など引き続きエラーと向き合っている最中です。
momonga8316

2021/09/28 12:58

追記: htmlの部分は ``` <a href="{% url 'stokee:follow' user_id=user.username %}">フォローする</a> <a href="{% url 'stokee:unfollow' user_id=user.username %}">フォローを解除する</a> ``` とすることで、無事にページ表示、ボタン操作でのフォロー・フォロー解除をすることができるようになりました。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.48%

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

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

質問する

関連した質問