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

巧了我就是萌 提交于 2021-02-10 05:10:47

问题


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:

  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


来源:https://stackoverflow.com/questions/45745226/django-extending-user-with-userprofile-error-user-has-no-profile

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!