Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get ID from submitted form in Django

I’m using React and Django and have created a form for user input.
On submit I would like the ID of the post to be returned so the page can automatically load the next step using the ID in the URL.

Currently the post is added to the database just fine but I’m having trouble with what happens after.

views.py

class CreateArticle(generics.CreateAPIView):
    queryset = Article.objects.all()
    serializer_class = CreateArticleSerializer

    def article(self, request, format=None):
        serializer = self.serializer_class(data=request.data)
        if(serializer.is_valid()):
            title = serializer.data.get('title')

            p = Article(title=title)
            p.save()
            return Response(ArticleSerializer(p).data, status=status.HTTP_200_OK)
        return Response(status=status.HTTP_400_BAD_REQUEST)
serializer.py

class CreateArticleSerializer(serializers.ModelSerializer):
    class Meta:
        model = Article
        fields = ('title')
models.py

def generate_unique_id():
        return(uuid.uuid4())

class Article(models.Model):
    id = models.CharField(max_length=36, default=generate_unique_id(), primary_key=True)
    title = models.CharField(max_length=50)

    def __str__(self):
        return self.title
CreateArticle.jsx

try {
        API.post("/create/", { ...article }).then((response) => console.log(response))
} catch (err) {
        console.log(err)
    }

I understand views can only return HTTP requests but I am new to Django and lost here.
I’ve tried creating the ID in the view and returning that as a response but it does not appear within the usual Axios data.
Any direction would be appreciated.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thank you

>Solution :

You have to include id/pk in your serializer class

...
class CreateArticleSerializer(serializers.ModelSerializer):
    class Meta:
        model = Article
        fields = ('id', 'pk', 'title')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading