Как подключить react frontend к django backend
У меня проблемы с тем, чтобы заставить мой react frontend и django backend работать вместе
У меня есть форма регистрации клиента, и вот она
Вот мои файлы django, размещаю содержимое, относящееся только к этой форме
models.py
class ClientRegistration(models.Model):
entityName = models.CharField(max_length=255)
organizationStatus = models.CharField(max_length=255)
estYear = models.CharField(max_length=4) # Assuming year is a string field
proprieterName = models.CharField(max_length=255)
officeAddress = models.TextField()
branchAddress = models.TextField()
companyPerson = models.CharField(max_length=255)
companyDesignation = models.CharField(max_length=255)
companyNumber = models.IntegerField(validators=[MinValueValidator(0000000000), MaxValueValidator(9999999999)]) # Assuming company number is a string field
companyFax = models.IntegerField(validators=[MinValueValidator(0000000000), MaxValueValidator(9999999999)]) # Assuming fax is a string field
companyEmail = models.EmailField(validators=[EmailValidator()])
industryNature = models.CharField(max_length=255)
companyCIN = models.CharField(max_length=255)
companyPAN = models.CharField(max_length=10) # Assuming PAN is a string field
companyGST = models.CharField(max_length=15) # Assuming GST is a string field
bdpName = models.ForeignKey(UserData, on_delete=models.CASCADE, limit_choices_to={'role__role': 'Business Development Partner'}, related_name='bdp_clientregistrations')
bdpmName = models.ForeignKey(UserData, on_delete=models.CASCADE, limit_choices_to={'role__role': 'Business Development Partner Manager'}, related_name='bdpm_clientregistrations')
accountManager = models.CharField(max_length=255)
billingCity = models.CharField(max_length=255)
billingCountry = models.CharField(max_length=255)
def __str__(self):
return self.entityName # Change this based on what you want to display for each instance
app/urls.py
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from .views import *
router = DefaultRouter()
router.register(r'userdata', UserDataViewSet)
router.register(r'education', EducationViewSet)
router.register(r'workexperience', WorkExperienceViewSet)
router.register(r'clientregistration', ClientRegistrationViewSet)
router.register(r'jobdescription', JobDescriptionViewSet)
router.register(r'assessment', AssessmentViewSet)
router.register(r'appointment', AppointmentViewSet)
urlpatterns = [
path('', include(router.urls)),
path('api/recruiters/', get_recruiters, name='get_recruiters'),
path('api/clients/', get_clients, name='get_clients'),
path('submit-assessment/', submit_assessment, name='submit_assessment'),
path('api/amanager/', get_accoutmanagers, name='get_accountmanagers'),
path('api/job-descriptions/', get_job_descriptions, name='get_job_descriptions'),
path('api/job-descriptions/<int:job_id>/assessments/', get_assessments_for_job, name='get_assessments_for_job'),
path('clientregistration/', ClientRegistrationViewSet.as_view({'post': 'create'}), name='clientregistration'),
]
project/urls.py
from django.contrib import admin
from django.urls import path, include
from backend_app.views import *
from django.views.generic import TemplateView
from backend_app.views import *
urlpatterns = [
# Other URL patterns (if any)
path('admin/', admin.site.urls),
# API endpoints for your app
path('', include('backend_app.urls')), # Include app-specific API endpoints
]
# Add a catch-all URL pattern to serve your React.js application
Views.py
class ClientRegistrationViewSet(viewsets.ModelViewSet):
queryset = ClientRegistration.objects.all()
serializer_class = ClientRegistrationSerializer
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
if serializer.is_valid():
# Check if the client registration is pending
if 'pending_registration_id' in serializer.validated_data:
pending_registration_id = serializer.validated_data.pop('pending_registration_id')
try:
pending_registration = PendingClientRegistration.objects.get(id=pending_registration_id)
except PendingClientRegistration.DoesNotExist:
return Response({'error': 'Pending registration not found.'}, status=status.HTTP_400_BAD_REQUEST)
# Create a new ClientRegistration object with details from PendingClientRegistration
client_registration_data = {
'entityName': pending_registration.client_registration.entityName,
'organizationStatus': pending_registration.client_registration.organizationStatus,
'estYear': pending_registration.client_registration.estYear,
# Add other fields as needed
}
client_registration_serializer = ClientRegistrationSerializer(data=client_registration_data)
if client_registration_serializer.is_valid():
client_registration_serializer.save()
# Update the pending registration to mark it as approved
pending_registration.approved = True
pending_registration.save()
return Response(client_registration_serializer.data, status=status.HTTP_201_CREATED)
else:
return Response(client_registration_serializer.errors, status=status.HTTP_400_BAD_REQUEST)
else:
# Save the client registration if it's not pending
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Я не уверен, что я упускаю, но при отправке формы на моем сервере react, ничего не отправляется на бэкенд django. Я попробовал проверить, используя метод get на сервере django
Любая помощь будет оценена по достоинству
На данный момент я рекомендую проверить консоль в вашем браузере и добавить все происходящее сюда, чтобы читатели могли вам помочь. (Вы уверены, что ваш api корректен и работает?)