我想了解在Class Base View中我将为以下内容执行逻辑:
基本上,我想检查用户是否有帐户,如果是这样,将它们转发到URL A,否则为URL B.但是,我不能100%确定get_success_url()是否是最适合这种情况的地方。一个CBV或者如果Django有一些已经满足这个用例的东西。我见过其他CBV喜欢RedirectView我试过这个但是失去了范围。请记住,我需要传递用户ID。
这是我到目前为止所处的地方:
class CampaignView(BaseUpdateView):
form_class = UserLookUpFrom
model = Campaign
def get_context_data(self, **kwargs):
context = super(CampaignView, self).get_context_data(**kwargs)
# context['form'] = AppUserLookUpFrom
return context
def form_valid(self, form):
"""
If the form is valid, in this case DON'T save it!
"""
return super(CampaignView, self).form_valid(form)
def get_success_url(self):
"""
Returns the supplied URL.
"""
if self.success_url:
url = self.success_url % self.object.__dict__
else:
try:
currect_user = Campaign.object.get_user_by_email(EMAIL HERE DONT KNOW HOW TO GET THIS YET FROM FORM)
if currect_user:
url = reverse('campaigns_login', args=(self.object.id,'self.userid'))
else:
url = reverse('campaigns_register', args=(self.object.id)
except AttributeError:
raise ImproperlyConfigured(
"No URL to redirect to. Either provide a url or define"
" a get_absolute_url method on the Model.")
return url
答案 0 :(得分:1)
您可以在form_valid
本身执行此操作。这是一个未经测试的代码,应该有助于解释这个概念:
from django.shortcuts import redirect
def form_valid(self, form):
email = form.cleaned_data.get("email", "")
prev_user = Campaign.object.filter(email=email)
if prev_user:
return redirect('campaigns_login', self.object.id, prev_user[0].userid)
else:
return redirect('campaigns_register', self.object.id)
答案 1 :(得分:1)
我认为它应该在CampaignView的帖子上:
def post(self, request, *args, **kwargs):
form= self.form_class(request.POST)
if form.is_valid():
user_email= form.cleaned_data['email']
user_of_campaign= Campaign.objects.filter(email= user_email)
if len(user_of_campaign)>0:
return redirect('/login', user_of_campaign[0].id)
else:
return redirect('/register')
return super(CampaignView, self).form_valid(form)
return super(CampaignView, self).form_invalid(form)