我无法让我的 React 前端和 django 后端一起工作
我有一份客户注册表,在这里
import React, { useState } from 'react';
import axios from 'axios';
import '../css/Clientregistration.css';
function ClientRegistration() {
const [userData, setUserData] = useState({
entityName: '',
organizationStatus: '',
estYear: '',
proprieterName : '',
officeAddress : '',
branchAddress : '',
companyPerson : '',
companyDesignation : '',
compnayNumber : '',
companyFax : '',
companyEmail : '',
industryNature : '',
companyCIN : '',
companyPAN : '',
companyGST : '',
bdpName : '',
bdpmName : '',
accountManager : '',
billingCity : '',
billingCountry : '',
});
const handleInputChange = (event) => {
const { name, value } = event.target;
setUserData({ ...userData, [name]: value });
};
const statusOptions = [
'Proprietorship',
'Private Limited',
'Public Limited',
];
const industryOptions = [
'Communcations',
'Consulting',
'Education',
'Financial services',
'Healthcare',
'IT Services',
'Manufacturing',
'Pharma',
'Real estate',
'Technology',
'Data Center',
'Semiconductor',
'Insurance',
];
const handleSubmit = async (event) => {
event.preventDefault();
try {
const response = await axios.post(`'http://localhost:8000/clientregistration/'`, userData);
console.log('Form submitted successfully:', response.data);
// You can add any additional logic here after the form is successfully submitted
} catch (error) {
console.error('Error submitting form:', error);
// Handle any errors here
}
// Reset the form after submission
setUserData({
entityName: '',
organizationStatus: '',
estYear: '',
proprieterName: '',
officeAddress: '',
branchAddress: '',
companyPerson: '',
companyDesignation: '',
companyNumber: '',
companyFax: '',
companyEmail: '',
industryNature: '',
companyCIN: '',
companyPAN: '',
companyGST: '',
bdpName: '',
bdpmName: '',
accountManager: '',
billingCity: '',
billingCountry: '',
});
};
return (
<div>
<h1>Client Registration Form</h1>
<form onSubmit={handleSubmit}>
<label>
Name of the Entity:
<input
type="text"
name="entityName"
value={userData.entityName}
onChange={handleInputChange}
/>
</label>
<br />
<label>
Status of Organization (Proprietorship/Pvt./Public Ltd.):
<select
name="organizationStatus"
value={userData.organizationStatus}
onChange={handleInputChange}
>
<option value="">Select</option>
{statusOptions.map((organizationStatus) => (
<option key={organizationStatus} value={organizationStatus}>
{organizationStatus}
</option>
))}
<option value="other">Other</option>
</select>
</label>
{userData.organizationStatus === 'other' && (
<input
type="text"
name="organizationStatus"
value={userData.organizationStatus}
onChange={handleInputChange}
/>
)}
<br />
<label>
Year of Establishment:
<input
type="tel"
name="estYear"
value={userData.estYear}
onChange={handleInputChange}
/>
</label>
<br />
<label>
Name of Proprietor/Director/MD:
<input
type="text"
name="proprieterName"
value={userData.proprieterName}
onChange={handleInputChange}
/>
</label>
<br />
<label>
Registered Office Address:
<input
type="text"
name="officeAddres"
value={userData.officeAddress}
onChange={handleInputChange}
/>
</label>
<br />
<label>
Address of Branch Office:
<input
type="text"
name="branchAddress"
value={userData.branchAddress}
onChange={handleInputChange}
/>
</label>
<br />
<label>
Contact Person:
<input
type="text"
name="companyPerson"
value={userData.companyPerson}
onChange={handleInputChange}
/>
</label>
<br />
<label>
Designation:
<input
type="text"
name="companyDesignation"
value={userData.companyDesignation}
onChange={handleInputChange}
/>
</label>
<br />
<label>
Phone Number:
<input
type="number"
name="compnayNumber"
value={userData.compnayNumber}
onChange={handleInputChange}
/>
</label>
<br />
<label>
Fax Number:
<input
type="number"
name="companyFax"
value={userData.companyFax}
onChange={handleInputChange}
/>
</label>
<br />
<label>
Email ID:
<input
type="email"
name="companyEmail"
value={userData.companyEmail}
onChange={handleInputChange}
/>
</label>
<br />
<label>
Nature of Industry
<select
name="industryNature"
value={userData.industryNature}
onChange={handleInputChange}
>
<option value="">Select</option>
{industryOptions.map((industryNature) => (
<option key={industryNature} value={industryNature}>
{industryNature}
</option>
))}
<option value="other">Other</option>
</select>
</label>
{userData.industryNature === 'other' && (
<input
type="text"
name="industryNature"
value={userData.industryNature}
onChange={handleInputChange}
/>
)}
<br />
<label>
Certification of Incorporation Number:
<input
type="text"
name="companyCIN"
value={userData.companyCIN}
onChange={handleInputChange}
/>
</label>
<br />
<label>
Pan Number:
<input
type="text"
name="companyPAN"
value={userData.companyPAN}
onChange={handleInputChange}
/>
</label>
<br />
<label>
GST Number:
<input
type="text"
name="companyGST"
value={userData.companyGST}
onChange={handleInputChange}
/>
</label>
<br />
<label>
Business Development Partner Name
<input
type="text"
name="bdpName"
value={userData.bdpName}
onChange={handleInputChange}
/>
</label>
<br />
<label>
Business Development Manager Name:
<input
type="text"
name="bdpmName"
value={userData.bdpmName}
onChange={handleInputChange}
/>
</label>
<br />
<label>
Account Manager:
<input
type="text"
name="accountManager"
value={userData.accountManager}
onChange={handleInputChange}
/>
</label>
<br />
<label>
Billing City:
<input
type="text"
name="billingCity"
value={userData.billingCity}
onChange={handleInputChange}
/>
</label>
<br />
<label>
Billing Country:
<input
type="text"
name="billingCountry"
value={userData.billingCountry}
onChange={handleInputChange}
/>
</label>
<br />
<button type="submit" class="btn btn-default btn-sm">Submit</button>
</form>
</div>
);
}
export default ClientRegistration;
这是我的django文件,仅发布与此表单相关的内容
模型.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
应用程序/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'),
]
项目/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
视图.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 后端。我尝试使用 django 服务器上的 get 方法进行检查
如有任何帮助,我们将不胜感激
目前我建议您在浏览器中检查控制台并添加此处发生的任何内容,以便读者可以帮助您。(您确定您的 api 正确且正常工作吗?)