What causes 'function' object has no attribute '_committed' error in django views?Can “list_display” in a Django ModelAdmin display attributes of ForeignKey fields?What is a “slug” in Django?How to combine 2 or more querysets in a Django view?What is `related_name` used for in Django?Can't add field to ModelForm at __init__Django - what is the difference between render(), render_to_response() and direct_to_template()?what is reverse() in DjangoSetting DEBUG = False causes 500 ErrorDjango 'bool' object has no attribute '_committed''Image' object has no attribute '_committed'

LWC - Local Dev - How can I run the local server on HTTPS?

Intuition for the role of diffeomorphisms

Prime sieve in Python

Counterfeit checks were created for my account. How does this type of fraud work?

How many people are necessary to maintain modern civilisation?

How to make clear to people I don't want to answer their "Where are you from?" question?

What determines the direction in which motor proteins go?

What is appropriate short form for "laboratoires" in French?

Hit the Bulls Eye with T in the Center

Do I have any obligations to my PhD supervisor's requests after I have graduated?

Helping ease my back pain by studying 13 hours everyday , even weekends

What can I do with a research project that is my university’s intellectual property?

Why are < or > required to use /dev/tcp

UK - Working without a contract. I resign and guy wants to sue me

What are Elsa's reasons for selecting the Holy Grail on behalf of Donovan?

Primes and SemiPrimes in Binary

DBCC checkdb on tempdb

Why does independence imply zero correlation?

Constitutionality of U.S. Democratic Presidential Candidate's Supreme Court Suggestion

What does it mean to not be able to take the derivative of a function multiple times?

Loss of power when I remove item from the outlet

Why does the Saturn V have standalone inter-stage rings?

Can Ogre clerics use Purify Food and Drink on humanoid characters?

Why is it easier to balance a non-moving bike standing up than sitting down?



What causes 'function' object has no attribute '_committed' error in django views?


Can “list_display” in a Django ModelAdmin display attributes of ForeignKey fields?What is a “slug” in Django?How to combine 2 or more querysets in a Django view?What is `related_name` used for in Django?Can't add field to ModelForm at __init__Django - what is the difference between render(), render_to_response() and direct_to_template()?what is reverse() in DjangoSetting DEBUG = False causes 500 ErrorDjango 'bool' object has no attribute '_committed''Image' object has no attribute '_committed'






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








0















I am trying to store a persistent sklearn joblib model through my app's model. Suddenly, my save() call in my views raised an error. something like this:
'function' object has no attribute '_committed'



This is writen for django2.1



Here is my view:



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)


Additionally, here is my 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']


And here is my 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)



Here is my sample joblib implementation where the file for the model_file should come from:



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


I expect that all the form fields will be saved into the database INCLUDING the joblib file.










share|improve this question






















  • If you posted the traceback, then we (and you) would know what causes it. As it is, we'd have to guess.

    – Daniel Roseman
    Mar 25 at 9:21

















0















I am trying to store a persistent sklearn joblib model through my app's model. Suddenly, my save() call in my views raised an error. something like this:
'function' object has no attribute '_committed'



This is writen for django2.1



Here is my view:



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)


Additionally, here is my 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']


And here is my 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)



Here is my sample joblib implementation where the file for the model_file should come from:



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


I expect that all the form fields will be saved into the database INCLUDING the joblib file.










share|improve this question






















  • If you posted the traceback, then we (and you) would know what causes it. As it is, we'd have to guess.

    – Daniel Roseman
    Mar 25 at 9:21













0












0








0








I am trying to store a persistent sklearn joblib model through my app's model. Suddenly, my save() call in my views raised an error. something like this:
'function' object has no attribute '_committed'



This is writen for django2.1



Here is my view:



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)


Additionally, here is my 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']


And here is my 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)



Here is my sample joblib implementation where the file for the model_file should come from:



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


I expect that all the form fields will be saved into the database INCLUDING the joblib file.










share|improve this question














I am trying to store a persistent sklearn joblib model through my app's model. Suddenly, my save() call in my views raised an error. something like this:
'function' object has no attribute '_committed'



This is writen for django2.1



Here is my view:



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)


Additionally, here is my 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']


And here is my 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)



Here is my sample joblib implementation where the file for the model_file should come from:



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


I expect that all the form fields will be saved into the database INCLUDING the joblib file.







django






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 25 at 7:45









dJudgedJudge

478




478












  • If you posted the traceback, then we (and you) would know what causes it. As it is, we'd have to guess.

    – Daniel Roseman
    Mar 25 at 9:21

















  • If you posted the traceback, then we (and you) would know what causes it. As it is, we'd have to guess.

    – Daniel Roseman
    Mar 25 at 9:21
















If you posted the traceback, then we (and you) would know what causes it. As it is, we'd have to guess.

– Daniel Roseman
Mar 25 at 9:21





If you posted the traceback, then we (and you) would know what causes it. As it is, we'd have to guess.

– Daniel Roseman
Mar 25 at 9:21












0






active

oldest

votes












Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55333223%2fwhat-causes-function-object-has-no-attribute-committed-error-in-django-view%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























0






active

oldest

votes








0






active

oldest

votes









active

oldest

votes






active

oldest

votes















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55333223%2fwhat-causes-function-object-has-no-attribute-committed-error-in-django-view%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript