1

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

1 回答 1

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()
于 2013-08-12T01:28:46.673 回答