Django:request {user in form

时间:2017-05-18 10:27:13

标签: django django-forms

如何获取用户详细资料?我知道在视图中我可以做到:

currentUser=request.user

但如果我在表单中使用它,那么我会收到以下错误"'请求'未定义"。

class SelectTwoTeams(BootstrapForm):

    currentUser=request.user

    date_joined = currentUser.date_joined.replace(tzinfo=pytz.utc)

    timeless30 = datetime.datetime.now() - datetime.timedelta(seconds=3610)
    timeless30 = timeless30.replace(tzinfo=pytz.utc)

    if date_joined > timeless30:
        currentCharities = forms.ModelChoiceField(queryset=Charity.objects.filter(enabled=1), empty_label=None, widget=forms.Select(attrs={"class":"select-format"}))

    team1 = forms.ModelChoiceField(queryset=StraightredTeam.objects.none(), empty_label=None,
                               widget=forms.Select(attrs={"class":"select-format"}))
    team2 = forms.ModelChoiceField(queryset=StraightredTeam.objects.none(), empty_label=None,
                               widget=forms.Select(attrs={"class":"select-format"}))

非常感谢您提前提供任何帮助。

下面显示了此表单的 init ,只是它可能会有所帮助。我知道如何使用kwargs访问这部分用户数据:

def __init__(self, *args, **kwargs):
    user = kwargs.pop('user', None)
    self.currentSelectedTeam1 = kwargs.pop('currentSelectedTeam1', None)
    self.currentSelectedTeam2 = kwargs.pop('currentSelectedTeam2', None)
    self.currentfixturematchday = kwargs.pop('currentfixturematchday', None)
    self.currentCampaignNo = kwargs.pop('currentCampaignNo', None)
    super(SelectTwoTeams, self).__init__(*args, **kwargs)

    cantSelectTeams = UserSelection.objects.select_related().filter(~Q(fixtureid__fixturematchday=self.currentfixturematchday),campaignno=self.currentCampaignNo, )

    if not cantSelectTeams:
        queryset = StraightredTeam.objects.filter(currentteam = 1).order_by('teamname')
    else:
        queryset = StraightredTeam.objects.filter(currentteam = 1).exclude(teamid__in=cantSelectTeams.values_list('teamselectionid', flat=True)).order_by('teamname')

    teamsAlreadyPlaying = StraightredFixture.objects.filter(soccerseason=1025, fixturematchday=self.currentfixturematchday, fixturedate__lte = timezone.now())
    postponedGames = StraightredFixture.objects.filter(soccerseason=1025, fixturematchday=self.currentfixturematchday,fixturestatus = "P")

    queryset = queryset.exclude(teamid__in=teamsAlreadyPlaying.values_list('home_team_id', flat=True)).order_by('teamname')
    queryset = queryset.exclude(teamid__in=teamsAlreadyPlaying.values_list('away_team_id', flat=True)).order_by('teamname')
    queryset = queryset.exclude(teamid__in=postponedGames.values_list('home_team_id', flat=True)).order_by('teamname')
    queryset = queryset.exclude(teamid__in=postponedGames.values_list('away_team_id', flat=True)).order_by('teamname')

    self.fields['team1'].queryset = queryset
    self.fields['team2'].queryset = queryset
    self.fields['team1'].initial = self.currentSelectedTeam1
    self.fields['team2'].initial = self.currentSelectedTeam2

    self.fields['team1'].label = False
    self.fields['team2'].label = False

    date_joined = user.date_joined.replace(tzinfo=pytz.utc)

    timeless30 = datetime.datetime.now() - datetime.timedelta(seconds=3610)
    timeless30 = timeless30.replace(tzinfo=pytz.utc)

    if date_joined > timeless30:
        self.fields['currentCharities'].label = False

3 个答案:

答案 0 :(得分:8)

加载模块时定义表单类。这意味着您无法设置currentUser = request.user,因为您还无法访问请求对象。您应该从代码中删除该行。

正确的方法是覆盖__init__方法,使其占用user。如果您的字段定义取决于user,则需要将其移至__init__方法。

class SelectTwoTeams(BootstrapForm):
    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user')
        super(SelectTwoTeams, self).__init__(*args, **kwargs)

        date_joined = self.user.date_joined.replace(tzinfo=pytz.utc)

        timeless30 = datetime.datetime.now() - datetime.timedelta(seconds=3610)
        timeless30 = timeless30.replace(tzinfo=pytz.utc)

        if date_joined > timeless30:
            self.fields['currentCharities'] = forms.ModelChoiceField(queryset=Charity.objects.filter(enabled=1))
        ...

如果不需要None,则只能在弹出时使用user作为默认设置。在您的情况下,这是必需的,因为您在self.user.date_joined方法中访问了__init__。通过将用户存储为self.user,您可以根据需要使用其他方法访问它。

最后,您需要更改视图以在实例化表单时传递用户。

if request.method == "POST"
    form = SelectTwoTeams(request.POST, user=request.user)
    ...
else:
    form = SelectTwoTeams(user=request.user)

答案 1 :(得分:0)

要获取表单中的任何变量,您必须将其作为kwarg参数传递,然后在 init

中获取它

在表格中:

class someForm(forms.ModelForm):
    ...code...

    def __init__(self, *args,**kwargs):

        self.Name = kwargs.pop('SomeName')

在您的观点中:

yourform = someForm(request.POST or None, initial={'foo': foo}, SomeName= someVar)

答案 2 :(得分:0)

您可以覆盖保存方法并在那里发送请求。

viewys.py

if request.method == "POST"
   if forms.is_valid():
       form.save(request=request.user)

并在您的forms.py中:

def save(self, request=None, *args, **kwargs
    self.currentUser = request.user
    super(SelectTwoTeams, self).save(*args, **kwargs)
    instance.save()
    return instance