/ accounts / regist_save /' User'中的AttributeError对象没有属性'用户'

时间:2017-12-10 00:34:21

标签: javascript python html django

/ accounts / regist_save /' User'中的AttributeError对象没有属性'用户'错误发生。我在views.py中写道 我在views.py中写道

def regist(request):
    regist_form = RegisterForm(request.POST or None)
    profile_form = ProfileForm(request.POST or None)
    context = {
        'regist_form': regist_form,
        'profile_form': profile_form, 
    }
    return render(request, 'registration/regist.html', context)

@require_POST
def regist_save(request):

    regist_form = RegisterForm(request.POST or None)
    profile_form = ProfileForm(request.POST or None)

    if request.method == "POST" and regist_form.is_valid() and profile_form.is_valid():
                regist = regist_form.save(commit=False)
                regist.is_staff = True
                regist.save()

                profile = profile_form.save(commit=False)
                profile.user = regist.user

    return render(request, 'registration/detail.html')

在regist.html中

<div class="form-group-lg">

    <label for="id_username">Username</label>

    {{ regist_form.username }}

  </div>

  <div class="form-group-lg">

    <label for="id_email">Email</label>

    {{ regist_form.email }}
  </div>

  <div class="form-group-lg">

    <label for="id_password">Password</label>

    {{ regist_form.password1 }}

  </div>


  <div class="form-group-lg">
    <label for="id_password">Password2</label>

    {{ regist_form.password2 }}
    <p class="help-block">{{ regist_form.password2.help_text }}</p>

  </div>



  {% load static %}

  <div class="form-group-lg">
    <label for="sex">SEX</label>
    <select id="sex" class="form-control sex" name="sex">
      <option value="">--</option>
      <option value="male">male</option>
      <option value="female">female</option>
    </select>
  </div>


  <script src="{% static 'accounts/register.js' %}"></script>


      <button type="submit" class="btn-lg regist">REGIST</button>

      <input name="next" type="hidden" />

  {% csrf_token %}

</form>

在models.py

from django.db import models
from django.contrib.auth.models import User

    class NewUser(models.Model):
        user = models.OneToOneField(User, on_delete=models.CASCADE)
        birthday = models.CharField(max_length=100,null=True, blank=True, default=None)
        sex = models.CharField(max_length=100,null=True, blank=True, default=None)

我真的无法理解为什么会出现这种错误,因为我认为profile.user = regist.user可以得到用户。我试着写profile.user = request.user但发生了IntegrityError。我怎样才能得到用户?为什么可以&#39;通过使用此代码获取它?我写错了用户模型的列名吗?我该怎么做才能解决这个问题?

1 个答案:

答案 0 :(得分:0)

我认为regist本身就是用户对象。

试试:

profile.user = regist