开发者

DoesNotExist error in django view/template with one-to-one field

开发者 https://www.devze.com 2023-04-11 01:46 出处:网络
I have these models. class Storypak(models.Model): headline = models.CharField(\'Headline\', max_length=200)

I have these models.

class Storypak(models.Model):
    headline = models.CharField('Headline', max_length=200)
    pub_date = models.DateField(blank=True)

class Story(models.Model):
    storypak = models.OneToOneField('Storypak', blank=True, null=True)
    copy = models.TextField(blank=True)

And this view.

def pak_detail(request, pak_id, year, month, day):
    pak = Storypak.objects.get(pk=pak_id)
    t = loader.get_template('storypak_detail.html')
    c = Context ({
        'pak' : pak,
        })
    return HttpResponse(t.render(c))

When I try to use an if statement in my template, a DoesNotExist error is thrown. The documentation I can find indicates that these开发者_开发问答 errors should be silenced. Shouldn't if pak.story resolve False and not throw an error? What am I missing? I think it may have something to do with the OneToOne relationship, but I can't find anything in the docs dealing with this specifically.

Here is the relevant template code as I remember it. I don't have the file on this computer. I'll fix it later if it isn't correct and possibly post the debug info if that would help.

{% if pak.story %}
    <p>{{ pak.story.copy }}</p>
{% endif %}


here is a related bug: https://code.djangoproject.com/ticket/10227

here is the source for the if tag: https://code.djangoproject.com/browser/django/trunk/django/template/defaulttags.py#L267

as you see, the tag's render method does not catch anything but VariableDoesNotExist.


You haven't given enough detail to troubleshoot much past the error here, but the simple error message can only be triggered by one statement in your view, that is...

pak = Storypak.objects.get(pk=pak_id)

The pak_id is either invalid, or your model is malformed and a Storypak with that id doesn't exist. That is the only call to an object that would raise a DoesNotExist error. You can verify it is a valid id by adding raise Exception(str(pak_id)) before this line to see what it is attempting to "get." Verify that record exists in the storypak table.

0

精彩评论

暂无评论...
验证码 换一张
取 消