如何从其他模板中为表单显示和提交编写基于Django类的视图?(How to write Django class

编程入门 行业动态 更新时间:2024-10-28 14:24:36
如何从其他模板中为表单显示和提交编写基于Django类的视图?(How to write Django class-based view for form displaying and submission from other template?)

我有一个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

本文发布于:2023-08-07 19:59:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1465698.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:视图   表单   中为   模板   Django

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!