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

ここに私のモデル、フォーム、ビューがあります

models.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

私のフォームでわかるように、ここで何が起こるかを追うためにプリントを追加しました

奇妙なことに、フォームの保存を 2 回行ったのはなぜですか? この動作を回避する方法は?

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 に答える