有没有更好的方法来制作可重用的创建方法?我使用的eval
被认为是危险的,但我不认为这是在这里使用的方式,因为我只是用字符串替换表单值。
def convert_camel_case_to_underscore(model_name):
s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', model_name)
return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()
@login_required
def create(request, model, template_name='create.html'):
user = request.user
profile = user.get_profile()
if profile.county_state:
county_state = profile.county_state
else:
county_state = get_object_or_404(CountyState, id=1)
model_name = model._meta.object_name
model_goto = convert_camel_case_to_underscore(model_name)
model_lower = convert_camel_case_to_underscore(model_name)
form_name = model_name + "Form"
if request.method == "POST":
form = eval(form_name)(data=request.POST, files=request.FILES)
if form.is_valid():
model_lower = form.save(commit=False)
model_lower.county_state = county_state
model_lower.user = request.user
model_lower.created_by = request.user.username
model_lower.last_modified_by = request.user.username
model_lower.save()
url = '/parcels/%s/show/%s' % (model_goto, str(model_lower.id))
return HttpResponseRedirect(url)
else:
error = "form is not valid"
return HttpResponseRedirect('/errors/index/')
else:
form = eval(form_name)()
return render_to_response(template_name, locals(), context_instance=RequestContext(request))
答案 0 :(得分:4)
如果您完全确定完全控制model
是什么,那么在这种特定情况下并不危险。
但是,我认为在不需要时使用eval
更好,你可以这样做:
import models
# Get the name of the class of the model object
model_name = model.__class__.__name__
# Get the class model_name + "Form" from the 'models' module
formklass = getattr(models, model_name + "Form")
# Instantiate the class
form = formklass()