POST Django中FormView的方法?

POST method of FormView in Django?

编辑:只是在用户提交用户进行搜索时使用了一个新列表,尽管我不确定如何在我的 QueryUser class 中获取用户提交的内容(24 的 ID 只是一个测试,哦,我试着添加分页但把它撕掉了,因为当有人点击一个新页面时它会中断,会返回到下面发布的 Query.html,脆皮表格不是返回的数据)

class QueryUser(LoginRequiredMixin, FormView):
    model = OnSiteLog
    form_class = QueryForm
    template_name = 'log/query.html'
    success_url = '/'
    def form_valid(self, form, *args, **kwargs):
        user = form.cleaned_data.get('user')

    def post(self, request, *args, **kwargs):
        object_list = OnSiteLog.objects.filter(user_id=24).order_by('-checkIn')
        super(QueryUser, self).post(request, *args, **kwargs)
        page = request.GET.get('page', 1)

        paginator = Paginator(object_list, 10) # 3 posts in each page
      #make a map into the object list
      
        try:
            log_pages = paginator.page(page)
        except PageNotAnInteger:
            # If page is not an integer deliver the first page
            log_pages = paginator.page(1)
        except EmptyPage:
            # If page is out of range deliver last page of results
            log_pages = paginator.page(paginator.num_pages)

        return render(request, 'log/query2.html', {'page':page, 'log':object_list, 'object_list':log_pages})

我想了解 Class 基于视图 在 Django 中的工作原理。我有 View 的下一个工作代码。我想在 FormView 的帮助下编写该代码。我的 `FormView 代码是否正确?我需要有人能够分析该代码并指出我的错误在哪里。如有任何帮助,我将不胜感激。

现在 get method 有效。问题是当我尝试 submit 形式时。表格不会消失。同时在控制台中我看到这个 url: "POST /url/ HTTP/1.1" 200 1891。在数据库中,我看到创建了新文章。如何用 post method 解决这个奇怪的问题?

带视图的 CBV:

class ArticleCreateView(FormView):
    template_name = 'article/create_article.html'
    form_class = ArticleForm

    def post(self, request):
        data = dict()
        article_create_form = ArticleForm(request.POST, request.FILES)
        if article_create_form.is_valid():
            article_create_form.save()
            data['form_is_valid'] = True
            context = {
                'articles': Article.objects.all()
            }
            data['html_articles'] = render_to_string(
                'article/articles.html',
                context
            )
        else:
            data['form_is_valid'] = False
        return JsonResponse(data)

    def get(self, request):
        data = dict()
        article_create_form = ArticleForm()
        context = {
            'article_create_form': article_create_form
        }
        data['html_article_create_form'] = render_to_string(
            'article/create_article.html',
            context,
            request=request
        )
        return JsonResponse(data)

带 FormView 的 CBV:

class ArticleCreateView(FormView):
    template_name = 'article/create_article.html'
    form_class = ArticleForm
    form_dict = {
        'Article_create_form': ArticleForm
    }

    def get(self, request):
        data = dict()
        context = {'article_create_form': ArticleForm()}
        data['html_article_create_form'] = render_to_string(
            'article/create_article.html', context, request=request
        )
        return JsonResponse(data)

    def form_valid(self, form):
        data = dict()
        self.object = form.save()
        context = {'articles': Article.objects.all()}
        data['html_articles'] = render_to_string(
            'article/articles.html',
            context
        )
        return JsonResponse(data)

编辑文章 FormView 代码:

class ArticleEditView(FormView):
    template_name = 'article/edit_article.html'
    form_class = ArticleForm

    def get(self, request, pk):
        data = dict()
        context = {
            'article': Article.objects.get(pk=pk),
            'article_edit_form': ArticleForm(instance=Article.objects.get(pk=pk))
        }
        data['html_article_edit_form'] = render_to_string(
            'article/edit_article.html', context, request=request
        )
        return JsonResponse(data)

    def form_valid(self, form):
        form.save()
        data = dict()
        data['form_is_valid'] = True
        context = {'articles': Article.objects.all()}
        data['html_articles'] = render_to_string('article/articles.html', context)
        return JsonResponse(data)

错误:

Traceback (most recent call last):
  File "/srv/envs/py27/lib/python2.7/site-packages/django/core/handlers/exception.py", line 41, in inner
    response = get_response(request)
  File "/srv/envs/py27/lib/python2.7/site-packages/django/core/handlers/base.py", line 217, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/srv/envs/py27/lib/python2.7/site-packages/django/core/handlers/base.py", line 215, in _get_response
    response = response.render()
  File "/srv/envs/py27/lib/python2.7/site-packages/django/template/response.py", line 107, in render
    self.content = self.rendered_content
  File "/srv/envs/py27/lib/python2.7/site-packages/django/template/response.py", line 84, in rendered_content
    content = template.render(context, self._request)
  File "/srv/envs/py27/lib/python2.7/site-packages/django/template/backends/django.py", line 66, in render
    return self.template.render(context)
  File "/srv/envs/py27/lib/python2.7/site-packages/django/template/base.py", line 207, in render
    return self._render(context)
  File "/srv/envs/py27/lib/python2.7/site-packages/django/template/base.py", line 199, in _render
    return self.nodelist.render(context)
  File "/srv/envs/py27/lib/python2.7/site-packages/django/template/base.py", line 990, in render
    bit = node.render_annotated(context)
  File "/srv/envs/py27/lib/python2.7/site-packages/django/template/base.py", line 957, in render_annotated
    return self.render(context)
  File "/srv/envs/py27/lib/python2.7/site-packages/django/template/defaulttags.py", line 458, in render
    url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app)
  File "/srv/envs/py27/lib/python2.7/site-packages/django/urls/base.py", line 91, in reverse
    return force_text(iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)))
  File "/srv/envs/py27/lib/python2.7/site-packages/django/urls/resolvers.py", line 497, in _reverse_with_prefix
    raise NoReverseMatch(msg)
NoReverseMatch: Reverse for 'article_edit' with arguments '('',)' not found. 1 pattern(s) tried: [u'administration/article/(?P<pk>\d+)/edit/$']

articles.html:

{% for article in articles %}
<div class="list-group-item" data-id='{{ article.id }}'>
   <button class="btn slideEditBtn" data-url="{% url 'article:article_edit' pk=slide.id %}">
        <i class="fa fa-pencil" aria-hidden="true"></i>
    </button>
</div>
{% endfor %}

当您的表单有效时,您发送回数据的 JsonResponse。您想要的是将用户重定向到包含一些消息的页面。

使用重定向! https://docs.djangoproject.com/en/1.11/topics/http/shortcuts/#redirect

一些简单的东西,例如:

return redirect('form-thankyou')

当然还要添加一个 url 模式,其 url 名称为 form-thankyou

这个问题与您的观点没有任何关系。您发送 json 回复的事实意味着您在这里使用 Ajax;这意味着您已明确承担从浏览器更改页面的责任。

您的 Ajax 脚本需要在成功提交后执行某些操作。

您忘记将 form_is_valid 添加到 data

def form_valid(self, form):
    data = dict()
    self.object = form.save()
    context = {'articles': Article.objects.all()}
    data['html_articles'] = render_to_string(
        'article/articles.html',
        context
    )
    # NEXT LINE
    data['form_is_valid'] = True
    return JsonResponse(data)