3
5

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でユーザー作成フォームをクラスベースで作る方法

Last updated at Posted at 2017-12-11

Djangoでユーザー作成フォームを作成するための資料が少なく、個人的に納得する記事がなかったためまとめた。
メソッドとして実装している例は複数あったのだが、クラスとして実装したほうがスマートだと思ったため、できるだけ無駄な実装を省くように記述した。

Django1.11でテストした内容だが、ある程度の上下は問題ない。

djangoでデフォルト設定のユーザーを作成する方法

myapp/view.py
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from django.views.generic import CreateView
from django.urls import reverse_lazy

class UserCreateView(CreateView):
  model = User
  form_class = UserCreationForm
  success_url = reverse_lazy('login') # urls.pyのnameを指定
  # template_nameのデフォルトはtemplates/auth/user_form.html

  def get_success_url(self):
    return reverse('login') 
myapp/urls.py
urlpatterns = [
  url(r'user_creation$', views.UserCreateView.as_view(), name = "user_creation"),
]
templates/auth/user_form.html
{% extends "base.html" %}

{% block contents %}
  <h1>Create User</h1>

  <form method="POST" action="">
    {% csrf_token %}

    {{ form.as_p }}

    <input type="submit" id="save" value="Save">
  </form>

{% endblock %}

これで、デフォルトのユーザー作成フォームができる。

カスタマイズしたユーザー作成フォームを作る方法(今後追加予定)

  1. 使用するフォームを変えたい場合
    UserCreationFormを継承し、新しいフォームをform_classに設定する
  2. 使用するモデルを変更したい場合
    Userを継承し、新しいモデルをmodelに設定する
3
5
2

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
3
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?