如何修复 Django 中 /signup/ 处的 UnboundLocalError

How to Fix UnboundLocalError at /signup/ in Django

我想创建一个像注册或注册这样的用户,当我点击提交按钮时我收到了这个错误:

UnboundLocalError 在 /signup/

我想注册用户:

local variable 'usercustom' referenced before assignment

这是我的Views.py

def signup(request):
    registered = False

    if request.method == "POST":
        user_form = UserForm(request.POST or None)
        custom_form = UserCustom(request.POST or None)

        if user_form.is_valid() and custom_form.is_valid():
            user = user_form.save(commit=False)
            user.save()

            custom = custom_form.save(commit=False)
            custom.user = user
            custom.save()

            registered = True
        else:
            print(user_form.errors,custom_form.errors)

    else:
        user_form = UserForm()
        usercustom = UserCustom()

    return render(request,'form.html',{'user_form':user_form,'usercustom':usercustom,'registered':registered})

这是我的Form.html

{% extends "base.html" %}
{% block body_block %}
      <div class="content-section">
        {% if registerd %}
          <h1>Thank Your For registering!</h1>
        {% else %}
          <h1>Register Here</h1>
          <h3>Fill out the form</h3>

          <form enctype="multipart/form-data" method="POST">
            {% csrf_token %}
            {{ user_form.as_p }}
            {{ usercustom.as_p }}
            <input type="submit" value="Register!" class="btn btn-danger">
          </form>
        {% endif %}
      </div>
{% endblock %}

这是因为您尝试发送 POST 请求时未声明 usercustom。您需要将 custom_form 变量重命名为 usercustom。我已经为您简化了代码。

def signup(request):
    registered = False
    if request.method == "POST":
        user_form = UserForm(request.POST or None)
        usercustom = UserCustom(request.POST or None)

        if user_form.is_valid() and usercustom.is_valid():
            user = user_form.save(commit=False)
            user.save()

            custom = usercustom.save(commit=False)
            custom.user = user
            custom.save()

            registered = True
        else:
            print(user_form.errors, usercustom.errors)

    else:
        user_form = UserForm()
        usercustom = UserCustom()

    return render(request,'form.html',{'user_form':user_form,'usercustom':usercustom,'registered':registered})