TadasK
TadasK

Reputation: 55

Django Getting PK from Createview

I am creating a blog post with a specific primary key (pk). My other function requires to have the pk as an input (please check the views.py). I am trying to get the post id by getting it as an object id, although it indicated that object has no attribute 'id'.

Any ideas how to get pk as a variable?

Thanks, Ted

#The template
{% extends "Blog/base.html" %}
{% load crispy_forms_tags %}
{% block content%}
    <div class="content-section">
        <form method = "POST">
            {% csrf_token %}
            <fieldset class="form-group">
                <legend class="border-bottom mb-4"> Blog Post </legend>
                {{ form|crispy }}
            </fieldset>
            <div class="form-group">
                <button class="btn btn-outline-info" type="submit">Post</button>
            </div>
        </form>
    </div>

{% endblock content%}
#urls.py
from django.urls import path
from .views import PostListView, PostDetailView, PostCreateView, PostUpdateView, PostDeleteView
from . import views

urlpatterns = [

    path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'),
    path('post/new', PostCreateView.as_view(), name='post-create'),
]

#views.py

from django.shortcuts import render
from django.views.generic import (
    ListView,
    DetailView,
    CreateView,
    UpdateView,
    DeleteView
)
from .models import Post
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from .latex import tex
from django.http import FileResponse, Http404
from django.urls import reverse

class PostCreateView(LoginRequiredMixin, CreateView):
    model = Post
    fields = ['first_name', 'last_name', 'titles' ,'title', 'content', 'billing']

    def form_valid(self, form):
        form.instance.author = self.request.user # Use this to get the information from the form.

        pk = self.object.id

        self.external(pk)

        return super().form_valid(form), 

#Error which I am getting
'NoneType' object has no attribute 'id'

Upvotes: 1

Views: 1617

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476813

You can obtain the object through the instance wrapped in the form. But as long as the object is not saved, it has no primary key.

class PostCreateView(LoginRequiredMixin, CreateView):
    model = Post
    fields = ['first_name', 'last_name', 'titles' ,'title', 'content', 'billing']

    def form_valid(self, form):
        form.instance.author = self.request.user
        response = super().form_valid(form)
        pk = form.instance.pk
        self.external(pk)
        return response

Upvotes: 1

Related Questions