关于基于类的视图的Django 1.3文档看起来像是寻宝。如何编写类很清楚......但是什么样的模板代码匹配每个泛型类?有人会为坚果提供完整的示例汤吗?这是我到目前为止所做的:
(r'^brand_create2$', BrandCreate.as_view()),
from django.views.generic import CreateView
@login_required
class BrandCreate(CreateView):
template_name = 'generic_form_popup.html'
context_object_name = "brand_thingie"
#queryset = models.Brand.objects.all()
success_url = '/'
????
在这种情况下,我正在探索是否值得学习新款式,因为旧款式仍然有效:
url(r'^brand_create1$', 'coat.views.brand_create'),
class formBrand(forms.ModelForm):
class Meta:
model = models.Brand
exclude = ('')
@login_required
def brand_create(request):
form = formBrand
if request.method == 'POST':
form = formBrand(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/')
passed = dict(
form=form,
MEDIA_URL = settings.MEDIA_URL,
STATIC_URL = settings.STATIC_URL)
return render_to_response('generic_form_popup.html',
passed, context_instance=RequestContext(request))
{% extends 'head-plain.html' %}
{% block title %}{% endblock %}
{% block headstuff %}{% endblock %}
{% block content %}
<form action="{{ action }}" method="post">
{% csrf_token %}{{ form.as_p }}
<input type="submit" value="Submit" /> </form>
{% endblock %}
答案 0 :(得分:0)
CreateView 继承自ModelFormMixin ,而继承自FormMixin和SingleObjectMixin 。
SingleObjectMixin提供了对象模板上下文变量,在CreateView的情况下可能不会有任何用处:
object:此视图正在显示的对象。如果指定了context_object_name,那么该变量也将在上下文中设置,其值与object相同。
但是 FormMixin提供了表单上下文变量:
form:为视图生成的表单实例。
因此,您可以将文档引用至display a form with a template :
<form action="/contact/" method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>
这意味着您发布的模板应该几乎使用基于类的视图:
{% extends 'head-plain.html' %}
{% block title %}{% endblock %}
{% block headstuff %}{% endblock %}
{% block content %}
<form action="" method="post">
{% csrf_token %}{{ form.as_p }}
<input type="submit" value="Submit" /> </form>
{% endblock %}
我删除了{{ action }}
,因为它不是上下文的一部分,既不是旧式视图,也不是基于类的视图,所以它没有任何意义。您应该知道 if action =“”然后浏览器将提交到当前网址。您可以使用action =“{{request.path}}”将操作强制设置为当前网址,也可以使用url template tag指定其他网址。
假设通过更改:
来应用naming url patterns的最佳做法(r'^brand_create2$', BrandCreate.as_view()),
为:
(r'^brand_create2$', BrandCreate.as_view(), name='band_create'),
然后你可以使用:action="{% url band_create %}"
。
您还可以customize further:
<form action="/contact/" method="post">
{% csrf_token %}
{{ form.non_field_errors }}
<div class="fieldWrapper">
{{ form.subject.errors }}
<label for="id_subject">Email subject:</label>
{{ form.subject }}
</div>
<div class="fieldWrapper">
{{ form.message.errors }}
<label for="id_message">Your message:</label>
{{ form.message }}
</div>
<div class="fieldWrapper">
{{ form.sender.errors }}
<label for="id_sender">Your email address:</label>
{{ form.sender }}
</div>
<div class="fieldWrapper">
{{ form.cc_myself.errors }}
<label for="id_cc_myself">CC yourself?</label>
{{ form.cc_myself }}
</div>
<p><input type="submit" value="Send message" /></p>
</form>
当然,表单中可用的字段取决于您的模型。