【问题标题】:Using the request object in forms.py在 forms.py 中使用请求对象
【发布时间】:2019-04-08 11:55:14
【问题描述】:

我正在开发一个电子投票系统,在该系统中,有志于争夺特定职位的人。我正在尝试创建一个表单,其中在 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: name 'self' 未定义

【问题讨论】:

    标签: python django


    【解决方案1】:

    您应该在 VotingForm 类的 __init__() 方法中调用 get_url() 方法

    试试这个,

    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']

    【讨论】:

      猜你喜欢
      • 2012-01-28
      • 2012-08-17
      • 2020-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-19
      • 2016-07-08
      • 2019-05-29
      相关资源
      最近更新 更多