我有一个ModelForm,我想在多个地方显示。 例如,在ListView中,在文章列表下面。 我可以通过将它放在ListView中的get_context_data()中来实现。 我还想在自己的模板中显示表单。
我已经为表单创建了一个视图,但我不确定如何实际编写它。
我在我的模型中定义了一个get_absolute_url() :
class Article(models.Model): author = models.ForeignKey('auth.User') title = models.CharField(max_length=200) text = models.TextField() categories = models.ManyToManyField(Category) city = models.ForeignKey(City) def __str__(self): return self.title def get_absolute_url(self): return reverse_lazy('article', args=self.id)表单的视图本身是:
Views.py
class ArticleSubmitView(CreateView): model = Article form_class = ArticleSubmitForm # is initial necessary? inital = {'title': '', 'text': '', 'categories': '', 'city': ''} # success url not necessary because model has get_absolute_url # however it does not redirect to the article template_name = 'articles/article-submit.html' # handle post data from other template/view # ???模板包含表单(ListView模板的相同内容)。
article-submit.html
{% extends 'articles/base.html' %} {% block article-submit %} {% include 'articles/article-form.html' %} {% endblock article-submit %}表单提交到调用CreateView的url:
article-form.html
<form action="{% url 'article-submit' %}" method="POST"> {% csrf_token %} {% for field in form %} <!--- etc. ---> {% endfor %} </form>urls.py
from django.conf.urls import url from .views import ArticlesView, ArticleSubmitView urlpatterns = [ url(r'^$', ArticlesView.as_view(), name='articles'), # some urls left out for brevity url(r'^article-submit/$', ArticleSubmitView.as_view(), name='article-submit'), ]但是,表单不会从列表模板提交,也不会从表单模板本身提交。 它也不会重定向或显示任何错误消息。
我究竟做错了什么?
完整代码可在此处获得 。
编辑:
检查表单是否有效,这表明表单实际上无效:
class ArticleSubmitView(CreateView): model = Article form_class = ArticleSubmitForm # success url not necessary because model has get_absolute_url # however it does not redirect to the article template_name = 'articles/article-submit.html' # handle post data from other template/view # ??? def form_valid(self, form): print('form is valid') def form_invalid(self, form): print('form is invalid') print(form.errors)但是我得到: AttributeError at /article-submit/ 'ArticleSubmitForm' object has no attribute 'errors'
将表单呈现为{{form}}时,会发生同样的事情
I have a ModelForm that I’d like to display in multiple places. For instance, in a ListView, underneath the list of articles. I can do this by putting it in get_context_data() in the ListView. I’d also like to display the form in its own template.
I’ve created a view for the form, but am not sure how to actually write it.
I’ve defined a get_absolute_url() in my model:
class Article(models.Model): author = models.ForeignKey('auth.User') title = models.CharField(max_length=200) text = models.TextField() categories = models.ManyToManyField(Category) city = models.ForeignKey(City) def __str__(self): return self.title def get_absolute_url(self): return reverse_lazy('article', args=self.id)The view for the form itself is:
Views.py
class ArticleSubmitView(CreateView): model = Article form_class = ArticleSubmitForm # is initial necessary? inital = {'title': '', 'text': '', 'categories': '', 'city': ''} # success url not necessary because model has get_absolute_url # however it does not redirect to the article template_name = 'articles/article-submit.html' # handle post data from other template/view # ???The template includes the form (same thing for the ListView template).
article-submit.html
{% extends 'articles/base.html' %} {% block article-submit %} {% include 'articles/article-form.html' %} {% endblock article-submit %}The form submits to the url that calls the CreateView:
article-form.html
<form action="{% url 'article-submit' %}" method="POST"> {% csrf_token %} {% for field in form %} <!--- etc. ---> {% endfor %} </form>urls.py
from django.conf.urls import url from .views import ArticlesView, ArticleSubmitView urlpatterns = [ url(r'^$', ArticlesView.as_view(), name='articles'), # some urls left out for brevity url(r'^article-submit/$', ArticleSubmitView.as_view(), name='article-submit'), ]However, the form does not submit from the list template, nor does it submit from the form template itself. It also doesn’t redirect, or show any error messages.
What am I doing wrong?
Full code is available here.
edit:
Checking to see if the form is valid or not like this shows me that the form is actually not valid:
class ArticleSubmitView(CreateView): model = Article form_class = ArticleSubmitForm # success url not necessary because model has get_absolute_url # however it does not redirect to the article template_name = 'articles/article-submit.html' # handle post data from other template/view # ??? def form_valid(self, form): print('form is valid') def form_invalid(self, form): print('form is invalid') print(form.errors)However I get: AttributeError at /article-submit/ 'ArticleSubmitForm' object has no attribute 'errors'
Same thing happens when rendering the form as just {{ form }}
最满意答案
事实证明,我不需要django-betterforms。 常规模型可以正常工作。 还有其他一些错误。
这是代码。
models.py
class Article(models.Model): author = models.ForeignKey('auth.User') title = models.CharField(max_length=200) text = models.TextField() categories = models.ManyToManyField(Category) city = models.ForeignKey(City) def __str__(self): return self.title def get_absolute_url(self): return reverse_lazy('article', kwargs={'pk': self.id})views.py
class ArticleSubmitView(CreateView): model = Article form_class = ArticleForm template_name = 'articles/article-submit.html' def form_valid(self, form): print('form is valid') print(form.data) obj = form.save(commit=False) obj.author = self.request.user obj.save() return HttpResponseRedirect(reverse('article', kwargs={'pk': obj.id}))网址和模板保持(大部分)如上所述。
As it turns out, I don’t need django-betterforms. A regular modelform works just fine. There were some other mistakes as well.
This is the code.
models.py
class Article(models.Model): author = models.ForeignKey('auth.User') title = models.CharField(max_length=200) text = models.TextField() categories = models.ManyToManyField(Category) city = models.ForeignKey(City) def __str__(self): return self.title def get_absolute_url(self): return reverse_lazy('article', kwargs={'pk': self.id})views.py
class ArticleSubmitView(CreateView): model = Article form_class = ArticleForm template_name = 'articles/article-submit.html' def form_valid(self, form): print('form is valid') print(form.data) obj = form.save(commit=False) obj.author = self.request.user obj.save() return HttpResponseRedirect(reverse('article', kwargs={'pk': obj.id}))The urls and templates remain (largely) as above.
更多推荐
form,url,电脑培训,计算机培训,IT培训"/> <meta name="description" co
发布评论