I'm trying to build a Django app for inputting science data, but am running into problems coming up with an elegant way to describe the possible forms.
I have two models, HCameraImage and 开发者_如何转开发MCameraImage that inherit from an Image model. On the site, the user can fill in HTML forms that populate either of these two models. In another words, I'm using HCameraImageForm(request.POST) to populate the model. Once I send it over to the client side, I find myself having to manually keep track of what form type is being sent to Django by appending an imagetype to the POST data:
if request.POST['imagetype'] == "HCameraImage":
form = HCameraImageForm(request.POST)
form.save()
if request.POST['imagetype'] == "MCameraImage":
form = MCameraImageForm(request.POST)
form.save()
...etc
Is there a more elegant way to deal with this? Ideally I want to have some parent base class Image that lets me do:
i = Image()
i.loadFormData(request.POST)
where loadFormData calls the correct derived function.
You could construct a string to instantiate the correct form object. Something like this should work:
import myapp.models
form_class = request.POST['imagetype'] + 'Form'
form_class = getattr(myapp.models, form_class)
form = form_class(request.POST)
form.save()
精彩评论