简体   繁体   English

ID不会显示在模板上

[英]ID won't show up on template

I'm trying to save a model object that has an auto-increment id and then get that ID and use it in a template. 我正在尝试保存一个具有自动递增ID的模型对象,然后获取该ID并在模板中使用它。 The id won't show up though. 该ID不会显示。

Here's the code that processes the submission: 这是处理提交的代码:

def process_submission(request):
    if request.method == 'POST':
            submission=request.POST
            temp = Listing(title=submission['title'],pub_date=datetime.datetime.now(),email=submission['email'],price=submission['price'],body=submission['body'],subject=submission['subject'],course_number=submission['course_number'])
            temp.save()
            return render(request, 'listing/success.html', {'temp', temp})

And then the relevant part of success.html 然后是success.html的相关部分

<p>Submission Successful!</p>
<p>You can find your listing at: <a href="blah/{{temp.id}}">URL/{{temp.id}}</a></p>

The ID won't show up. 该ID不会显示。 I'm not quite sure why this isn't working. 我不太确定为什么这行不通。 Any thoughts? 有什么想法吗?

Thanks. 谢谢。

Edit: 编辑:

Here is the model in question: 这是有问题的模型:

class Listing(models.Model):
    title = models.CharField(max_length=100)
    pub_date = models.DateTimeField('Date Published')
    email = models.CharField(max_length=200)
    price = models.CharField(max_length=20)
    body = models.CharField(max_length=1500)
    subject = models.CharField(max_length=4)
    course_number = models.CharField(max_length=4)

    def __str__(self):
            return self.title

Actually, code you mentioned above should work. 实际上,您上面提到的代码应该可以工作。 Check this document: https://docs.djangoproject.com/en/dev/ref/models/instances/?from=olddocs#auto-incrementing-primary-keys , and please make sure that you;re using AutoField as id. 检查此文档: https ://docs.djangoproject.com/en/dev/ref/models/instances/?from=olddocs#auto-incrementing-primary-keys,请确保您使用的是AutoField作为ID。

Have you set primary_key=True on one of the other fields in your model? 您是否在模型的其他字段之一上设置了primary_key=True If so Django will not automatically provide an id field. 如果是这样,Django将不会自动提供id字段。 Or perhaps you declared your own field named id ? 还是您声明了自己的名为id的字段? If you do have another valid primary key in your model, you could use that in your template rather than Django's autoincremented id. 如果您的模型中确实有另一个有效的主键,则可以在模板中使用它,而不是Django的自动递增ID。

Try printing out the value of id after saving the record in your view. 将记录保存在视图中后,尝试打印出id的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM