当我尝试保存我的表单时,我遇到了这个错误:
Exception Value:
Cannot assign None: "TriggerService.user" does not allow null values.
Exception Location: /usr/local/lib/python2.6/dist-packages/django/db/models/fields/related.py in __set__, line 362
这是我的模型、表格和视图
模型.py
class TriggerService(models.Model):
"""
TriggerService
"""
provider = models.ForeignKey(TriggerType, related_name='+', blank=True)
consummer = models.ForeignKey(TriggerType, related_name='+', blank=True)
description = models.CharField(max_length=200)
user = models.ForeignKey(User)
date_created = models.DateField(auto_now_add=True)
表格.py
class TriggerServiceForm(forms.ModelForm):
"""
TriggerService Form
"""
class Meta:
"""
meta to add/override anything we need
"""
model = TriggerService
widgets = {
'description':\
TextInput(attrs={'placeholder':\
_('A description for your new service')}),
}
exclude = ('user',
'date_created')
provider = forms.ModelChoiceField(queryset=TriggerType.objects.all())
consummer = forms.ModelChoiceField(queryset=TriggerType.objects.all())
def save(self, user=None):
myobject = super(TriggerServiceForm, self).save(commit=False)
print "i am:"
print user
myobject.user = user
myobject.save()
视图.py
class TriggerServiceCreateView(CreateView):
form_class = TriggerServiceForm
template_name = "triggers/add_trigger.html"
@method_decorator(login_required)
def dispatch(self, *args, **kwargs):
return super(TriggerServiceCreateView, self).dispatch(*args, **kwargs)
def form_valid(self, form):
self.object = form.save(user=self.request.user)
return super(TriggerServiceCreateView, self).form_valid(form)
def get_context_data(self, **kwargs):
context = super(TriggerServiceCreateView, self).get_context_data(**kwargs)
context['action'] = 'add_trigger'
return context
就像你在我的表格中看到的那样,我添加了一个打印来跟踪这里发生的事情
奇怪的是我保存了我的表格两次,为什么?以及如何避免这种行为?
i am:
foxmask
i am:
None