Django用户提交表单后切换展示页面,报错'NoneType'无registration_date属性
修复步骤
1. 错误根源说明
你之前遇到的'NoneType' object has no attribute 'registration_date'报错,是因为未提交过表单的用户没有对应的UserProfile记录,UserProfile.objects.filter(user=request.user).first()会返回None,直接访问属性就会抛出异常。
用新增的profile_submitted布尔字段判断提交状态远比用registration_date合理,字段语义明确,后续调整提交判定逻辑也更灵活。
2. 修改视图函数(views.py)
你需要同时补充表单提交的POST处理逻辑,提交成功后把profile_submitted设为True,同时要先判断用户是否已经有UserProfile记录,避免访问None的属性:
from django.shortcuts import redirect from .forms import 你的表单类名 # 替换成你实际的UserProfile表单类名 def view_profile(request): # 先获取用户的profile,不存在则返回None user_profile = UserProfile.objects.filter(user=request.user).first() # 判定提交状态:有profile且profile_submitted为True才算已提交 profile_is_submitted = user_profile and user_profile.profile_submitted if request.method == "POST": # 如果已经提交过就直接返回,防止重复提交 if profile_is_submitted: return redirect("view_profile") # 替换成你这个视图的对应路由名 # 有旧profile就用旧的实例更新,没有就新建 form = 你的表单类名(request.POST, instance=user_profile) if form.is_valid(): profile = form.save(commit=False) profile.user = request.user profile.profile_submitted = True # 提交成功后标记为已提交 profile.save() return redirect("view_profile") else: form = 你的表单类名(instance=user_profile) context = { 'profile_is_submitted': profile_is_submitted, 'form': form } return render(request, 'page.html', context)
3. 优化模板(page.html)
你原来的模板存在标签拼写错误、闭合不全的问题,修正后即可正常使用:
{% extends 'base.html' %} {% block content %} <div class="container"> <h1> Title </h1> {% if profile_is_submitted %} <p>你已成功提交表单</p> {% else %} <h1> Title </h1> <div class="container"> <div class="form-group"> <!-- 修正原拼写错误cass为class --> <form method="POST"> {% csrf_token %} {{ form.as_p }} <button class="btn btn-primary" type="submit">提交</button> </form> <!-- 补充原遗漏的form闭合标签 --> </div> </div> {% endif %} <!-- 补充原遗漏的endif闭合标签 --> </div> {% endblock %}
内容的提问来源于stack exchange,提问作者Diana Mele
相关产品推荐
相关产品推荐

