Задать вопрос
@nurzhannogerbek

FormView для формы редактирования?

Здравствуйте! Помогите пожалуйста разобраться.

Пытаюсь переписать код вьюхи c CBV(View) на CBV(FormView). CBV(View) работает прекрасно, но вот CBV(FormView) выдает ошибку, когда нажимаю кнопку submit в форме редактирования. Метод get работает верно, я получаю форму редактирования с актуальными данными. Думаю проблема либо в методе form_valid или в том, что я забыл что-то прописать дополнительно в CBV(FormView). Где я совершил ошибку?

CBV(View):
class ArticleEditView(View):
    def post(self, request, pk, *args, **kwargs):
        data = dict()
        article = Article.objects.get(pk=pk)
        article_edit_form = ArticleForm(
            request.POST,
            request.FILES,
            instance=article
        )
        if article_edit_form.is_valid():
            article_edit_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, pk, *args, **kwargs):
        data = dict()
        article = Article.objects.get(pk=pk)
        article_edit_form = ArticleForm(instance=article)
        context = {
            'article': article,
            'article_edit_form': article_edit_form
        }
        data['html_article_edit_form'] = render_to_string(
            'article/edit_article.html',
            context,
            request=request
        )
        return JsonResponse(data)


CBV(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)


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


urls.py:
urlpatterns = [
    # Edit Article
    url(r'^(?P<pk>\d+)/edit/$',
        ArticleEditView.as_view(),
        name='article_edit'),
]


JS code:
$("#articleModalBox").on("submit", ".articleEditForm", function(){
    	var form = $(this);
        var dataForm = new FormData(form.get(0));
    	$.ajax({
    		url: form.attr("action"),
                data: dataForm,
                type: form.attr("method"),
                dataType: 'json',
                success: function (data) {
                if (data.form_is_valid) {
                    $("#articles").html(data.html_articles);
                    $("#articleModalBox").modal("hide");
                }
                else {
                    $("#articleModalBox .modal-content").html(data.html_article_edit_form);
                }
            },
            cache: false,
            contentType: false,
            processData: false
    	});
    	return false;
    });


ERROR:
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/$']
  • Вопрос задан
  • 466 просмотров
Подписаться 2 Оценить 3 комментария
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы