すべてのモデルに「ユーザー」フィールドを追加しました。ユーザーがオブジェクトを作成するときに、外部キーを介して ID をアタッチしたい
user = models.ForeignKey(User)
以前は、create_object と update_object を使用していました。必要なユーザーをレコードに最も簡単に挿入するには、クラスベースの汎用ビューに切り替える必要があると思います。しかし、create_object または update_object が呼び出される前に、以前の関数で発生していた事前計算のいくつかをどのように開始するかについて、私は混乱しています。
作成または更新に関係なく、すべてのオブジェクト編集を処理する関数が 1 つあります。
@login_required
def edit_item(request, modelname, submodelname=None, slug=None, id=None):
# Get parameter "next" to determine where to send user after object is created or updated
# Define which template to use
# Determine whether user is converting an object to another type
# Determine which form_class to use based on modelname and whether user is converting or not
# Redirect user if slug and id are not both correct
# Abort if user hit cancel instead of submit
# If object exists (slug and id are defined):
# Update_object with form_class, object_id, template_name, post_save_redirect, and extra_context
# Else
# Create_object with form_class, template_name, post_save_redirect, and extra_context
クラスベースの汎用ビュー内で、これらの計算の一部をどのように/どこで/いつ実行するか (条件に基づいて template または form_class を定義するロジック)? ドキュメントは定義に直行しているように見えるので、私は混乱しています:
class ContactView(FormView):
template_name = 'contact.html'
form_class = ContactForm
success_url = '/thanks/'
私はそこにロジックを投げることができますか?
class ContactView(FormView):
A = 1 + 2
if A == 3:
template_name = 'contact.html'
else:
template_name = 'contact_two.html'
form_class = ContactForm
success_url = '/thanks/'
また、slug/id が定義されているかどうかに応じて、同じ関数で create_object または update_object を使用してここで行ったことに対して、CreateView または UpdateView を使用するようにロジックを変更するにはどうすればよいですか?