我正在尝试从Photographer
模型中获取值的字典以显示在我的表单中。之后,用户将选择Photographer
,提交表单(以及其他信息),并使用A
作为属性创建模型Photographer
的实例。虽然我理解ModelForms可以更友好,但在这种情况下我必须使用BaseForm:
@login_required
def create_in(request, slug):
element = get_object_or_404(Element, slug=slug)
a = A.objects.create(element=element, user=request.user)
a.save()
return redirect('CreationEditView', pk=a.pk)
urlconf
将用户发送到create_in,
,其中用户选择element
,然后重定向到CreationEditView,
,class EditView(BaseUpdateView):
model = A
form_class = AForm
context_object_name = 'a'
page = 'edit.html'
def get_element(self):
return self.object.element
def render_to_response(self, context, **response_kwargs):
element = self.get_element()
return render_page(self.request, element,
self.page, context)
def get_success_url(self):
return reverse('view_all')
def get_context_data(self, **kwargs):
context = super(EditView, self).get_context_data(**kwargs)
return context
def get_queryset(self):
qs = super(EditView, self).get_queryset()
return qs.filter(active=True, user=self.request.user)
def get(self, request, *args, **kwargs):
self.object = self.get_object()
return super(EditView, self).get(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
self.object = self.get_object()
return super(EditView, self).post(request, *args, **kwargs)
@method_decorator(login_required)
def dispatch(self, request, *args, **kwargs):
return super(EditView, self).dispatch(request, *args, **kwargs)
class CreationEditView(EditView):
def get_queryset(self):
qs = super(EditView, self).get_queryset()
return qs.filter(active=False, user=self.request.user)
def get_success_url(self):
return reverse('create_finished',
kwargs=dict(pk=self.object.pk))
def get_context_data(self, **kwargs):
context = super(CreationEditView, self).get_context_data(**kwargs)
context['create'] = True
return context
使用来自Django Generic Views的BaseUpdateView操纵对象:
render_page
然后通过def render_page(request, element, page, context):
template_name = element_template_name(element, page)
try:
template = get_template(template_name)
except TemplateDoesNotExist:
template = get_template('template_location/%s' % page)
context = RequestContext(request, context)
return HttpResponse(template.render(context))
呈现页面,如下所示:
class Photographer(models.Model):
name = models.CharField(max_length=20)
models = models.ManyToManyField('Model')
class Model(models.Model):
model = models.CharField(max_length=20, blank=False)
series = models.ForeignKey('Series', null=True, blank=True)
class A(models.Model):
user = models.ForeignKey(User)
photographer = models.ForeignKey('Photographer', blank=True, null=True)
model = models.ForeignKey('Model', blank=True, null=True)
如果我的模型如下:
Photographer
您如何将class AForm(BaseForm):
def __init__(self, data=None, files=None, instance=None, auto_id='id_%s',
prefix=None, initial=None, error_class=ErrorList,
label_suffix=':', empty_permitted=False):
if not instance:
raise NotImplementedError("Instance must be provided")
self.instance = instance
object_data = self.instance.fields_dict()
self.declared_fields = SortedDict()
self.base_fields = fields_for_a(self.instance)
# if initial was provided, it should override the values from instance
if initial is not None:
object_data.update(initial)
BaseForm.__init__(self, data, files, auto_id, prefix, object_data,
error_class, label_suffix, empty_permitted)
cleaned_data = self.cleaned_data
# save fieldvalues for self.instance
fields = field_list(self.instance)
for field in fields:
if field.enable_wysiwyg:
value = unicode(strip(cleaned_data[field.name]))
else:
value = unicode(cleaned_data[field.name])
return self.instance
中的值正确地集成到视图代码中以便稍后在模板中使用?这些值将成为用户将从中选择的下拉表单的一部分。用法示例非常有用。
感谢任何想法。
编辑(添加表格)
{{1}}
答案 0 :(得分:4)
我认为你缺少Django编程的基本方面,即Django形式。您应该创建一个表单,如:
class AForm(forms.Form):
model = forms.ModelChoiceField(queryset=Model.objects.all())
photographer = forms.ModelChoiceField(queryset=Photographer.objects.all())
class Meta:
model = A
fields = ('model', 'photographer', )
然后您的创建视图将类似于:
@login_required
def create_in(request, slug):
if request.method == 'POST':
form = AForm(request.POST)
if form.is_valid():
instance = form.save(commit=False)
instance.user = request.user
return HttpResponseRedirect("/somewhere/")
else:
form = AForm()
return render_to_response('create_in.html', { 'form': form }, context_instance=context)
很难弄清楚你要做什么,我认为你变得过于棘手,因为我从来没有需要扩展BaseForm,而且我已经在选择上使用特殊过滤器做了很多表格。通常这些都是这样的:
class AForm(forms.Form):
def __init__(self, profile, *args, **kwargs):
super(AForm, self).__init__(*args, **kwargs)
self.fields['photographer'].queryset = models.Photographer.objects.filter(profilephotographer__profile=profile)