You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Django中整合首页函数视图与PasswordResetView类视图

正确整合Django PasswordResetView的方法

Hey there! Let's fix this PasswordResetView integration issue—you don't need to copy Django's source code (that's usually a bad call, since Django's built-in views are designed to be extended, not duplicated). Here's the clean, maintainable way to make it work with your existing home view:

1. Inherit Django's Built-in PasswordResetView (Don't Copy Source)

Instead of duplicating Django's code, just inherit the native PasswordResetView and override only the parts you need to customize. This avoids dependency issues and keeps your code concise.

Update your views.py like this:

from django.contrib.auth.views import PasswordResetView, PasswordResetDoneView
from django.urls import reverse_lazy
from django.utils.translation import gettext_lazy as _

# Keep your existing home view exactly as it is
def home(request):
    user = request.user
    signin_form = SigninForm()
    signup_form = SignupForm()
    if 'signin_form' in request.POST:
        signin_form = SigninForm(request.POST)
        if signin_form.is_valid():
            email = request.POST['email']
            password = request.POST['password']
            user = authenticate(email=email, password=password)
            if user:
                login(request, user)
            elif user is None:
                messages.error(request, 'Email or password is incorrect')
    if 'signup_form' in request.POST:
        signup_form = SignupForm(request.POST)
        if signup_form.is_valid():
            signup_form.save()
            full_name = signup_form.cleaned_data.get('full_name')
            email = signup_form.cleaned_data.get('email')
            raw_password = signup_form.cleaned_data.get('password1')
            account = authenticate(email=email, password=raw_password)
            login(request, account)
    context = {'signin_form': signin_form,'signup_form': signup_form}
    return render(request, 'main/home.html', context)

# Custom password reset view (only override what you need)
class CustomPasswordResetView(PasswordResetView):
    # Use your app's template instead of Django's default registration folder
    template_name = 'main/password_reset_form.html'
    # Redirect to home page after successful reset request
    success_url = reverse_lazy('home')
    # Optional: Customize email templates if needed
    # email_template_name = 'main/password_reset_email.html'
    # subject_template_name = 'main/password_reset_subject.txt'
    title = _('Password Reset')

2. Update Your URL Config

Add the password reset routes to your urls.py alongside your home view:

from django.urls import path
from . import views

urlpatterns = [
    path('', views.home, name='home'),
    # Password reset route
    path('password-reset/', views.CustomPasswordResetView.as_view(), name='password_reset'),
    # Required: Password reset confirmation page
    path('password-reset/done/', 
         views.PasswordResetDoneView.as_view(template_name='main/password_reset_done.html'), 
         name='password_reset_done'),
    # Optional: Add remaining reset flow routes if you need full functionality
    # path('reset/<uidb64>/<token>/', views.PasswordResetConfirmView.as_view(), name='password_reset_confirm'),
    # path('reset/done/', views.PasswordResetCompleteView.as_view(), name='password_reset_complete'),
]

3. Embed Reset Form in Home Template (Optional)

If you want users to access the password reset form directly on your home page (instead of a separate page), modify your home view to include the reset form in the context:

from django.contrib.auth.forms import PasswordResetForm

def home(request):
    # ... keep your existing login/registration logic ...

    # Add password reset form to context
    password_reset_form = PasswordResetForm()

    context = {
        'signin_form': signin_form,
        'signup_form': signup_form,
        'password_reset_form': password_reset_form
    }
    return render(request, 'main/home.html', context)

Then add this form to your main/home.html template:

<!-- Place this wherever you want the reset form to appear -->
<h3>Reset Your Password</h3>
<form method="post" action="{% url 'password_reset' %}">
    {% csrf_token %}
    {{ password_reset_form.as_p }}
    <button type="submit">Send Reset Link</button>
</form>

Why Copying Source Code Causes Errors

When you duplicate Django's view code, you often run into issues like:

  • Missing internal dependencies (like the translation function _ or private session tokens)
  • Outdated code that conflicts with your Django version
  • Incorrect decorator or inheritance setup that breaks CSRF protection or view flow

By inheriting the native view, you let Django handle all the core logic while you focus on customizations that fit your project.

内容的提问来源于stack exchange,提问作者Mohcen CH

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 13:47:38