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

基于邮箱搜索并停用用户账号的Django视图问题排查

Hey there! Let's break down the issues with both your Function-Based View (FBV) and Class-Based View (CBV) and fix them one by one.


Fixing the Function-Based View (FBV)

Looking at your FBV code, there are a few key issues preventing it from working correctly:

  1. You're using self.request for messages, but FBVs don't have a self context—this throws an error and skips your update logic.
  2. The profile variable is only defined inside the try block, so it'll be undefined if the request isn't POST or the try fails (causing template errors).
  3. You're not validating the email input with your SearchForm, so invalid emails might slip through.
  4. After updating the user status, you don't refresh the profile data to show the updated state in the template.

Here's the fixed FBV:

@login_required
def admin_deactivate_profile_view(request):
    error_text = ''
    profile = None
    form = SearchForm(request.POST or None)  # Use form for validation

    if request.method == 'POST':
        if form.is_valid():
            user_email = form.cleaned_data.get('email')
            try:
                profile = User.objects.filter(email=user_email).first()
                if profile and request.POST.get('delete'):
                    profile.active = False
                    profile.save()  # Use save() instead of update() to trigger signals (if any)
                    messages.success(request, 'Profile successfully deactivated!')
                    # Refresh profile to show updated status
                    profile = User.objects.filter(email=user_email).first()
                else:
                    messages.warning(request, 'User not found or delete action not triggered.')
            except Exception as e:
                print(e)
                messages.error(request, f'There was an error: {str(e)}')
        else:
            messages.error(request, 'Please enter a valid email address.')

    return render(request, "admin/delete_profile.html", {'profile': profile, 'form': form})

Key fixes:

  • Initialized profile = None to avoid undefined variable errors
  • Used SearchForm to validate email input
  • Replaced self.request with request for messages
  • Switched to profile.save() instead of bulk update() (better practice for single objects)
  • Added clear feedback for missing users, invalid forms, and errors

Fixing the Class-Based View (CBV)

Your CBV has two main problems:

  1. You're using form_valid, which is a method from FormView (not the base View class)—it never gets called in your current setup.
  2. You're not fetching or passing the user profile data to the template, so nothing shows up.

We can fix this by either using FormView (the recommended approach for form handling) or manually handling POST requests in the base View.

Option 1: Use FormView (Cleaner, Django-idiomatic)

from django.views.generic.edit import FormView
from django.contrib.messages.views import SuccessMessageMixin

@method_decorator(login_required, name='dispatch')
class AdminDeleteProfileView(SuccessMessageMixin, LoginRequiredMixin, FormView):
    form_class = SearchForm
    template_name = 'admin/view_account.html'
    success_message = 'Profile successfully deactivated!'

    def form_valid(self, form):
        user_email = form.cleaned_data.get('email')
        user = User.objects.filter(email=user_email).first()
        if user:
            user.active = False
            user.save()
            # Pass user data to template context
            self.extra_context = {'profile': user}
        else:
            messages.warning(self.request, 'User not found!')
        return super().form_valid(form)

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        # Ensure profile exists in context even for GET requests
        context.setdefault('profile', None)
        return context

Option 2: Manual POST Handling with Base View

If you prefer sticking to the base View:

@method_decorator(login_required, name='dispatch')
class AdminDeleteProfileView(LoginRequiredMixin, View):
    def get(self, request):
        form = SearchForm()
        return render(request, 'admin/view_account.html', {'form': form, 'profile': None})

    def post(self, request):
        form = SearchForm(request.POST)
        profile = None
        if form.is_valid():
            user_email = form.cleaned_data.get('email')
            profile = User.objects.filter(email=user_email).first()
            if profile and request.POST.get('delete'):
                profile.active = False
                profile.save()
                messages.success(request, 'Profile successfully deactivated!')
            else:
                messages.warning(request, 'User not found or delete action not triggered.')
        else:
            messages.error(request, 'Please enter a valid email address.')
        return render(request, 'admin/view_account.html', {'form': form, 'profile': profile})

Key fixes for CBV:

  • Properly handled GET/POST request flows
  • Fetched and passed user profile data to the template
  • Added validation and error feedback
  • Used Django's built-in CBV tools (like FormView) to reduce boilerplate

Template Quick Tip

Make sure your template checks if profile exists before rendering user data, and includes the delete button with the correct name:

<form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit" name="delete" value="1">Deactivate User</button>
</form>

{% if profile %}
    <h3>User Profile</h3>
    <p>Email: {{ profile.email }}</p>
    <p>Name: {{ profile.name }}</p>
    <p>Status: {% if profile.active %}Active{% else %}Deactivated{% endif %}</p>
{% endif %}

{% if messages %}
    {% for message in messages %}
        <div class="alert {% if message.tags %}alert-{{ message.tags }}{% endif %}">
            {{ message }}
        </div>
    {% endfor %}
{% endif %}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 08:15:27