这是我的views.py

def createpost(request, id=None):

    form = PostForm(request.POST or None, request.FILES or None)

    if form.is_valid() and request.method == 'POST':
        instance = form.save(commit=False)
        instance.user = request.user

        instance.save()
        messages.success(request, "successfully create!")
        return HttpResponseRedirect('/post')
    else:
        context ={
        'form': form
        }
    return render_to_response('createPost.html', context)


和createPost.html代码,我要显示错误的帖子页面

{% if form.errors %}
    {% for field in form %}
        {% for error in field.errors %}
            <div class="alert alert-danger">
                <strong>{{ error|escape }}</strong>
            </div>
        {% endfor %}
    {% endfor %}
    {% for error in form.non_field_errors %}
        <div class="alert alert-danger">
            <strong>{{ error|escape }}</strong>
        </div>
    {% endfor %}
{% endif %}

{% if request.user.is_authenticated %}\
    <form method="POST" name="PostForm" action="/post/createpost/" enctype="multipart/form-data"> {% csrf_token %}
        {{form|as_bootstrap_inline}}
        <input type="hidden" name="user_id" value="{{ user.id }}" />
        <button type="submit" class="btn btn-primary">Save AD</button>

{% else %}

    <div>Please Register First!</div>

{% endif %}

    </form>

{% endblock content %}


但是,当错误发生时,它会重定向并注销我。如何将经过身份验证的用户发布到我的帖子页面?
python - django在render_to_response()之后注销我-LMLPHP

最佳答案

您可能应该在请求中使用渲染
  
  在views.py中重写其他部分


例如-

else:
        context ={
        'form': form,

        }

        return render(request, 'createPost.htm', context)

关于python - django在render_to_response()之后注销我,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41345277/

10-11 12:53