Django:自动将当前登录的用户输入为表单中的值

时间:2014-10-12 13:06:50

标签: python django django-models foreign-keys

我试图向登录用户显示一个表单,他们可以输入namesensitivity,但是这需要与登录用户相关联(当前使用外键和init尝试此操作) )。这是我的方法:

查看:

@login_required
def restricted(request):
    context = RequestContext(request)
    if request.method == 'POST':
        form = TrackForm(request.user, request.POST)
        if form.is_valid():
            form.save(commit=True)

            return index(request)
        else:
            print form.errors
    else:
        form = TrackForm()

    return render_to_response('tracker/restricted.html', {'form': form}, context)

形式:

class TrackForm(forms.ModelForm):
    name = forms.CharField(help_text="Please enter a name")
    sensitivity = forms.IntegerField(help_text="Sensitivity: 1=Low Sensitivity, 2=Standard Sensitivity, 3=Highly Sensitive", initial=0)

    def __init__(self, user, *args, **kwargs):
        self.user = user
        super(TrackForm, self).__init__(*args, **kwargs)

    class Meta:
        model = ToTrack
        fields = ('name','sensitivity')

型号:

class ToTrack(models.Model):
    name = models.CharField(max_length=128)
    sensitivity = models.IntegerField(default=0)
    user = models.ForeignKey(User)

    def __unicode__(self):
        return self.name

我目前收到错误消息:

TypeError at /tracker/restricted/
__init__() takes at least 2 arguments (1 given)

1 个答案:

答案 0 :(得分:0)

像这样更改views.py(我评论更改了行):

@login_required
def restricted(request):
    context = RequestContext(request)
    if request.method == 'POST':
        form = TrackForm(request.POST, user=request.user) #this line change
        if form.is_valid():
            form.save(commit=True)

            return index(request)
        else:
            print form.errors
    else:
        form = TrackForm(user=request.user) #this line change

    return render_to_response('tracker/restricted.html', {'form': form}, context)

并像这样更改form

class TrackForm(forms.ModelForm):
    name = forms.CharField(help_text="Please enter a name")
    sensitivity = forms.IntegerField(help_text="Sensitivity: 1=Low Sensitivity, 2=Standard Sensitivity, 3=Highly Sensitive", initial=0)

    def __init__(self, *args, **kwargs):
        user = kwargs.pop('user', None)
        if user:
            self.user = user
        super(TrackForm, self).__init__(*args, **kwargs)

    class Meta:
        model = ToTrack
        fields = ('name','sensitivity')