Django中显示CreateView前检查用户是否已有对应对象防止重复创建
问题原因
你在CreateView中重写的get_object方法不会被默认调用,因为CreateView的原生逻辑是处理新对象创建,不会主动查询当前用户的已有Applicant实例,导致模板中的applicant变量不存在,if applicant判断永远为假,所以表单一直展示。
解决方案
方案1:保留现有模板逻辑,给模板传入实例
重写get_context_data方法,把当前用户的Applicant实例传入模板上下文即可让现有模板判断生效:
class ApplicantProfileCreateView(LoginRequiredMixin, generic.CreateView): model = Applicant fields = [...] template_name = 'profile_create_form.html' success_url = '/' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) # 传入当前用户的Applicant实例,不存在则为None context['applicant'] = Applicant.objects.filter(user=self.request.user).first() return context
方案2(更推荐):提前校验跳转,优化用户体验
直接在请求进入视图时就做校验,如果用户已经有Applicant实例,直接跳转到资料详情页,不需要用户手动点击跳转链接:
from django.shortcuts import redirect class ApplicantProfileCreateView(LoginRequiredMixin, generic.CreateView): model = Applicant fields = [...] template_name = 'profile_create_form.html' success_url = '/' def dispatch(self, request, *args, **kwargs): # 校验是否已有资料,存在则直接跳转到详情页 if Applicant.objects.filter(user=request.user).exists(): return redirect('/profile/') return super().dispatch(request, *args, **kwargs)
额外优化建议
你已经用了OneToOneField关联User模型,数据库层面默认就会强制唯一性,就算视图层校验遗漏,也不会出现同一个用户创建多条Applicant记录的脏数据问题,双重保障更稳妥。
内容的提问来源于stack exchange,提问作者nickj_french
相关产品推荐
相关产品推荐

