我有一个继承自通用CreateView的视图,并覆盖了get_initial方法,如下所示:
class PosterVisualCreateView (ModelFormMixin, generic.edit.CreateView, ObjectClassContextMixin):
model = Poster
valid_message = "Successfully created object."
template_name = "poser/create_poster_visual.html"
def get_form_class (self):
return super(PosterVisualCreateView, self).get_form_class(extra="CreateVisual")
def get_form_kwargs (self):
kwargs = super(PosterVisualCreateView, self).get_form_kwargs()
kwargs.update({
"company": self.request.company
})
return kwargs
def get_context_data (self, **kwargs):
context = super(PosterVisualCreateView, self).get_context_data(**kwargs)
context.update({
"company": self.request.company,
})
return context
def get_initial (self):
initial = super(PosterVisualCreateView, self).get_initial()
initial.update({
"company": self.request.company,
"template": self.request.company.template_set.all().first()
})
return initial
def form_valid(self, form):
success_url = super(PosterVisualCreateView, self).form_valid(form)
attributes = form.instance.create_attributes()
for attribute in attributes:
attribute.poster = form.instance
attribute.save()
form.instance.save()
form.instance.render_html(commit=True)
form.instance.save()
return success_url
@method_decorator(login_required)
def dispatch (self, *args, **kwargs):
return super(PosterVisualCreateView, self).dispatch(*args, **kwargs)
页面呈现此表单:
class PosterFormCreateVisual (CompanyHiddenForm):
"""Create form for Posters."""
template = fields.ModelChoiceField(widget=forms.RadioSelect, queryset=Template.objects.all())
product = fields.ModelChoiceField(widget=forms.Select, queryset=Product.objects.all(),
required=False)
class Meta:
model = Poster
fields = ("template", "product", "company")
def __init__ (self, *args, **kwargs):
company = kwargs.pop("company", None)
assert company is not None, "Company is required to create attribute form."
super(PosterFormCreateVisual, self).__init__(*args, **kwargs)
self.fields["template"].queryset = company.template_set.all()
self.fields["product"].queryset = company.product_set.all()
初始值应该是模板的无线电选择中的第一项,但事实并非如此,任何人都可以帮助我吗?
答案 0 :(得分:0)
试试这个:
"template": self.request.company.template_set.all().first()
但据我所知,原始代码也应该有用。
顺便说一下,你是如何测试表格的?通过点击"刷新"按钮或Ctrl-R
/ F5
键?某些浏览器重新加载页面但保存以前选择/输入的表单值。要检查初始值,您应重新加载表单页面,方法是单击地址栏(或按Ctrl-L
),然后按Enter
键。