我无法通过我的django视图获取post值

3bygqnnd  于 2023-06-25  发布在  Go
关注(0)|答案(1)|浏览(117)

我是django的新手,我做了一个自定义的视图来登录,但是不管我的帖子请求,这个函数从来没有得到用户名和密码。以下是我的观点:

@csrf_exempt
def custom_login(request):
    if request.method == 'POST':
        username = request.POST.get("usuario")
        password = request.POST.get("clave")

        user = authenticate(request, username=username, password=password)
        if user is not None:
            login(request, user)
            return JsonResponse({'success': True})
        else:
            return JsonResponse({'success': False, 'message': 'Invalid credentials', 'username': username, 'password': password})

这里也是我的网址模式在www.example.com urls.py

urlpatterns = [
    # asocia la raiz del proyecto con el index.html
    path("", views.index, name="index"),
    # asocia las rutas creadas previamente por el enroutador Router
    path('', include(router.urls)),
    # incluye rutas de autenticacion de usuario de Django
    path('api-auth/', include('rest_framework.urls', namespace='rest_framework')),
    path('admin/', admin.site.urls),
    path('custom-login/', custom_login, name='custom_login'),

]

下面是我如何从react发出请求,handlesubmit是提交表单时触发的函数

export default function LoginView() {

  const csfrtoken = getCSRFToken();

  const handleSubmit = async (event) => {

    event.preventDefault();
    const data = new FormData(event.currentTarget);
    console.log({
      username: data.get('id'),
      password: data.get('clave'),
    });

    try {
      const response = await axios.post('http://localhost:8000/custom-login/', {
        usuario: data.get('id'),
        clave: data.get('clave'),
      });
      if (response.data.success) {
        console.log('Login successful:', response.data);
      } else {
        // Login failed, display error message or handle accordingly
        console.log('Login failed:', response.data.message);
      }
      // Perform any necessary actions after successful login
    } catch (error) {
      console.error('Login failed:', error.response.data);
      // Handle login failure
    }

  };

  return (
    <Grid container component="main" sx={{ height: '100vh' }}>
      <CssBaseline />
      <Grid
        item
        xs={false}
        sm={4}
        md={7}
        sx={{
          backgroundImage: 'url(https://source.unsplash.com/random?wallpapers)',
          backgroundRepeat: 'no-repeat',
          backgroundColor: (t) =>
            t.palette.mode === 'light' ? t.palette.grey[50] : t.palette.grey[900],
          backgroundSize: 'cover',
          backgroundPosition: 'center',
        }}
      />
      <Grid item xs={12} sm={8} md={5} component={Paper} elevation={6} square>
        <Box
          sx={{
            my: 8,
            mx: 4,
            display: 'flex',
            flexDirection: 'column',
            alignItems: 'center',
          }}
        >
          <Avatar sx={{ m: 1, bgcolor: 'secondary.main' }}>
            <LockOutlinedIcon />
          </Avatar>
          <Typography component="h1" variant="h5">
            La investigación en la UNAL
          </Typography>
          <Box component="form" noValidate onSubmit={handleSubmit} sx={{ mt: 1 }}>
            <TextField
              margin="normal"
              required
              fullWidth
              id="id"
              label="Número de identificación"
              name="id"
              type="number"
              autoFocus
            />
            <TextField
              margin="normal"
              required
              fullWidth
              name="clave"
              label="Contraseña"
              type="password"
              id="clave"
              autoComplete="current-password"
            />
            <TextField
              value={csfrtoken}
              name="csrfmiddlewaretoken"
            />
            {/* <FormControlLabel
              control={<Checkbox value="remember" color="primary" />}
              label="Remember me"
            /> */}
            <Button
              type="submit"
              fullWidth
              variant="contained"
              sx={{ mt: 3, mb: 2 }}
            >
              Iniciar sesión
            </Button>
            <Grid container>
              {/* <Grid item xs>
                <Link href="#" variant="body2">
                  Forgot password?
                </Link>
              </Grid> */}
              {/* <Grid item>
                <Link href="#" variant="body2">
                  {"Don't have an account? Sign Up"}
                </Link>
              </Grid> */}
            </Grid>
            <Copyright sx={{ mt: 5 }} />
          </Box>
        </Box>
      </Grid>
    </Grid>
  );
}

我已经尝试使用 Postman 提出的要求,我希望一个成功的登录,但总是不成功。当我在python中调试用户名和密码值时,我总是得到None。如果我手动将其更改为真实的用户字符串,它将成功登录

mftmpeh8

mftmpeh81#

我解决了在axios post请求中添加application/json头的问题,如下所示:

headers: {
   'Content-Type': 'application/json',
}

所以我得这样修改我的视图:

@csrf_exempt
def custom_login(request):
    if request.method == 'POST':
        data = json.loads(request.body)
        username = data.get("usuario")
        password = data.get("clave")
        print(username)
        print(password)

        user = authenticate(request, username=username, password=password)
        if user is not None:
            login(request, user)
            return JsonResponse({'success': True})
        else:
            return JsonResponse({'success': False, 'message': 'Invalid credentials', 'username': username, 'password': password})

相关问题