0
我正在嘗試保存基於按鈕提交的簡單數據。但我不斷收到以下錯誤:無法使用django保存模型實例
TypeError at /exercise/1/
save() got an unexpected keyword argument 'commit'
models.py:
class StrategyHistory(models.Model):
user = models.ForeignKey(User)
strategy = models.ForeignKey(Strategies)
created = models.DateTimeField(editable=False)
modified = models.DateTimeField()
def save(self, *args, **kwargs):
''' On save, update timestamps '''
if not self.id:
self.created = datetime.datetime.today()
self.modified = datetime.datetime.today()
return super(StrategyHistory, self).save(*args, **kwargs)
def __unicode__(self):
return self.strategy.name
views.py:
def exercise_view(request, pk):
template_name = 'mobileApp/page/exercise.html'
if not request.user.is_authenticated():
return HttpResponseRedirect(reverse('mobile_user_login'))
strategy = Strategies.objects.get(pk=pk)
context = {
'strategy':strategy,
}
if request.method == 'POST':
strategyhistory = StrategyHistory()
entry = strategyhistory.save(commit=False)
entry.user = self.request.user
entry.strategy = Strategies.objects.get(id=pk)
entry.save()
if pk < 5:
return HttpResponseRedirect(reverse('mobile_exercise', kwargs={'pk':pk+1}))
else:
return HttpResponseRedirect(reverse('mobile_comeback_later'))
return render_to_response(template_name,
context,
context_instance = RC(request, {}))
HTML文件:
<form action="" method="post">{% csrf_token %}
<a href="#" data-role="button" data-inline="true" data-rel="back" data-transition="flow" data-icon="refresh" data-theme="c">Prøv igen</a>
<button type="submit" value="submit" data-inline="true" data-transition="flow" data-icon="check" data-theme="b">Fortsæt</button>
</form>
我運行Django 1.6.2
用於創建和更新時間,我有這個在我的項目:CREATION_TIME = models.DateTimeField(auto_now_add =真,auto_now = FALSE) UPDATE_TIME =模型.DateTimeField(auto_now_add = False,auto_now = True) –
您不必同時指定'auto_now'這個動作。 –