2012-07-04 67 views
1

我希望能夠保存基於登錄用戶的表單提交的數據(而不是讓用戶通過文本框寫他/她的名字)。我正在使用django的內置身份驗證系統。有關我如何完成此任務的任何想法?使用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) 

回答

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