问题
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)
回答1:
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
})
# ^^^^^^
回答2:
You should add the following line to the script:
profile = Profile.objects.create(user=request.user)
回答3:
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.
回答4:
The best and easiest thing to do here while in the development is:
- in the terminal create another superuser -$ python manage.py createsuperuser
- login in the admin page with the new credentials
- Delete the old admin or any user that may have been created before the userprofile models were created
来源:https://stackoverflow.com/questions/45745226/django-extending-user-with-userprofile-error-user-has-no-profile