简体   繁体   中英

Django extending user with userprofile (error: User has no profile.)

在此处输入图片说明 someone can told me, why this code don't working? I'm trying to create a registration form for users.

I'm getting an error

"RelatedObjectDoesNotExist at /signup/client/2/ User has no profile."

views.py

if request.POST:
            user_form = UserCreationForm(request.POST)
            profile_form = ProfileForm(request.POST)
            if user_form.is_valid() and profile_form.is_valid():
                user = user_form.save()
                user.profile.city="WW"
                user.profile.phone="32323"
                user.profile.save()

forms.py

class UserForm(forms.ModelForm):
    class Meta:
        model = User
        fields = ('first_name', 'last_name', 'email')

class ProfileForm(forms.ModelForm):
    class Meta:
        model = Profile
        fields = ( 'city', 'phone')

html file

  <h2>Sign up</h2>
  <form method="post">
    {% csrf_token %}
    {{ user_form.as_p }}
    {{ profile_form.as_p }}
    <button type="submit">Sign up</button>

models.py

from __future__ import unicode_literals
from django.contrib.auth.models import User
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    city = models.TextField(max_length = 50)
    phone = models.TextField(max_length = 12)

You need to create a profile , it does not get created when you save user_form

        user_form = UserCreationForm(request.POST)
        profile_form = ProfileForm(request.POST)
        if user_form.is_valid() and profile_form.is_valid():
            user = user_form.save()
            Profile.objects.create(**{
                 'city':"WW", 'phone': '32323', 'user': user
            })
            # ^^^^^^

您应该将以下行添加到脚本中:

profile = Profile.objects.create(user=request.user)

I believe this code is referred from 'Django by Examples'. If so, Go to your application admin Site and add a profile manually under profile account and run the server again. This will solve the issue.

The best and easiest thing to do here while in the development is:

  1. in the terminal create another superuser -$ python manage.py createsuperuser
  2. login in the admin page with the new credentials
  3. Delete the old admin or any user that may have been created before the userprofile models were created

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM