簡體   English   中英

POST請求中的數據未從模板/表單傳遞到Django中進行查看

[英]Data from POST request not passed from template/form to view in django

實際上,我不太確定問題到底出在哪里,但是我認為表單/模板中的數據沒有傳遞到Django應用程序的視圖中。

運行測試可以得出:

AttributeError: 'NoneType' object has no attribute 'id'

表格:

    <form action="/{{ link.id }}/{{ node.id }}/" method="post" class="comment-form">
        {% csrf_token %}
        {% for field in form %}
            {{ field.label_tag }} {{ field }}
            {% if field.help_text %}
            <p class="help">{{ field.help_text|safe }}</p>
            {% endif %}
        {% endfor %}
        <input type="submit" value="submit">
    </form>

風景:

def comments(request, link_id, comment_id=None):
    link = get_object_or_404(Link, pk=link_id)
    if comment_id is not None:
        parent = get_object_or_404(Comment, pk=comment_id)
    else:
        parent = None
    comments = link.comments.all()
    if request.method == 'POST':
        if request.user.is_authenticated():
            form = CommentForm(data=request.POST,auto_id=True)
            if form.is_valid():
                form.full_clean()
                new_comment = form.save(commit=False)
                new_comment.link = link
                new_comment.parent = parent
                new_comment.save()
                return reverse('comments', kwargs={'link_id':link.id,'comment_id':parent.id})
        else:
            return HttpResponseRedirect('/accounts/login/?next=/{0}/'.format(link.id))
    else:
        form = CommentForm(auto_id=True)
        return render(request, 'posts/comments.html', {'nodes':comments, 'link': link, 'form': form})

完整的相關代碼在這里 ,因為對於一個stackoverflow帖子可能要花很多。 (是否有指導方針?)

這是(目前正在運行) 項目

這是回溯的關鍵部分。

    File "/Users/robin/learning/python/parrot/posts/views.py", line 42, in comments
return reverse('comments', kwargs={'link_id':link.id,'comment_id':parent.id})

AttributeError:“ NoneType”對象沒有屬性“ id”

由於link不能為None,這表明parentNone 如果parent_id為None,則可能需要使用其他URL。

該視圖應返回HttpResponse而不是url。 我想你要:

return HttpResponseRedirect(reverse('comments', kwargs={'link_id':link.id,'comment_id':parent.id}))

或者您可以使用redirect快捷方式:

from django.shortcuts import reverse
return redirect('comments', link_id=link.id, comment_id=parent.id)

您認為:

    if comment_id is not None:
        parent = get_object_or_404(Comment, pk=comment_id)
    else:
        parent = None

但是似乎您永遠不會傳遞comment_id ,而只會傳遞link_id ,因此在這一行中:

return reverse('comments', kwargs={'link_id':link.id,'comment_id':parent.id})

parent永遠是無。

這將有助於查看您的url映射以及CommentForm。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM