Skip to main content
 首页 » 编程设计

python之在 forms.py 中使用请求对象

2024年11月24日10开发

我正在开发一个电子投票系统,有抱负的人可以竞争特定的职位。我正在尝试创建一个表格,其中在 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' is not defined

请您参考如下方法:

您应该在 __init__() 方法中调用 get_url() 方法 < strong>VotingForm类

试试这个,

class VotingForm(forms.ModelForm): 
 
    def __init__(self, *args, **kwargs): 
        self.request = kwargs.pop('request', None) 
        super(VotingForm, self).__init__(*args, **kwargs) 
        <b>self.fields['aspirants'].choices = self.get_url() # change is here </b> 
 
    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 _ 
 
    <b>CHOICES = [] # change is here </b> 
 
    aspirants = forms.ChoiceField(choices=CHOICES, widget=forms.RadioSelect) 
 
    class Meta: 
        model = Aspirant 
        fields = ['aspirants']