基于类的视图CreateView给Form添加初值
2018-12-19 本文已影响0人
吾星喵
基于类的视图CreateView给Form添加初值
知识点:
- 直接在视图中使用
get_form_kwargs
函数,然后再函数内通过initial
给表单传递初值。 - 通过
get_success_url
函数使用reverse_lazy
带参数跳转的方法,跳转到其他页面
表单
class WorksForm(forms.ModelForm):
category = forms.ModelChoiceField(queryset=Category.objects.all(), required=False, label='作品分类', widget=forms.Select(attrs={'class': 'form-control'}))
phase = forms.ModelChoiceField(queryset=Phase.objects.all(), required=False, label='团购期数', widget=forms.Select(attrs={'class': 'form-control'}))
status = forms.ChoiceField(choices=Works.Status, label='状态', widget=forms.Select(attrs={'class': 'form-control'}))
class Meta:
model = Works
fields = '__all__'
视图
@method_decorator(login_required, name='dispatch')
class WorksCreate(CreateView):
"""
新增作品,链接加上参数:{% url 'casual:works_create' %}?phase_id={{ phase_id }}
"""
model = Works
template_name = 'works-edit.html'
form_class = WorksForm
def get_form_kwargs(self):
kwargs = super(WorksCreate, self).get_form_kwargs()
phase_id = self.request.GET.get('phase_id')
if phase_id:
phase = Phase.objects.get(id=phase_id)
print(kwargs) # 进入网页,该字段值:{'initial': {}, 'prefix': None, 'instance': None}
kwargs.update(
{'initial': {'phase': phase}} # 给表单的phase字段传递外键实例
)
return kwargs
def get_success_url(self):
phase_id = self.request.GET.get('phase_id')
# print(phase_id)
if phase_id:
return reverse_lazy('casual:works_list_by_phase', kwargs={'phase_id': phase_id}) # reverse_lazy带参数跳转,键值对
else:
return reverse('casual:works_list')
def get_context_data(self, **kwargs):
context = super(WorksCreate, self).get_context_data(**kwargs)
return context