有没有更好的方法来制作可重用的创建方法?我正在使用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))