Django视图未将上下文数据发送到ReactJS / Axios应用程序

时间:2020-06-25 01:30:21

标签: django reactjs axios

看来我遇到了非常奇怪的行为。我正在构建一个ReactJS + Django 3.0应用程序。这是问题所在...

我有一个<form onSubmit={handleSubmit}>,将表单包装在前端。

const handleSubmit = (e) => {
    e.preventDefault();
    axios.post(paths.login, qs.stringify({
                email: emailVal,
                password: passwordVal
            }));
}

这可以很好地将数据发送到Django视图!但是,当我尝试通过Django视图传递上下文变量时,它完全失败了。意思

def login(request):
    data = {}
    '''
    Handle Logging in
    '''
    if request.method == 'POST':
        login_form = forms.LoginForm(request.POST)
        if login_form.is_valid():
            user = login_form.authenticate_user()
            #login(request, user)
            return redirect('home')
        else:
            data['errorMessage'] = ''
            for field, errors in login_form.errors.items():
                for error in errors:
                    data['errorMessage'] += error
    print(data)
    return render(request, 'index.html', context=data)

鉴于此,数据字典首先将为空,但是即使print(data)显示已填充数据字典,发送到index.html文件的上下文数据仍然为空。

为什么会这样?我一直坚持下去。

如果我仅使用表单提交而不是像这样的axios,我可以解决此问题:<form method='POST'>但是,我需要使用axios。 SOS

1 个答案:

答案 0 :(得分:0)

您也可以为此使用Django消息框架,这可能是一个更好的选择(假设您在POST之后重新渲染页面):

from django.contrib import messages
def login(request):
    data = {}
    '''
    Handle Logging in
    '''
    if request.method == 'POST':
        login_form = forms.LoginForm(request.POST)
        if login_form.is_valid():
            user = login_form.authenticate_user()
            #login(request, user)
            return redirect('home')
        else:
            error_message = ''
            for field, errors in login_form.errors.items():
                for error in errors:
                    error_message += error
             messages.add_message(request, messages.ERROR, error_message)
    
    return render(request, 'index.html')

然后在您的模板中(这是使用Bootstrap的示例,但是您可以根据需要进行修改):

    {% if messages %}
        {% for message in messages %}
            {% if message.tags == 'error' %}
                <div class="alert alert-danger alert-with-icon alert-dismissible fade show" role="alert">
            {% else %}
                <div class="alert alert-{{ message.tags }} alert-with-icon alert-dismissible fade show" role="alert">
            {% endif %}
                {{ message|safe }}
                <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
        {% endfor %}
{% endif %}

如果您将数据作为AJAX JSON响应发送回去,则:

from django.http import JsonResponse
def login(request):
    data = {}
    '''
    Handle Logging in
    '''
    if request.method == 'POST':
        login_form = forms.LoginForm(request.POST)
        if login_form.is_valid():
            user = login_form.authenticate_user()
            #login(request, user)
            return redirect('home')
        else:
            error_message = ''
            for field, errors in login_form.errors.items():
                for error in errors:
                    error_message += error
            data['error_message'] = error_message
            return JsonResponse(data)
      else:
         return render(request, 'index.html')

在您的Axios代码中:

const handleSubmit = (e) => {
    e.preventDefault();
    axios.post(paths.login, qs.stringify({
                email: emailVal,
                password: passwordVal
            }).then((response) => {
             //do something with JSON response
           }, (error) => {
             //do something with JSON response
           });
     });