Untitled
unknown
plain_text
2 years ago
1.3 kB
9
Indexable
from django.views.generic import CreateView, UpdateView, DeleteView
def create_model_view(view_type, model, fields, success_url):
# Determine the base class based on the view_type argument
if view_type == 'create':
base = CreateView
template = 'base_form.html'
elif view_type == 'update':
base = UpdateView
template = 'base_form.html'
elif view_type == 'delete':
base = DeleteView
template = 'base_confirm_delete.html'
else:
raise ValueError(f"Invalid view_type: {view_type}")
# Define the get_success_url method
def get_success_url(self):
return self.success_url
# Create the new class
new_class = type(f"{model.__name__}{view_type.capitalize()}View", (base,), {
"model": model,
"fields": fields,
"success_url": success_url,
"template_name": template,
"get_success_url": get_success_url,
})
return new_class
# Then you can create views for your models like this:
MyModelCreateView = create_model_view('create', MyModel, ['field1', 'field2'], '/my_model/')
MyModelUpdateView = create_model_view('update', MyModel, ['field1', 'field2'], '/my_model/')
MyModelDeleteView = create_model_view('delete', MyModel, ['field1', 'field2'], '/my_model/')
Editor is loading...