2022-07-15
4721
#django#python#react
Diogo Souza
11057
Jul 15, 2022 ⋅ 16 min read

Using React with Django to create an app: Tutorial

Diogo Souza Brazilian dev. Creator of altaluna.com.br

Recent posts:

Developing Web Extensions With Wxt

Developing web extensions with the WXT library

Browser extensions are an important part of the web ecosystem. They make our lives easier and enhance our web browsing […]

Debjyoti Banerjee
May 24, 2024 ⋅ 8 min read
Bulma Css Adoption Guide: Overview, Examples, And Alternatives

Bulma CSS adoption guide: Overview, examples, and alternatives

Explore how Bulma CSS simplifies frontend development with its ease of use and customizable, responsive, pre-designed UI elements.

Timonwa Akintokun
May 23, 2024 ⋅ 10 min read
Using Mountaineer To Develop A React App With Python

Using Mountaineer to develop a React app with Python

Develop a React app with Python using the Mountaineer framework for building a simple app with integrated your frontend and backend database.

Rosario De Chiara
May 23, 2024 ⋅ 7 min read
Enhance CSS View Transitions With Velevette

Enhance CSS view transitions with Velvette

Velvette is a utility library developed to make working with view transitions easier.

David Omotayo
May 22, 2024 ⋅ 9 min read
View all posts

28 Replies to "Using React with Django to create an app: Tutorial"

  1. Hello,
    I was trying the app and stop in 2 errors:
    Error: 1
    ========
    ….
    re.error: unknown extension ?P[ at position 15
    ….
    “^api/students/(?P[0-9]+)$” is not a valid regular expression: unknown extension ?P[ at position 15

    Error: 2
    ========
    whilie visiting http://localhost:8000/api/students/
    “…Exception Value: name ‘StudentSerializer’ is not defined…”

    How to solve these?
    Thanks.

  2. OK I managed to get it working by

    1. NOTE you cannot add students to settings.py before running the migrate command as it says it cant find module students – it works by first running migrate then amending settings.py
    2. on the regex – deleting ?P works (for now)
    3. instead of the code above for serializers.py, rather put this code in instead:

    from rest_framework import serializers
    from students.models import Student

    class StudentSerializer(serializers.ModelSerializer):

    class Meta:
    model = Student
    fields = [‘name’, ’email’, ‘document’, ‘phone’, ‘registrationDate’]

  3. 1. Perhaps use P to represent pk kwarg in the view
    url(r’^api/students/(?P[0-9]+)$’, views.students_detail)
    2. need to add bootstrap css into /src/index.js by adding the below line
    import ‘bootstrap/dist/css/bootstrap.min.css’;
    3. define Student model id as pk field in StudentSerializer or call id in Serializer and update react to use student.id instaed of student.pk

  4. Hi Diogo,

    The ‘python manage.py startapp students’ command which you have mentioned in the article is incorrect the correct command is as follows:

    (logrocket_env) osi@osi-ThinkPad-T420:~/Project/django_react_proj$ django-admin startapp students

  5. Hey guys, Im sorry for the delay. I’m going to answer everyone here, instead of individually, ok?

    So, let’s break it down:

    1. The ?P comes from the need for a regular expression that allows only numbers to the “pk” param. That’s it. You can read more here: https://docs.djangoproject.com/en/3.0/topics/http/urls/#using-regular-expressions

    In the docs, the recommended usage is with the re_path() function. So, I’ve updated the code alike:

    from django.urls import path, re_path

    urlpatterns = [
    path(‘admin/’, admin.site.urls),
    re_path(r’^api/students/$’, views.students_list),
    re_path(r’^api/students/(?P[0-9]+)$’, views.students_detail),
    ]

    Please, let me know if it works fine with you.

    2. Regarding the following code:

    students.models import Student

    It’s not necessary if you have the files into the same folder. Please check that.

    3. Great catch with the Bootstrap import, many thanks. 🙂

    I’ll update the article.

    4. It’s not necessary to create an id field, but feel free to if you want a different name.

    5. Kashyap, manage.py is automatically created in each Django project. It does the same thing as django-admin but also sets the DJANGO_SETTINGS_MODULE environment variable so that it points to your project’s settings.py file.

    Refer to https://docs.djangoproject.com/en/3.0/ref/django-admin/ for more.

    6. Finally, I’ve update the README.md on the GitHub project, so then you and everyone can check how to run the final project locally. I hope this helps. 🙂

    Please, let me know if you have any other questions.

  6. Hi Paul,

    On your first point, it also works if instead of running the command

    `python manage.py startapp students`

    you run

    `django-admin startapp students`

    This completely fixed my issue with that point of the tutorial

    Thanks for the rest!

  7. It’s ok, I saw the correction above by @Paul

    instead of the code above for serializers.py, rather put this code in instead:

    from rest_framework import serializers
    from students.models import Student

    class StudentSerializer(serializers.ModelSerializer):

    class Meta:
    model = Student
    fields = [‘name’, ’email’, ‘document’, ‘phone’, ‘registrationDate’]

  8. hello thank for the tutorial, whoever am not able to remove student using the modal when ever i clicked on the remove button it does not work and return :
    createError.js:16 Uncaught (in promise) Error: Request failed with status code 404

    same as the edit button pls help

  9. Hey Udeh, have you tried to download the source code and compare your files one by one?

    Your error is too generic, it could be a lot of things. Please, do it and let me know.

  10. It’s ok, I saw the correction above by @Paul

    instead of the code above for serializers.py, rather put this code in instead:

    from rest_framework import serializers
    from students.models import Student
    from django.db import models

    class StudentSerializer(serializers.ModelSerializer):

    class Meta:
    model = Student
    fields = ‘__all__’

  11. The only problem I see is that I was expecting to see an article about integrating both, not using them apart, because well… this is using a development server for React and another server for Django which isn’t practical at all to implement these technologies in a production project. Anyway I’ll keep searching how to do it because there must be an efficient way. Thanks anyway.

  12. Diogo, thank you for this article. However, you still haven’t fixed the incorrect code for the Serializers.py, as several people in the comments have suggested. I think a lot of people will be confused by that and it’s quite simple to fix.

  13. Thanks for the artcle. I cloned the code and it workd fine and understand most ot the artcle but I can’t figure out how this Fragment:

    {button}

    {title}

    Is able to display the edit/create fields from the imported NewStudentForm class a generic mechanism. IOW does this mechanism of rendering parts of referenced imported classes only work in modal forms or perhaps only in Fragments? Any reference to a tutorial or sample that explains this is more detail would be greatly appreciated.

  14. Hello, Thanks for the wonderful tutorial. I have successfully created the student form but when click on the send button, it keeps giving an error that “this.props.resetState” is not a function. It send the data to the api created though. How do I fix this?

  15. using django 3.0.8
    if the regex for the path to CRUD operation like DELETE and PUT are not working for you i changed mine into

    urlpatterns = [
    path(‘admin/’, admin.site.urls),
    re_path(r’^api/students/$’, views.students_list),
    re_path(r’^api/students/([0-9])$’, views.students_detail)
    ]

    and they are working how they are suppose to :

    this is my function definition inside views.py
    @api_view([‘PUT’, ‘DELETE’])
    def students_detail(request, pk):

    hope this can help anyone out there.

  16. The url path is wrong.
    django.core.exceptions.ImproperlyConfigured: “^api/students/(?P[0-9]+)$” is not a valid regular expression: unknown extension ?P[ at position 15
    C:\Users\3738254\code\react\example\backend\backend\urls.py changed, reloading.
    Watching for file changes with StatReloader

    You should have something like this:
    re_path(r’^api/students/(?P\w+)/$’, views.students_detail),

    or pass the pk

  17. Access to XMLHttpRequest at ‘http://localhost:8000/api/students’ from origin ‘http://localhost:3000’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: Redirect is not allowed for a preflight request.

  18. on react interface data is not removing and also when edit the data send does not work.

    when press “yes” on toggle and edit on send data its not working?

    createError.js:16 Uncaught (in promise) Error: Request failed with status code 404
    at createError (createError.js:16)
    at settle (settle.js:17)
    at XMLHttpRequest.handleLoad (xhr.js:62)

  19. I really appreciate the tutorial. It cleared up a lot of things – especially on the React end. That said…

    > “One way to simplify this is to use Django’s own capabilities to serve static files. After all, the front end application is nothing more than a set of files of this type.”

    – But the steps we follow here really don’t serve static files (HTML, JavaScript, CSS) that Django serves up. Instead we create a full blown React app for the front end and run on a node web server. The Django back end does nothing except serving the API and handing the HTTP requests from the React app. I followed a different approach where I bundle everything on the React end with webpack and serve it on a second app on Django.

    > “In this article, we’ll outline how to create a simple CRUD API with Django and its famous Django REST Framework free from CORS common issues, and integrate it with a React app.”

    – In the beginning I was running a simple react module that just listed the items that it got from the API with a GET request on a page and did nothing else. I also didn’t face any CORS issues. However, after I incorporated this tutorial and added the new functions in the views.py file, I started get the “Cross-Origin Request Blocked” error on Firefox. After I incorporated the “django-cors-headers” to backend and added the `CORS_ALLOWED_ORIGINS = ( ‘http://127.0.0.1:8000’, )` settings.py file the issue went away.

    Other than these two secondary issues, this tutorial really worked for me. Thank you!

  20. It seems it would be better to serve react from Django, and .gitignore.

    This example is unnecessarily bloated.

Leave a Reply