1
2

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 3 years have passed since last update.

(Django) django-extra-viewsのUpdateWithInlinesViewで、条件によってInline Formを変える

Posted at

Djangoでインラインフォームを簡単に実装できるdjango-extra-views

ただたインラインフォームを使うだけだったら、view.pyに

from extra_views import UpdateWithInlinesView, InlineFormSetFactory

class PostUpdateInlineFormSet(InlineFormSetFactory):
	model = Author
	fields = ('name',)
	factory_kwargs = {'extra': 0,'can_order': False, 'can_delete': False}

class PostUpdate(UpdateWithInlinesView):
	model = Post
	fields = ('title',)
	template_name = 'post/post_detail.html'
	success_url = reverse_lazy('post:home')

を書くだけで実装できてしまう。

また、インラインフォームクラスを複数作って、条件によって使うインラインフォームを変えたい時はget_inlines()をオーバーライドすれば可能になる。

class PostUpdate(UpdateWithInlinesView):
	model = Post
	fields = ('title',)
	template_name = 'post/post_detail.html'
	success_url = reverse_lazy('post:home')
        #ここではユーザーのタイプによって出し分け
        def get_inlines(self, **kwargs):
		inlines = super().get_inlines(**kwargs)
		user = self.request.user
		if user.user_type == 'admin':
			inlines = [AdminUpdateInlineFormSet, ]
		elif user.user_type == 'member':
			inlines = [PostUpdateInlineFormSet, ]
		return inlines
1
2
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
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?