根据变量创建模型和模板名称

时间:2018-04-15 22:05:19

标签: django django-views

我首先要说的是,我知道这可能既是非传统的也是不好的做法,但这里也是如此。

我有一个UserProfile模型。在此模型的表单中,用户可以选择要在其博客上使用的模板。在这样做时,他们将从下拉菜单中选择1,2或3。此号码将保存到字段'模板'在UserProfile模型中。

点击提交按钮后,我希望发生以下情况:

1)我希望创建一个TemplateProfilex,其中x等于他们选择的模板编号。

为了让您知道我想要发生什么(即使我知道这不会起作用),这是代码。

x = user.userprofile.template

Model = TemplateProfile + 'x'

blog = Model.objects.create(user=request.user)

如果用户在表单上选择了3,那么这里的目标是为该用户创建TemplateProfile3。

2)接下来,一旦创建模型并将用户重定向到下一个视图,我想将此用户发送到模板,该模板由user.userprofile.template中的值确定

return render(request, 'accounts/templateX.html', args) where X is the value in user.userprofile.template

如果我可以按上述方法执行某些操作,则可以大大简化我的代码。另一种方法是在我的视图中做一堆if语句。例如:

if user.userprofile.template == 1: 

   template_profile= TemplateProfile1.objects.create(user=request.user)

   return render(request, 'accounts/template1.html', args)

非常感谢你们。

0 个答案:

没有答案