[英]How to call form in template when using generic.FormView in django?
This is my form class: from django import forms 这是我的表单类:从Django导入表单
from .models import Category
class AddResource(forms.Form):
CATEGORY_CHOICES = [cat.title for cat in Category.objects.all()]
ResourceTitle = forms.CharField()
Description = forms.Textarea()
Link = forms.URLField()
Categories = forms.MultipleChoiceField(choices=CATEGORY_CHOICES)
This is my view for the form URL: 这是表单URL的视图:
from django.shortcuts import render
from django.views.generic import View, TemplateView, FormView
from .models import *
from .forms import AddResource
class AddResourceView(FormView):
template_name = 'addRes.html'
form_class = AddResource
success_url = '/'
def get_form(self, form_class):
return form_class()
def form_valid(self, form):
print form
return super(AddResourceView, self).form_valid(form)
The trouble that I'm having is calling this inside templates. 我遇到的麻烦是在模板内部调用它。 How do I call the form that I assigned inside of django-templates?
如何调用在django-templates内部分配的表单?
The FormView
supplies a context variable called form
that holds your actual form object, so you can use: FormView
提供了一个名为form
的上下文变量,该变量保存您的实际表单对象,因此您可以使用:
{{ form.as_table }}
Or any of the other rendering options that form
supplies. 或
form
耗材的任何其他渲染选项。 See: https://docs.djangoproject.com/en/dev/topics/forms/#displaying-a-form-using-a-template 请参阅: https : //docs.djangoproject.com/en/dev/topics/forms/#displaying-a-form-using-a-template
I found the answer. 我找到了答案。 Its how you include choices in django forms.
它是如何包含Django形式的选择的。 So
CATEGORY_CHOICES
has to be a list of tuples, which it was not in this case. 因此
CATEGORY_CHOICES
必须是一个元组列表,在这种情况下不是。
Thus, this simple change made it work: 因此,这个简单的更改使其起作用:
CATEGORY_CHOICES = [('', cat.title)
for cat in Category.objects.all()]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.