Johny
Johny

Reputation: 85

How to get the latest ID from different class in Django

I saw all the conversations about this issue, but I can't solve it. I am new in this Python-Django programming so if anyone can help me? :)

This is my views.py:

class HistoryProjectCreate(CreateView):
    template_name = 'layout/create_proj_history.html'
    model = ProjectHistory
    project = Project.objects.latest('id')
    user = User.id

    fields = ['user', 'project', 'user_start_date']
    success_url = reverse_lazy('git_project:index')

Var project has to return latest project ID from database, and I have to use it ID in my html form:

<form class="form-horizontal" action="" method="post" enctype="multipart/form-data">
    {% csrf_token %}
    <label for="user"></label>
    <input id="user" type="text" name="user" value="{{ user.id }}" ><br>
    <label for="project">Project title: </label>

    <input id="project" type="text" name="project" value="{{ project.id }}" ><br>

<!--Here - "project.id" I need latest project ID-->

    <label for="user_start_date">Start date: </label>
    <input id="user_start_date" type="date" name="user_start_date" value="{{ projectHistory.user_start_date }}" ><br>
    <div class="form-group">
        <div class="col-sm-offset-2 col-sm-10">
            <button type="submit" class="btn btn-success">Submit</button>
        </div>
    </div>
</form>

I am not sure if project = Project.objects.latest('id') is correct statement for getting the latest ID from Project table.

Upvotes: 0

Views: 515

Answers (1)

Wilfried
Wilfried

Reputation: 1633

If you want the last Id of project, you need to order by id, and use last() function available on queryset

project = Project.objects.order_by('id').last()

Order_by doc

Last function doc

Upvotes: 2

Related Questions