简体   繁体   中英

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. The id won't show up though.

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

<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. 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.

Have you set primary_key=True on one of the other fields in your model? If so Django will not automatically provide an id field. Or perhaps you declared your own field named 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.

Try printing out the value of id after saving the record in your view.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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