0
0

More than 1 year has passed since last update.

【Django】汎用ビュー CreateView を用いたフォームのラベルを変更する

Posted at

CreateView

モデルの作成に使われる、汎用ビューの一つである
汎用ビューを用いることでコードの量を減らすことができる

こたえ: get_form()

views.py
class PostCreateView(LoginRequiredMixin, CreateView):
    model = Post
    template_name = "post.html"
    fields = ['shop_name', 'shop_link']
    success_url = reverse_lazy('APP:posted')

    #ラベルを日本語に
    def get_form(self, form_class=None):
        form = super().get_form(form_class)
        form.fields['shop_name'].label = '店名' 
        form.fields['shop_link'].label = 'お店のURL'
        return form

    #ログインユーザーで投稿
    def form_valid(self, form):
        form.instance.user = self.request.user
        return super().form_valid(form)

CreateViewを使用しないときはforms.pyで

forms.py
class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = ['shop_name', 'shop_link']
        #これを記述
        labels={
            'shop_name':'店名',
            'shop_link':'お店のリンク(ラーメンDB等)'
           }

とする。
(CreateViewではこれが反映されなかったけど、普通はされるのかな...??)

参考: https://yu-nix.com/archives/django-create-view/

0
0
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
0
0