Django我无法从数据库中提取数据,网页中不存在错误

y0u0uwnf  于 2022-12-14  发布在  Go
关注(0)|答案(1)|浏览(131)

管理员可以更改网站标题,关键字或描述。但它不工作rn。当我进入网站我有一个错误:DoesNotExist at /设置匹配的查询不存在。
这是我的家/models.py

from django.db import models
class Setting(models.Model):
    title = models.CharField(max_length=150)
    keywords = models.CharField(max_length=255)
    description = models.CharField(max_length=255)
    company = models.CharField(max_length=50)
    address = models.CharField(blank=True, max_length=150)
    phone = models.CharField(blank=True, max_length=15)
    fax = models.CharField(blank=True, max_length=15)
    email = models.CharField(blank=True, max_length=50)
    smptpserver = models.CharField(blank=True, max_length=30)
    smptemail = models.CharField(blank=True, max_length=30)
    smptpassword = models.CharField(blank=True, max_length=150)
    smptport = models.CharField(blank=True, max_length=15)
    icon = models.ImageField(blank=True, upload_to='images/')
    facebook = models.CharField(blank=True, max_length=50)
    instagram = models.CharField(blank=True, max_length=50)
    twitter = models.CharField(blank=True, max_length=50)
    aboutus = models.CharField(max_length=50)
    contact = models.CharField(max_length=50)
    contact_map = models.CharField(max_length=50)
    references = models.CharField(max_length=50)
    status = models.CharField(max_length=10, choices=STATUS)
    create_at = models.DateTimeField(auto_now_add=True)
    uptade_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.title

这是我的家/views.py

from django.http import HttpResponse
from django.shortcuts import render
from home.models import Setting
def index(request):
    setting=Setting.objects.get(pk=1)
    context={'setting':setting}
    return render(request,'index.html',context)

这是我的主页/

{% block title %} {{ setting.title }} {% endblock %}
{% block keywords %} {{ setting.keywords }} {% endblock %}
{% block description %} {{ setting.description }} {% endblock %}
tjrkku2a

tjrkku2a1#

因为get()函数如果行不存在会引发异常。(官方解释)

1.选择;

您可以通过这种方式使用get_or_404;

from django.shortcuts import get_object_or_404

Setting.objects.get_object_or_404(pk=1)

2.任择办法;

您可以通过这种方式使用get_or_create;

Setting.objects.get_or_create(pk=1)

相关问题