【问题标题】:Load values from Models.py into Views.py将 Models.py 中的值加载到 Views.py
【发布时间】:2021-12-31 02:55:57
【问题描述】:

我正在尝试创建一个页面,该页面允许用户更改 Django 管理页面中的某些 CSS 变量,我在从 models.py 中提取单个值并将其分配给我的 views.py 中的变量时遇到了一些问题.在 Django 管理页面中分配颜色是可行的,但我不确定如何将 views.py 中的 linkcolor 变量设置为 models.py 中的 link_color 变量。

views.py

from django.shortcuts import render
from django.http import HttpResponse
from .models import cssEditor

# Create your views here.

def index(request):
    linkcolor = "#000" # Grab link_color from models.py here
    linkfont = "Brush Script MT" # Grab link_font from models.py here
    linkbc = "whitesmoke" # Grab link_bc from models.py here
    return render(request, "SocialLinks/index.html", {"linkcolor":linkcolor, "linkfont":linkfont, "linkbc":linkbc})
models.py

from django.db import models

# Create your models here.

class cssEditor(models.Model):
    link_color = models.CharField(max_length=7, default="000000")
    link_font = models.CharField(max_length=15, default="Brush Script MT")
    link_bc = models.CharField(max_length=7, default="#F5F5F5")
admin.py

from django.contrib import admin
from SocialLinks.forms import *

# Register your models here.

@admin.register(cssEditor)
class cssEditor(admin.ModelAdmin):
    form = cssForm
forms.py

from django.forms import ModelForm
from django.forms.widgets import TextInput
from SocialLinks.models import *

class cssForm(ModelForm):
    class Meta:
        model = cssEditor
        fields = "__all__"
        widgets = {
            "link_color": TextInput(attrs={"type": "color"}),
            "link_bc": TextInput(attrs={"type": "color"}),
        }

【问题讨论】:

    标签: python html css django


    【解决方案1】:

    您只需要在视图中查询模型并获取值。

    from django.shortcuts import render
    from django.http import HttpResponse
    from .models import cssEditor
    
    # Create your views here.
    
    def index(request):
        editor = cssEditor.objects.get(X) # <- X is the instance pk
        return render(
            request,
            "SocialLinks/index.html",
            {
                "linkcolor":editor.linkcolor,
                "linkfont":editor.linkfont,
                "linkbc":editor.linkbc
             }
        )
    

    现在,您没有提及如何将实例绑定到某个对象,例如用户,或者它是否是单个实例。您有几种查询模型的方法。在示例中,我使用了我神奇地得到它的 pk ;) 。这是你需要弄清楚的事情。

    【讨论】:

    • 谢谢!所以基本上我只需要一种方法将模型作为对象拉入然后引用每个部分? -编辑。我明白了,只需要添加 editor = cssEditor.objects.get(pk=1) 并没有意识到 pk=1 是默认值。感谢您的帮助!
    • 很高兴你解决了!
    猜你喜欢
    • 1970-01-01
    • 2019-11-22
    • 2018-01-29
    • 2021-08-29
    • 1970-01-01
    • 1970-01-01
    • 2022-11-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多