user18587924
user18587924

Reputation:

Django I can't pull data from database. DoesNotExist error in web

Admin can change the web title,keywords or description. But it's not working rn. When i entry website i have a error: DoesNotExist at / Setting matching query does not exist.

This is my home/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 

This is my home/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)

This is my home/temp/index.html

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

Upvotes: 0

Views: 48

Answers (1)

Sezer BOZKIR
Sezer BOZKIR

Reputation: 562

Because get() function will raise an exception if the row does not exist. (official explanation)

1. option;
You can use get_or_404 with this way;

from django.shortcuts import get_object_or_404

Setting.objects.get_object_or_404(pk=1)

2. option;
You can use get_or_create with this way;

Setting.objects.get_or_create(pk=1)

Upvotes: 1

Related Questions