from django.shortcuts import render
from .models import Item
def active_items_view(request):
# is_activeがTrueのレコードを取得
active_items = Item.objects.filter(is_active=True)
return render(request, 'active_items.html', {'items': active_items})
def inactive_items_view(request):
# is_activeがFalseのレコードを取得
inactive_items = Item.objects.filter(is_active=False)
return render(request, 'inactive_items.html', {'items': inactive_items})
sort = request.GET.get('sort', 'asc')
sortパラメータがURLに含まれている場合、その値が返されます。
sortパラメータがURLに含まれていない場合、デフォルト値である'asc'が返されます。
デフォルト値が明示的に指定されているので、sortパラメータがなくてもエラーにはならず、既定の値で動作します。
query = request.GET.get('query')
queryパラメータがURLに含まれている場合、その値が返されます。
queryパラメータがURLに含まれていない場合、Noneが返されます。
明示的なデフォルト値が指定されていないため、パラメータが存在しない場合にはNoneとなり、そのまま使用するとエラーになる可能性もあります。
args
*argsに渡された引数の中からbananaだけを取得する方法として、argsタプルのインデックスを使う方法が考えられます。aaa(10, 'apple', 'banana', 'cherry')では、argsは('apple', 'banana', 'cherry')というタプルになり、bananaはインデックス1に位置しています。
以下のように、argsのインデックスを使ってbananaを取得できま
def aaa(bb, *args):
print(f"必須引数 bb の値: {bb}")
print("追加の引数 (args):")
for i, arg in enumerate(args, start=1):
print(f" 引数 {i}: {arg}")
# 'banana'だけを取得
if len(args) > 1: # argsに少なくとも2つ以上の要素があるか確認
banana = args[1]
print(f"2番目の引数: {banana}")
# 関数の呼び出し例
aaa(10, 'apple', 'banana', 'cherry')
def aaa(bb, *args):
print(f"必須引数 bb の値: {bb}")
print("追加の引数 (args):")
for i, arg in enumerate(args, start=1):
print(f" 引数 {i}: {arg}")
# 関数の呼び出し例
aaa(10, 'apple', 'banana', 'cherry')
各リンクに、既にクリックされた状態を保持しながら、新たにクリックするたびに必要なクエリパラメータだけをURLに残します。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>検索結果</title>
</head>
<body>
<h1>リンクから検索</h1>
<div>
{% if "test_1" not in clicked_texts %}
<a href="{% url 'process_text' %}?text_1=test_1&{{ clicked_texts_url }}">test_1</a>
{% else %}
<a href="{% url 'process_text' %}?remove=test_1&{{ clicked_texts_url }}">test_1 (再表示解除)</a>
{% endif %}
</div>
<div>
{% if "test_11" not in clicked_texts %}
<a href="{% url 'process_text' %}?text_1=test_11&{{ clicked_texts_url }}">test_11</a>
{% else %}
<a href="{% url 'process_text' %}?remove=test_11&{{ clicked_texts_url }}">test_11 (再表示解除)</a>
{% endif %}
</div>
<div>
{% if "test_2" not in clicked_texts %}
<a href="{% url 'process_text' %}?text_2=test_2&{{ clicked_texts_url }}">test_2</a>
{% else %}
<a href="{% url 'process_text' %}?remove=test_2&{{ clicked_texts_url }}">test_2 (再表示解除)</a>
{% endif %}
</div>
<h2>検索結果</h2>
<ul>
{% for item in items %}
<li>{{ item.text }}</li>
{% empty %}
<li>検索結果が見つかりませんでした。</li>
{% endfor %}
</ul>
</body>
</html>
views.pyでは、removeクエリパラメータで削除されたテキストをclicked_textsから除外し、clicked_texts_urlで最新のクリック履歴をURLに反映します。
from django.shortcuts import render, get_object_or_404
from .models import TextItem
def process_text(request):
# 新しいクリックや解除リクエストを取得
text_1 = request.GET.get('text_1')
text_2 = request.GET.get('text_2')
remove_text = request.GET.get('remove') # 表示解除するテキスト
# セッションから過去のクリック履歴を取得
clicked_texts = set(request.session.get('clicked_texts', []))
# 表示解除リクエストがある場合、該当テキストを履歴から削除
if remove_text:
clicked_texts.discard(remove_text)
# 新規クリックされたテキストを履歴に追加
if text_1:
clicked_texts.add(text_1)
if text_2:
clicked_texts.add(text_2)
# 検索結果リストを作成
items = [get_object_or_404(TextItem, text=text) for text in clicked_texts]
# 現在のクリック履歴をURLパラメータに変換
clicked_texts_url = '&'.join(f'text_1={text}' for text in clicked_texts)
# セッションに更新されたクリック履歴を保存
request.session['clicked_texts'] = list(clicked_texts)
# 検索結果、クリック履歴、URLパラメータをテンプレートに渡す
return render(request, 'test.html', {'items': items, 'clicked_texts': clicked_texts, 'clicked_texts_url': clicked_texts_url})
# urls.py
urlpatterns = [
path('', views.process_text, name='process_text'),
]