Django评论应用提交表单时自动登出的问题排查求助
Let's troubleshoot why your comment submission is logging you out instead of taking you to the comment list. Here are the key issues in your code and how to fix them:
1. Fix the misdirected form action (most likely culprit)
Your form uses {% url 'create' %} for the action, but without a URL namespace, Django might be resolving this to the wrong endpoint (or failing silently). Let's add a namespace to your usercomments URLs to avoid conflicts:
First, update usercomments/urls.py to include an app namespace:
from django.conf.urls import url from . import views app_name = 'usercomments' # Add this line to define the namespace urlpatterns = [ url(r'^$',views.comments_list, name="list"), url(r'^create/$', views.comments_create, name="create"), url(r'^(?P<slug>[\w-]+)/$',views.comments_detail, name="detail"), ]
Then modify your template's form action to use the namespace:
<form class="site-form" action="{% url 'usercomments:create' %}" method="post">
This ensures the form submits to the correct comments_create view instead of accidentally hitting the logout endpoint.
2. Fix the broken logout view
Your current logout_view doesn't return a response for GET requests, which violates Django's requirement that all views return an HttpResponse. This can cause unexpected errors that might trigger your logout flow. Update it to handle all request methods properly:
from django.http import HttpResponseNotAllowed from django.shortcuts import redirect, logout def logout_view(request): if request.method == 'POST': logout(request) return redirect('/') else: # Reject GET requests (prevents accidental logouts via links) return HttpResponseNotAllowed(['POST']) # Or redirect to home: return redirect('/')
3. Associate comments with the logged-in user
If your Comment model has a user foreign key (which it should for authenticated comments), your current form.save() doesn't set this value—this will throw a database integrity error. Fix the comments_create view to link the comment to the current user:
@login_required(login_url='/userprofile/login/') def comments_create(request): if request.method == 'POST': form = forms.CreateComment(request.POST) if form.is_valid(): # Create a comment instance but don't save to DB yet comment = form.save(commit=False) # Link to the currently logged-in user comment.user = request.user comment.save() # Now save to DB return redirect('/usercomments') else: form = forms.CreateComment() return render(request,'usercomments/comments_create.html', {'form':form})
4. Verify CSRF token is present
Check your rendered page source to ensure the {% csrf_token %} tag generates a hidden input field like this:
<input type='hidden' name='csrfmiddlewaretoken' value='[your-token-value]' />
A missing or invalid CSRF token will trigger a 403 error, and if your error handling flows into logout logic, that could cause the unexpected sign-out.
内容的提问来源于stack exchange,提问作者Robin Peyret

