oluwakayode
oluwakayode

Reputation: 192

Using the request object in forms.py

I am working on an e-voting system where there are aspirants vying for particular positions. I am trying to create a form where the aspirants are displayed per position in RadioSelect buttons.

To do this, I have tried to initialize a for loop through all the objects in the Position() class and used an if statement to compare the current URL path to the get_absolute_url() of each object. I have trouble getting the request module to work.

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

I'm getting this error. I'm not sure what I am doing wrong.

CHOICES = self.get_url()

NameError: name 'self' is not defined

Upvotes: 2

Views: 60

Answers (1)

JPG
JPG

Reputation: 88689

You should've called the get_url() method inside the __init__() method of the VotingForm class

Try this,

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

Upvotes: 1

Related Questions