私が単純なモデルを持っているとしましょう:
class Contact(models.Model):
owner = models.ForeignKey(User, editable=False)
first_name = models.CharField(max_length=255,)
last_name = models.CharField(max_length=255,)
email = models.EmailField()
オブジェクトの作成時に、オブジェクトの所有者 (request.user、ログイン ユーザー) を自動的に設定したいと考えています。さまざまなオプションを検索しましたが、それらのほとんどは管理者側での方法に関連しており、他のオプションはうまくいきません。たとえばhttp://blog.jvc26.org/2011/07/09/django-automatically-populate-request-userを試してから、save メソッドやある種の pre_save シグナルをオーバーライドする多くの方法を試しました。何もうまくいかないようで、エラーが発生するだけです
IntegrityError at /new
null value in column "owner_id" violates not-null constraint
それを行う正しい方法は何ですか?これは簡単なことだと思いますが、それを行う方法が見つかりません。
...編集...私の作成ビューは次のようになります:
class CreateContactView(LoginRequiredMixin, ContactOwnerMixin, CreateWithInlinesView):
model = models.Contact
template_name = 'contacts/edit_contact.html'
form_class = forms.ContactForm
inlines = [forms.ContactAddressFormSet]
def form_valid(self, form):
obj = form.save(commit=False)
obj.owner = self.request.user
obj.save()
return HttpResponseRedirect(self.get_success_url())
def get_success_url(self):
return reverse('contacts-list')
def get_context_data(self, **kwargs):
context = super(CreateContactView, self).get_context_data(**kwargs)
context['action'] = reverse('contacts-new')
return context
これは、私がこれまでにその問題を解決しようとした 1 つの方法にすぎません。http://blog.jvc26.org/2011/07/09/django-automatically-populate-request-userからその解決策を見つけました