2012-03-26 12 views
0

そうように私は、フォームを持っている:ユーザがこのフォームを送信するとき、私はに、フォームのエントリを関連付けることができるようにDjangoはログインしたユーザーに初期値を設定して設定しますか?

from django import forms 
from django.contrib.auth.models import User 

from django_countries.countries import COUNTRIES 

from statuses.models import Status 

class StatusForm(forms.Form): 
    country = forms.ChoiceField(choices=COUNTRIES) 
    mood = forms.IntegerField() 
    sleep_quality = forms.IntegerField() 

このフォームは唯一私がrequest.userを設定することができますどのようにログインしているユーザーに表示されますそれら?私のモデルは、ユーザFKで次のようになります。ここでは

from django.db import models 
from django.contrib.auth.models import User 

from django_countries import CountryField 

class Status(models.Model): 
    user = models.ForeignKey(User) 
    country = CountryField() 
    mood = models.SmallIntegerField(default=4) 
    sleep_quality = models.SmallIntegerField(default=4) 

は、同様に、このフォームの私の見解である:

@login_required 
def index(request, template_name="status/index.html"): 
    if request.method == 'POST': 
     postdata = request.POST 
     form = StatusForm(postdata) 
     if form.is_valid(): 
      messages.success(request, 'Something happened, good!') 
      return redirect(urlresolvers.reverse('profile')) 
    else: 
     form = StatusForm() 
    context = RequestContext(request, { 'form': form }) 
    return render_to_response(template_name, context) 

私は多分私は中のHiddenFieldや店舗からrequest.userを作成する必要がありますと思いましたそれは火かき棒などで簡単に編集できるので安全だとは思われません。どのように私はこのフォームのrequest.userを格納することができるかに関する任意の提案?

ありがとうございます!

+0

あなたは、あなたのビューでやろうとしていますか?現在のユーザは 'request.user'で常にアクセス可能ですので、フォームにフィールドをまったく入れる必要はありません。 –

+0

pastylegs、上記の私の意見を追加 – JeffC

答えて

5

現在のユーザーは要求にrequest.userと表示されますので、フォームに含める必要はありません。代わりに、ModelFormsを活用して、オブジェクトをフォームにリンクすることに対処してください。

あなたのビューで次に
class StatusForm(forms.ModelForm): 
    country = forms.ChoiceField(choices=COUNTRIES) 
    # The other fields are automatically included, we just overwrite country 

    class Meta: 
     model = Status 
     exclude = ("user") 

... 
form = StatusForm(request.POST): 
    if form.is_valid(): 
     # Because your model requires that user is present, we validate the form and 
     # save it without commiting, manually assigning the user to the object and resaving 
     obj = form.save(commit=False) 
     obj.user = request.user 
     obj.save() 
     messages.success(request, 'Something happened, good!') 
     return redirect(urlresolvers.reverse('profile')) 
    ... 
関連する問題