是什么原因导致“功能”对象在Django视图中没有属性“ _committed”错误?

时间:2019-03-25 07:45:52

标签: django

我正在尝试通过我的应用程序模型存储持久的sklearn joblib模型。突然,我在视图中的save()调用引发了一个错误。像这样的东西: “功能”对象没有属性“ _committed”

这是为django2.1写的

这是我的观点:

def predictionModelCreateView(request, **kwargs):
    proj_pk = kwargs.get('pk')

    if request.method == 'POST':
        form = PredictionCreateModelForm(proj_pk, request.POST)
        print('POST')
        if form.is_valid():
            predModel = form.save(commit=False)
            # proj = Project.objects.filter('id'=kwargs('pk').first()
            predModel.model_file = train_model  #sample joblib file to be stored into database
            predModel.save()
            # form.save()
            messages.success(request, f'Model has been created!')
            return redirect('project-home')

    else:
        form = PredictionCreateModelForm(project_id=proj_pk)

    context = {
        'form': form
    }

    return render(request, 'predictions/create_prediction_model.html', context)

另外,这是我的Forms.py:

ALGORITHM_TYPE = (
    ('bin-log regression', 'Binary Logistic Regression'),
    ('another regression', 'Another Model')
)

class PredictionCreateModelForm(forms.ModelForm):
    # proj = ''
    name = forms.CharField(max_length=100)
    algorithm_type = forms.ChoiceField(
        choices=ALGORITHM_TYPE, 
        widget=forms.RadioSelect, 
        label="Select Algorithm:"
    )

    predictors = forms.MultipleChoiceField(
        widget = forms.CheckboxSelectMultiple, 
        label="Select Feature Predictor:"
    )

    target_column = forms.CharField(
        widget = forms.RadioSelect, 
        label="Select Target Feature:"
    )

    def __init__(self, project_id=1, *args, **kwargs):
        super(PredictionCreateModelForm, self).__init__(*args, **kwargs)

        project = Project.objects.get(id=project_id)

        df = pd.read_csv(project.base_file)
        cols = df.columns
        a_cols = np.column_stack(([cols, cols]))
        self.fields['predictors'].choices = a_cols
        self.fields['target_column'].choices = a_cols

    class Meta:
        model   = PredictionModel
        fields  = ['name', 'algorithm_type', 'target_column', 'model_file']
        exclude = ['model_file']

这是我的Models.py:

class PredictionModel(models.Model):

    name = models.CharField(max_length=30, default='New Model')
    algorithm_type = models.CharField(max_length=25, default='bin log regression')
    predictors = models.TextField(default="column1, column2, column-n")
    target_column = models.CharField(max_length=50, default='column1')
    model_file = models.FileField(upload_to='model_files', null=True)
    project = models.ForeignKey(Project, on_delete=models.CASCADE)

这是我的示例joblib实现,其中model_file的文件应来自:

ad_data = pd.read_csv('advertising.csv')
    X = ad_data[['Daily Time Spent on Site', 'Age', 'Area Income','Daily Internet Usage', 'Male']]
    y = ad_data['Clicked on Ad']

    # ** Split the data into training set and testing set using train_test_split**
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=42)

    # ** Train and fit a logistic regression model on the training set.**
    logmodel = LogisticRegression()
    logmodel.fit(X_train,y_train)

    # # ** Now predict values for the testing data.**
    # predictions = logmodel.predict(X_test)

    filename='sample.sav'
    joblib.dump(logmodel, filename)
    print('Hello')
    return filename

我希望所有表单字段都将保存到数据库中,包括joblib文件。

0 个答案:

没有答案