AttributeError:type object' Newmodel'没有属性' get'在django动态模型创建中?

时间:2018-04-13 12:55:48

标签: python django django-models

我想基于我的csv文件创建一个动态模型。我遵循Django一般方法(DynamicModel)在 views.py 中我的代码应该看起来像`

 def create_model(name, fields=None, app_label='', module='', options=None, admin_opts=None):
"""
Create specified model
"""
class Meta:
    # Using type('Meta', ...) gives a dictproxy error during model creation
    pass

if app_label:
    # app_label must be set using the Meta inner class
    setattr(Meta, 'app_label', app_label)

# Update Meta with any options that were provided
if options is not None:
    for key, value in options.iteritems():
        setattr(Meta, key, value)

# Set up a dictionary to simulate declarations within a class
attrs = {'__module__': module, 'Meta': Meta}

# Add in any fields that were provided
if fields:
    attrs.update(fields)

# Create the class, which automatically triggers ModelBase processing
model = type(name, (models.Model,), attrs)

# Create an Admin class if admin options were provided
if admin_opts is not None:
    class Admin(admin.ModelAdmin):
        pass
    for key, value in admin_opts:
        setattr(Admin, key, value)
    admin.site.register(model, Admin)

return model
在此功能下,我添加了此代码
def upload_csv(request):
data = {}
if request.method == "GET":
    return render(request, "upload_csv.html", data)
# if not GET, then proceed
try:
    csv_file = request.FILES["csv_file"]
    if not csv_file.name.endswith('.csv'):
        messages.error(request,'File is not CSV type')
        return HttpResponseRedirect(reverse("upload_csv"))

    df2 = pd.read_csv(csv_file,error_bad_lines=False)
    columns=df2.iloc[0]
    fields = {}
    for line in columns:

        fields[line] = models.CharField(max_length=45)
    print('fields', fields)

    return create_model('Newmodel', fields, app_label='myapp')

` 当我上传我的csv文件时,它会显示错误,如下所示:

fields {'company': <django.db.models.fields.CharField>,
    '2017-02-06':  <django.db.models.fields.CharField>} Internal Server
    Error: /upload/csv/    Traceback (most recent call last):   File
    "/home/rakib/Desktop/TTTTT/env/lib/python3.6/site-packages/django/core/handlers/exception.py",
    line 35, in inner
            response = get_response(request)   File "/home/rakib/Desktop/TTTTT/env/lib/python3.6/site-packages/django/utils/deprecation.py",
    line 97, in __call__
            response = self.process_response(request, response)   File "/home/rakib/Desktop/TTTTT/env/lib/python3.6/site-packages/django/middleware/clickjacking.py",
    line 26, in process_response
            if response.get('X-Frame-Options') is not None: AttributeError: type object 'Newmodel' has no attribute 'get'

我怎样摆脱这个问题?

0 个答案:

没有答案