Home > Blockchain >  Get ID from submitted form in Django
Get ID from submitted form in Django

Time:10-23

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.

Thank you

CodePudding user response:

You have to include id/pk in your serializer class

...
class CreateArticleSerializer(serializers.ModelSerializer):
    class Meta:
        model = Article
        fields = ('id', 'pk', 'title')
  • Related