1

当我尝试保存我的表单时,我遇到了这个错误:

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
4

1 回答 1

3

这:

def form_valid(self, form):
    # call form.save manually: creates "i am: foxmask"
    self.object = form.save(user=self.request.user)

    # Call parent form_valid(), CreateView.form_valid() ...
    # ... which also calls form.save() without user argument !!
    # So, it should create "i am: None" because the default value for 
    # the user argument of the save() method of your form is None.
    return super(TriggerServiceCreateView, self).form_valid(form)

CreateView.form_valid()调用. TriggerServiceForm.save()_user=None

所以你不能在这里使用 super() ,因为它会调用直接父级。

为什么不保持简单:

from django import http

# ...

def form_valid(self, form):
    self.object = form.save(user=self.request.user)
    return http.HttpResponseRedirect(self.get_success_url())
于 2013-02-11T20:58:06.753 回答