所以基本任务是:使用仅链接到经过身份验证的用户的 dB 中的数据将模板名称和文本添加到带有Selector
小部件的ChoiceField
中的choices
。Template
是作为ForeignKey
链接到用户的模型。
我想通过链接到连接的视图的 Form 类访问请求数据(用户django.views.generic.View
类。
我在这里检查了类似的问题: 对 FormView 中的get_form_kwargs感到好奇
在这里:从 Django 中基于类的通用视图向 ModelForm 发送 request.user 对象
在这里:Django:在干净的函数中访问请求 forms.py
但是,它们不与非FormView
类接触。由于这是相当古老的解决方案,我很好奇是否有更有可能从课堂上接触到request
forms.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(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'], user=request.user)
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')
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=templates, 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();'}))
一般来说,我想实现这样的目标:
`class InformForm(forms.Form):
def get_template_choices(self):
templates = self.request.user.template_set.all()
choices = []
for t in templates:
choices.append((t.text, t.name))
return choices
flight_number = forms.CharField(5, widget=forms.TextInput())
date = forms.DateField(widget=forms.DateInput(attrs={'class':
'datepicker'}))
template = forms.ChoiceField(choices=get_template_choices(),
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();'}))`
我会很感激任何方法,mb 我缺乏知识并问新手问题,对此感到抱歉。
我只想获得python-way
解决方案,而不是构建一些js/jinja
的绕行。
谢谢你的时间!
#在@Danielius评论之后,我做了一些调整:
`class InformForm(forms.Form):
def __init__(self, user=None, *args, **kwargs):
if user:
self.fields['template'] = forms.ChoiceField(choices=tuple([(template.text, template.name) for template in user.template_set.all()]),
widget=forms.Select(attrs={'id': 'select_box', 'onchange': 'javascript:changer();'}))
flight_number = forms.CharField(5, widget=forms.TextInput())
date = forms.DateField(widget=forms.DateInput(attrs={'class': 'datepicker'}))
# template = forms.ChoiceField(choices=templates, 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();'}))`
出现错误AttributeError: 'InformForm' object has no attribute 'fields'
您可以通过更改__init__
方法将请求传递给表单,如下所示:
class InformForm(forms.Form):
...
def __init__(self, user=None,*args, **kwargs):
super(InformForm, self).__init__(**kwargs)
if user:
self.fields['somefield'] = forms.ChoiceField()
self.fields['somefield'].widget = forms.Select()
self.fields['somefield'].queryset = Someobject.objects.filter(User=user)
...
如果用户通过外键链接到 db 中的其他对象,那么您将获得其他对象的所有值作为选择项。
另外,在创建表单时,您可以像这样传递用户:
form= InformForm(user=request.user,data=request.POST)