0

Dear Python community,

Could you please share some insights with a newbie like myself regarding the following topic:

I would like to dynamically modify the inputs into form field input, specifically

forms.ChoiceField(choices=((text, name), widget=forms.Select())

As I was not able to access requestfrom class in forms.py, I'd like to try editing the choices from Django template engine. Is it possible to edit the choices, taking the parameters from views.py method using jinja?

The question is conceptual, a few lines of code as an example would be enough, I'll pick it up.

The tricky part is - the data should be dependent on logged-in User's created model instances.

If there's no actual way to do it via python, but js only - please let me know so I don't dry to do the impossible.

Thank you!

Code sample for reference:

forms.py

class InformForm(forms.Form):

flight_number = forms.CharField(5, widget=forms.TextInput())
date = forms.DateField(widget=forms.DateInput(attrs={'class': 'datepicker'}))
template = forms.ChoiceField(choices=tuple([(template.text, template.name) for template in Template.objects.all()]),
                             widget=forms.Select(attrs={'id': 'select_box',
                                                        'onchange': 'javascript:changer();'}))
text = forms.CharField(widget=forms.Textarea(attrs={'id': 'txt_box', 'class': 'latin',
                                                    'maxlength': "160", 'onchange': 'javascript:validateTextArea();'}))

template

<form class="form-signin form-container" method="post" enctype="multipart/form-data">
    {% csrf_token %}
    {% for field in form %}
        <div class="form-element-wrapper">
            <div class="error-form-element">
                <span class="error-span">{{field.errors}}</span>
            </div>
            <div class="form-label">{{field.label_tag}}</div>
            <div class="form-data">{{field}}</div>
        </div>
    {% endfor %}
    <button id="cr_inf" type="submit" class="btn btn-lg btn-primary btn-block stl-color"><span id="loader" class=""></span>Create inform</button>
</form>

views.py

class InformFill(View):
form_class = InformForm
temlate_name = 'distrib_db/inform_fill.html'

def get(self, request):
    if request.user.is_authenticated():
        form = self.form_class(None)
        return render(request, self.temlate_name, context={'form': form})
    else:
        return redirect('distrib_db:login')

def post(self, request):
    if request.user.is_authenticated():
        form = self.form_class(user=request.user, data=request.POST)
        if form.is_valid():
            inform = Inform(flt_numbr=form.cleaned_data['flight_number'], date=form.cleaned_data['date'],
                            template=form.cleaned_data['text'], request=request)
            inform.save()
            date = form.cleaned_data['date']
            flt_numbr = form.cleaned_data['flight_number']
            try:
                emails, contacts = get_mail_cnt(date, flt_numbr)
                # inform = get_object_or_404(Inform, pk=request['pk'])
                paxdata = PaxData(inform=inform, emails=' '.join(emails), contacts=' '.join(contacts))
                paxdata.save()
                return redirect('/inform/{0}/'.format(inform.pk))
            # 'distrib_db:detail', context={'pk': inform.id}
            except Exception as e:
                return render(request, 'distrib_db/sample.html',
                              context={'date': date, 'flight_number': flt_numbr, 'error': e})

                # return render(request, 'distrib_db/sample.html', context={'date': date, 'flt_numbr': flt_numbr})

        return render(request, self.temlate_name, context={'form': form})
    else:
        return redirect('distrib_db:login')

QuerySet issue:

>>> usr = User.objects.filter(username='aleks')

sample = tuple([(template.text, template.name) for template in usr.template_set.all()]) Traceback (most recent call last): File "", line 1, in AttributeError: 'QuerySet' object has no attribute 'template_set'

Aleks_Saint
  • 67
  • 1
  • 2
  • 12

1 Answers1

3

In InformForm class override __init__

def __init__(self, user, *args, **kwargs):
    super(InformForm, self).__init__(*args, **kwargs)
    self.fields['template'] = forms.ChoiceField(choices="make choice based on user")
itzMEonTV
  • 19,851
  • 4
  • 39
  • 49