Django:编辑表单的选择集。在模板

时间:2017-05-15 06:36:51

标签: python django django-templates

亲爱的Python社区,

请您就以下主题与我这样的新手分享一些见解:

我想动态修改表单字段输入的输入,特别是

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

由于我无法从forms.py中的类访问request,因此我想尝试编辑Django template engine中的选项。是否可以使用jinja从views.py方法中获取参数来编辑选项?

问题是概念性的,作为一个例子的几行代码就足够了,我会把它拿起来。

棘手的部分是 - 数据应该依赖于登录用户创建的模型实例。

如果没有实际的方法可以通过python进行,但只有js - 请让我知道,所以我不干不可能。

谢谢!

代码示例供参考:

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();'}))

模板



<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>
&#13;
&#13;
&#13;

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问题:

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

sample = tuple(usr.template_set.all()中模板的[(template.text,template.name)])       Traceback(最近一次调用最后一次):         文件&#34;&#34;,第1行,in       AttributeError:&#39; QuerySet&#39;对象没有属性&#39; template_set&#39;

    
  

1 个答案:

答案 0 :(得分:1)

InformForm班级覆盖__init__

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