【问题标题】:Referring to forms and models in views.py with variables用变量引用views.py中的表单和模型
【发布时间】:2018-07-06 23:27:20
【问题描述】:

当用户在我的网站上注册时,他们会选择一个他们希望在用户个人资料中看到的模板。在这种情况下,因为他们想查看“绿色”配置文件,所以 user.userprofile.color 等于 1。

我已经为绿色模板构建了一个特定的模型(称为 model1),并为该模型构建了一个特定的表单(称为 form1)。当用户在 UserProfile 表单中选择“绿色”并提交表单时,会自动为用户分配一个 model1 的实例

在 views.py 中,我想创建一个通用视图,它采用 user.userprofile.color 值并使用它来建立

a) 以什么形式提供网页

b) 表单基于什么模型

而不是像这样硬编码表单和模型值:

def 主页模板(请求):

if request.method == 'POST':
    form = form1(request.POST, request.FILES, 
    instance=request.user.model1)

    if form.is_valid():
        form.save()
        return redirect('/accounts/')        


else:
    form = form1(instance=request.user.model1)
    args = {'form': form}
    return render(request, 'homepage.html', args)

在函数中而不是指定'form1'和'model1',我希望表单和模型值等于'form'+i和'model'+i,其中i等于user.userprofile.color的值(即 1)。

对此的任何帮助将不胜感激!

【问题讨论】:

  • 在模板 {% if user.userProfile.1 %} 使用模板 {% elif user.userProfile.2 %} 使用模板 {% endi f%}

标签: django django-models django-forms django-views


【解决方案1】:

我想你正在寻找Django's contenttypes framework

基本上,您可以创建一个包含以下内容的模型:

from django.db import models
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType

class Templates(models.Model):
    template_name = models.SlugField()  # e.g. "green"
    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)  # this will point to a template model
    object_id = models.PositiveIntegerField()  # this one will point to a specific row in your DB - resulting with an model instance
    content_object = GenericForeignKey('content_type', 'object_id')

您的用户模型可以通过template = models.ForeignKey(Templates) 引用此模型,以便您可以这样做:

template = User.objects.get(pk=1).template.content_object

现在对于表单部分...这将更加棘手。也许Templates 模型可以存储一个导入路径,然后使用import_modeule How to access a python module variable using a string [ django ] 加载该特定表单?

感觉可能有更适合您的用户需求的解决方案。即使模型最终会成为一个属性包并具有动态形式 Jacob Kaplan-Moss one of Django's core contributors explain how to achieve the latter 用于前者,我也无法快速找到任何东西(对于这个问题来说太难了)。

【讨论】:

    猜你喜欢
    • 2012-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-21
    相关资源
    最近更新 更多