Django在Form Action Parameter中替代PK

时间:2019-04-18 23:01:43

标签: javascript python ajax django django-rest-framework

我有两个具有亲子关系的模型:IdeaComment。我正在使用DRF和嵌套的DataTables将这些模型提供给浏览器。要创建评论,必须知道相应的想法ID。创建新评论的按钮如下所示,其中parentObjDataIdea id:

<button type="button" class="btn btn-primary js-create-idea-comment" data-url="/platform/ideas/comments/' + parentObjData + '/create/"><span class="fa fa-plus"></span> New Comment</button>

单击时会发生:

var loadForm = function () {
  var btn = $(this)
  $.ajax({
    url: btn.attr("data-url"),
    type: 'get',
    dataType: 'json',
    beforeSend: function () {
      $("#modal-activity").modal()
    },
    success: function (data) {
      $("#modal-activity .modal-content").html(data.html_form)
    }
  })
}

这可行,单击每个按钮时,将发送对正确URL的请求。这些视图说明了成功请求应该发生的情况:

def save_comment_form_create(request, form, template_name, parent_id):
    data = dict()
    if request.method == 'POST':
        if form.is_valid():
            instance = form.save(commit=False)
            instance.created_by_id = request.user.id
            instance.idea_id = parent_id
            form.save()
            data['form_is_valid'] = True
            comments = IdeaComment.objects.all()
            data['html_idea_comment_list'] = render_to_string('ic/includes/partial_idea_comment_list.html', {
                'comments': comments
            })
        else:
            data['form_is_valid'] = False
    context = {'form': form}
    data['html_form'] = render_to_string(template_name, context, request=request)
    return JsonResponse(data)


def idea_comment_create(request, parent_id):
    idea_id = parent_id
    if request.method == 'POST':
        form = IdeaCommentForm(request.POST)
    else:
        form = IdeaCommentForm()
    return save_comment_form_create(request, form, 'ic/includes/partial_idea_comment_create.html', idea_id)

partial_idea_comment_create.html解析为以下形式:

<form method="post" action="{% url 'idea_comment_create' parent_id %}" class="js-idea-comment-create-form">
  {% csrf_token %}
  <div class="modal-header">
    <h4 class="modal-title">New Comment</h4>
    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
      <span aria-hidden="true">&times;</span>
    </button>
  </div>
  <div class="modal-body">
    {% include 'ic/includes/partial_idea_comment_form.html' %}
  </div>
  <div class="modal-footer">
    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
    <button type="submit" class="btn btn-primary">Create</button>
  </div>
</form>

这是URL:

url(r'^platform/ideas/comments/(?P<parent_id>\d+)/create/$', views.idea_comment_create, name='idea_comment_create'),

parent_id是问题所在。如果我将数字硬编码到partial_idea_comment_create.html中,那么一切都会很好(除非注释有错误的意思)。现在,我收到此错误:

NoReverseMatch at /platform/ideas/comments/1/create/
Reverse for 'idea_comment_create' with arguments '('',)' not found. 1 pattern(s) tried: ['platform/ideas/comments/(?P<parent_id>\\d+)/create/$']

对于不依赖父实例的普通pk,我会这样做:

<form method="post" action="{% url 'idea_update' form.instance.pk %}">

如何将parent_id动态加载到该URL中?

我认为这个问题部分存在:How do I pass a parent id as an fk to child object's ModelForm using generic class-based views in Django?,但我无法让它对我有用。

1 个答案:

答案 0 :(得分:1)

问题在于您没有在模板上下文中传递parent_id。这是您在save_comment_form_create方法中应该做的:

...
context = {'form': form, 'parent_id': parent_id}
data['html_form'] = render_to_string(template_name, context, request=request)
return JsonResponse(data)