33
25

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Django】renderとreverse_lazyの使い分けについて

Posted at

#概要
Djangoでアプリ作成のときに、renderreverse_lazyの違いがわからなかったので、備忘録として書きます。

#TemplateView or Function
結論からいうと、reverse_lazyTemplateViewで使い、renderfunctionで実装する場合に使用します。

下記にて、投稿サイトをイメージした例になります。

  • PostClasslistfunctionに注目してください
myapp/models.py
from django.db import models

class PostModel(models.Model):
    title = models.CharField(max_length=50)
    memo = models.TextField()
myapp/views.py
from django.views.generic import CreateView
from django.urls import reverse_lazy
from .models import PostModel

class PostClass(CreateView):
    template_name = 'post.html'
    model = PostModel
    fields = ('title','memo')
    success_url = reverse_lazy('list')

def listfunction(request):
    object_list = PostModel.objects.all()
    return render(request, 'list.html')
myapp/urls.py
from django.urls import path
from .views import PostClass, listfunction

urlpatterns = [
    path('post/', PostClass.as_view(), name='post'),
    path('list/', listfunction, name='list'),
]
post.html
<form action="" method="POST">
{% csrf_token %}
  <p>タイトル:<input type="text" name="title"></p>
  <p>メモ:<input type="text" name="memo"></p>
  <input type="submit" value="投稿する">
</form>
list.html
<div class="container">
  {% for post in object_list %}
  <div class="post">
    <p>タイトル:{{ post.title }}</p>
    <p>メモ:{{ post.memo }}</p>
  </div>
  {% endfor %}
</div>

#まとめ
上記でも書いたように

  • reverse_lazyTemplateViewの場合
  • renderfunctionの場合になります

参照:
https://docs.djangoproject.com/ja/2.2/ref/urlresolvers/
https://teratail.com/questions/103080
https://teratail.com/questions/50683

以上

33
25
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
33
25

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?