基于邮箱搜索并停用用户账号的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:
- You're using
self.requestfor messages, but FBVs don't have aselfcontext—this throws an error and skips your update logic. - The
profilevariable is only defined inside thetryblock, so it'll be undefined if the request isn't POST or the try fails (causing template errors). - You're not validating the email input with your
SearchForm, so invalid emails might slip through. - After updating the user status, you don't refresh the
profiledata 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 = Noneto avoid undefined variable errors - Used
SearchFormto validate email input - Replaced
self.requestwithrequestfor messages - Switched to
profile.save()instead of bulkupdate()(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:
- You're using
form_valid, which is a method fromFormView(not the baseViewclass)—it never gets called in your current setup. - 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
相关产品推荐
相关产品推荐

