So in my project I am using react for the frontend and django for the backend. I have the following model
class Role(models.Model):
ROLE_CHOICES = (
('Recruiter', 'Recruiter'),
('Manager', 'Manager'),
('Business Development Partner', 'Business Development Partner'),
('Business Development Partner Manager', 'Business Development Partner Manager'),
('Account Manager', 'Account Manager'),
)
role = models.CharField(max_length=50, choices=ROLE_CHOICES)
def __str__(self):
return self.name
I have created the following view to get the role choices I have defined to the frontend
@csrf_exempt
def role_choices(request):
roles = [role[1] for role in Role.ROLE_CHOICES]
return JsonResponse(roles, safe=False)
And this is the endpoint I created for it
path('roles/', role_choices, name='roles_list'),
Now in my frontend, I have a form, with one of the field being a role, which when clicked should show a dropdown list populated with the role choices (only pasting the required code here)
<h2>Role</h2>
<label>
Select Role:
<select
name="role"
value={userData.role}
onChange={handleInputChange}
>
<option value="">Select</option>
{roleOptions.map(role => (
<option key={role.id} value={role.role}>
{role.role}
</option>
))}
</select>
</label>
<br />
<button type="submit" class="btn btn-default btn-sm">Submit</button>
</form>
</div>
But I dont see the role options on the webpage
I have logged the response I get when calling the endpoint and I see the role options being fetched
The below code shows how I am setting the role options on the webpage
const [roleOptions, setRoleOptions] = useState([]);
useEffect(() => {
// Fetch role options from backend when component mounts
axios.get('http://127.0.0.1:8000/roles/')
.then(response => {
// Check if response data is an array
if (Array.isArray(response.data)) {
setRoleOptions(response.data);
console.log(response.data);
} else {
console.error('Invalid response data:', response.data);
}
})
.catch(error => {
console.error('Error fetching roles:', error);
});
}, []);
I dont why I am not able to see the role choices on the webpage, even after I get the correct response from the endpoint
Because there is no id
or role
, you just returned a list of strings. You should wrap these in dictionaries, like:
@csrf_exempt
def role_choices(request):
roles = [{'id': key, 'role': role} for key, role in Role.ROLE_CHOICES]
return JsonResponse(roles, safe=False)
It however has not really an "id" or at least it is not an id of a model.
Note: In 2008, Phil Haack discovered a way to obtain data from the outer JSON array. While most browser have implemented countermeasures, it is still better to use a JSON object as "envelope" of the data. That is why a
JsonResponse
[Django-doc] by default does not allow something else than adict
as outer object. It might thus better to wrap the data in a dictionary and keepsafe=True
onTrue
.