我希望能够根据登录的用户保存表单提交的数据(而不是让用户通过文本框写下他/她的名字)。我正在使用django的内置身份验证系统。有关如何实现这一目标的任何想法?
@login_required
def add_review(request, product_id):
p = get_object_or_404(Productbackup, pk=product_id)
if request.method == 'POST':
form = ReviewbackupForm(request.POST)
if form.is_valid():
review = form.save(commit=False)
review.product = p
#how to save user as well? review.user = user
review.save()
return HttpResponseRedirect(reverse('reserve.views.view_reviews', kwargs={'product_id':p.id}))
else:
form = ReviewbackupForm()
variables = RequestContext(request, {'form': form, 'product_id': product_id})
return render_to_response('reserve/templates/create_review.html', variables)
答案 0 :(得分:2)
您已使用commit=False
保存,因此您几乎就在那里。您可以从请求对象中获取登录用户。
if form.is_valid():
review = form.save(commit=False)
review.product = p
review.user = request. user
review.save()
有关详细信息,请参阅Django docs for user authentication。