Django 在 .exists 查询后将 id 传递给 URL



>我创建了一个视图集,它在其中检查用户是否已创建对象,如果未创建对象,它会将他重定向到表单以填充它,如果存在,它将重定向到下一步。

我目前面临的挑战是如何将 id 传递给下一个视图并基于它设置外键。

models.py:
class Startup ( models.Model ) :
author = models.OneToOneField ( User , on_delete = models.CASCADE )
startup_name = models.CharField ( 'Startup Name' , max_length = 32 , null = False , blank = False )
class Startup_About ( models.Model ) :
str_about = models.ForeignKey ( Startup , on_delete = models.CASCADE )
about = models.TextField ( 'About Startup' , max_length = 2000 , null = False , blank = False )
problem = models.TextField ( 'Problem/Opportunity' , max_length = 2000 , null = False , blank = False )
business_model = models.TextField ( 'Business Monitization Model' , max_length = 2000 , null = False ,blank = False )
offer = models.TextField ( 'Offer to Investors' , max_length = 2000 , null = False , blank = False )
def __str__(self) :
return str(self.str_about)

views.py

@login_required
@str_required
def create_startupform(request):
q = Startup.objects.filter(author=request.user)
if q.exists():
return redirect ( 'appwizard')
else:
form = startupform ( request.POST or None )
if form.is_valid ( ) :
instance = form.save (commit = False)
instance.author = request.user
instance.save()
return redirect ( 'appwizard', stup = instance.pk )
else:
form = startupform()
return render ( request , 'str_name.html' , { 'form' : form } )
@method_decorator(login_required, name='dispatch')
@method_decorator(str_required, name='dispatch')
class create_startupaboutform(CreateView):
model= Startup_About
template_name = 'create_about.html'
form_class = startupaboutform
success_url = '/str_detailedview/'
def form_valid(self, form):
if form.is_valid():
form.save(commit=False)
form.str_about = #i need to get the ID from the URL in both cases if the User had created the object or is going to create it#
return super(create_startupaboutform,self).form_valid(form)

urls.py

path ( 'appwizard/' , views.applicationwizard , name = 'appwizard' ) ,
path('create_startupaboutform/', views.create_startupaboutform.as_view(), name='create_startupaboutform'),

有很多方法。我在这里只列出两种方法。

  1. 创建保存 id 的会话变量。
  2. 修改 URL 以包含 id,some-url/<int:pk>/pk将是 ID。

最新更新