在Django的基于类的UpdateView中,我排除了用户字段,因为它是系统内部的,我不会要求它。现在将Django传递给表单的正确方法是什么。 (我现在如何做,是将用户传递到表单的 init ,然后覆盖表单的save()方法。但我敢打赌,有一种正确的方法可以做到这一点。隐藏的领域或那种性质的东西。
# models.py
class Entry(models.Model):
user = models.ForeignKey(
User,
related_name="%(class)s",
null=False
)
name = models.CharField(
blank=False,
max_length=58,
)
is_active = models.BooleanField(default=False)
class Meta:
ordering = ['name',]
def __unicode__(self):
return u'%s' % self.name
# forms.py
class EntryForm(forms.ModelForm):
class Meta:
model = Entry
exclude = ('user',)
# views.py
class UpdateEntry(UpdateView):
model = Entry
form_class = EntryForm
template_name = "entry/entry_update.html"
success_url = reverse_lazy('entry_update')
@method_decorator(login_required)
def dispatch(self, *args, **kwargs):
return super(UpdateEntry, self).dispatch(*args, **kwargs)
# urls.py
url(r'^entry/edit/(?P<pk>\d+)/$',
UpdateEntry.as_view(),
name='entry_update'
),
答案 0 :(得分:7)
像传递隐藏字段一样黑客攻击没有意义,因为这与客户端无关 - 这个经典的“与登录用户相关联”问题应该在服务器端处理。
我将此行为放在form_valid
方法中。
class MyUpdateView(UpdateView):
def form_valid(self, form):
instance = form.save(commit=False)
instance.user = self.request.user
super(MyUpdateView, self).save(form)
# the default implementation of form_valid is...
# def form_valid(self, form):
# self.object = form.save()
# return HttpResponseRedirect(self.get_success_url())
答案 1 :(得分:3)
必须返回HttpResponse对象。以下代码有效:
class MyUpdateView(UpdateView):
def form_valid(self, form):
instance = form.save(commit=False)
instance.user = self.request.user
return super(MyUpdateView, self).form_valid(form)
答案 2 :(得分:2)
我们也可以这样做
class MyUpdateView(UpdateView):
form_class = SomeModelForm
def form_valid(self, form):
form.instance.user = self.request.user
return super(MyUpdateView, self).form_valid(form)