Wednesday, May 27, 2020

Redirect to login page without losing content of form

I have problem similar to this one: https://stackoverflow.com/questions/50272631/django-form-data-lost-on-making-login-required-on-post
I want answer to be added if user is logged in otherwise redirect user to login page, let him login and then add his answer. My problem is that I lose content of the form.
At the moment I'm getting this errror:
The view questions.views.answer didn't return an HttpResponse object. It returned None instead.


def question(request, question_id):
question = get_object_or_404(Question, pk=question_id)
form = AnswerForm()
return render(request, 'questions/question.html', {'question': question, 'form' : form},)

@login_required
def answer(request, question_id):
question = get_object_or_404(Question, pk=question_id)
form = AnswerForm(request.POST) if request.method == 'POST' else AnswerForm()
if form.is_valid():
answer = form.save(commit=False)
answer.author = request.user
answer.question = question
answer.save()
return HttpResponseRedirect(reverse('question', args=(question.id,)))



<form method="POST" action="{% url 'answer' question.id %}">
{% csrf_token %}
{{form.as_p}}
<input type="submit" value="Odpowiedz">
</form>

form method="post" action="{% url 'login' %}">
{% csrf_token %}
{{ form.as_p }}
<input type="hidden" name="next" value="{{request.GET.next}}" />
<input type="submit" value="login" />
</form>

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/4d2bd93d-3a92-4e14-9b8b-f758616c6cfb%40googlegroups.com.

No comments:

Post a Comment