'I am trying to send a post request with an authorization key as a parameter and keep receiving an error: "Program.user" must be a "User" instance
The error I keep receiving is: ValueError: Cannot assign "<django.contrib.auth.models.AnonymousUser object at 0x102704820>": "Program.user" must be a "User" instance.
I am using Redux and making the post request using an action called createProgram which looks like this
export const createProgram = () => async (dispatch, getState) => {
try{
dispatch({ type: PROGRAM_CREATE_REQUEST})
const {
userLogin: { userInfo },
} = getState()
const config = {
header: {
'Content-type': 'application/json',
Authorization: `Bearer ${userInfo.token}`
}
}
const { data } = await axios.post(
`/api/programs/program-create/`,
{},
config
)
dispatch({
type: PROGRAM_CREATE_SUCCESS,
payload: data,
})
} catch (error) {
dispatch({
type: PROGRAM_CREATE_FAIL,
payload: error.response && error.response.data.detail
? error.response.data.detail
: error.message
})
}
}
I am using Dango for the backend and the createProgram view and model look as such:
@api_view(['POST'])
def createProgram(request):
user = request.user
program = Program.objects.create(
user = user,
name = 'Empty Name'
)
serializer = ProgramSerializer(program, many=False)
return Response(serializer.data)
class Program(models.Model):
user = models.ForeignKey(User, on_delete=CASCADE, null=False)
name = models.CharField(max_length=200)
dateCreated = models.DateTimeField(auto_now_add=True)
# lastWorkout = models.DateTimeField(auto_now_add=False) #I have to fix this
def __str__(self):
return str(self.name) + ' - ' + str(self.user.first_name)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
