Question: django logout me after render_to_response()

Question

django logout me after render_to_response()

Answers 2
Added at 2016-12-27 13:12
Tags
Question

this is my 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)

and createPost.html code that i want show the post page with errors

{% 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 %}

But when the error happens, it redirects and logs me out . How can I post the authenticated user to my post page ? enter image description here

Answers to

django logout me after render_to_response()

nr: #1 dodano: 2016-12-27 13:12

You shoud use render instead, render_to_response does not make request available see documentation:

This function preceded the introduction of render() and works similarly except that it doesn’t make the request available in the response. It’s not recommended and is likely to be deprecated in the future.

That is why {% if request.user.is_authenticated %} validation in template not passed.

nr: #2 dodano: 2016-12-27 13:12

You should probably use render with request

rewrite your else part in views.py

e.g -

else:
        context ={      
        'form': form,

        }

        return render(request, 'createPost.htm', context)
Source Show
◀ Wstecz