在forms.py中使用请求对象

时间:2019-04-08 03:33:01

标签: python django

我正在开发一个电子投票系统,其中有一些争夺者争夺特定职位。我正在尝试创建一个表单,其中在RadioSelect按钮中的每个位置都显示有抱负者。

为此,我尝试通过Position()类中的所有对象初始化一个for循环,并使用if语句将当前URL路径与每个对象的get_absolute_url()比较。 我无法让请求模块正常工作。

class VotingForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request', None)
        super(VotingForm, self).__init__(*args, **kwargs)

    def get_url(self):
        self._ = []
        for post in Position.objects.all():
            if self.request.get_full_path() == "/post/pro":
                no_ = Position.objects.get(post='PRO')
                self._.clear()
                for i in Aspirant.objects.filter(post=no_):
                    self._.append(tuple([i.name, i.name]))
            elif self.request.get_full_path() == "/post/gen-sec":
                no_ = Position.objects.get(post='General Secretary')
                self._.clear()
                for i in Aspirant.objects.filter(post=no_):
                    self._.append(tuple([i.name, i.name]))

        return _

    CHOICES = self.get_url()



    aspirants = forms.ChoiceField(choices=CHOICES, widget=forms.RadioSelect)

    class Meta:
        model = Aspirant
        fields = ['aspirants']

我收到此错误。 我不确定自己在做什么错。

  

CHOICES = self.get_url()

     

NameError:名称'self'未定义

1 个答案:

答案 0 :(得分:1)

您应该已经在 get_url() __init__() 方法内调用了 VotingForm 方法>课

尝试一下

class VotingForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request', None)
        super(VotingForm, self).__init__(*args, **kwargs)
        self.fields['aspirants'].choices = self.get_url() # change is here 

    def get_url(self):
        self._ = []
        for post in Position.objects.all():
            if self.request.get_full_path() == "/post/pro":
                no_ = Position.objects.get(post='PRO')
                self._.clear()
                for i in Aspirant.objects.filter(post=no_):
                    self._.append(tuple([i.name, i.name]))
            elif self.request.get_full_path() == "/post/gen-sec":
                no_ = Position.objects.get(post='General Secretary')
                self._.clear()
                for i in Aspirant.objects.filter(post=no_):
                    self._.append(tuple([i.name, i.name]))

        return _

    CHOICES = [] # change is here 

    aspirants = forms.ChoiceField(choices=CHOICES, widget=forms.RadioSelect)

    class Meta:
        model = Aspirant
        fields = ['aspirants']