/register/User处的RelatedObjectDoesNotExist没有扩展用户模型和配置文件的配置文件



当用户注册时,注册完成,但没有创建配置文件,并引发错误。在数据库中创建了用户,但没有配置文件。错误突出显示在"p_reg_form=ProfileRegisterForm(request.POST,instance=credentials.profile("以下是该项目的.py文件。此代码以前可以工作,但现在突然停止了。models.py:

class User(AbstractBaseUser, PermissionsMixin):
"""
An abstract base class implementing a fully featured User model with
admin-compliant permissions.
Username and password are required. Other fields are optional.
"""
username_validator = UnicodeUsernameValidator()
username = models.CharField(
"username",
max_length=150,
unique=True,
help_text="Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.",
validators=[username_validator],
error_messages={"unique": "A user with that username already exists.", },
)
first_name = models.CharField("first name", max_length=30, blank=True)
last_name = models.CharField("last name", max_length=150, blank=True)
email = models.EmailField("email", blank=True, unique=True)
is_staff = models.BooleanField(
"staff status",
default=False,
help_text=["Designates whether the user can log into this admin site."],
)
is_active = models.BooleanField(
"active",
default=True,
help_text=(
"Designates whether this user should be treated as active. "
"Unselect this instead of deleting accounts."
),
)
date_joined = models.DateTimeField("date joined", default=timezone.now)
objects = UserManager()
EMAIL_FIELD = "email"
USERNAME_FIELD = "email"
REQUIRED_FIELDS = ()
class Meta:
verbose_name = "user"
verbose_name_plural = "users"
def clean(self):
"""Try and find the new way to right this save"""
super(User, self).save()
self.email = self.__class__.objects.normalize_email(self.email)
def get_full_name(self):
"""
Return the first_name plus the last_name, with a space in between.
"""
full_name = "%s %s" % (self.first_name, self.last_name)
return full_name.strip()
def get_short_name(self):
"""Return the short name for the user."""
return self.first_name
def email_user(self, subject, message, from_email=None, **kwargs):
"""Send an email to this user."""
send_mail(subject, message, from_email, [self.email], **kwargs)

class Profile(models.Model):
"""Profile class lists the library and choices and settings for each field in the model the Profile
and also sets the database structure"""
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
image = models.ImageField(default="default.jpg", upload_to="profile_pics")
date_birth = models.DateField(max_length=75, null=True, name="date_birth")
def __str__(self):
return str(self.user)
def get_absolute_url(self):
"""Definition for the absolute path to be rendered in the profile-detail view"""
# return f'{self.user.username} Profile'
return reverse("profile-detail", kwargs={"pk": self.pk})

class Profile1(models.Model):
"""This class lists the library classes and settings in the model"""
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
image = models.ImageField(default="default.jpg", upload_to="profile_pics")
def __str__(self):
return str(self.user)
def get_absolute_url(self):
"""Definition for the absolute path to be rendered in the profile-detail view"""
# return f'{self.user.username} Profile'
return reverse("profile-detail", kwargs={"pk": self.pk})

views.py:

def register(request):
"""This function provides the logic and condition for saving the classes, the form variables used
plus the message and the redirection or rendering url """
if request.method == "POST":
form = UserRegistrationForm(request.POST)
p_reg_form = ProfileRegisterForm(request.POST)
if form.is_valid() and p_reg_form.is_valid():
credentials = form.save()
credentials.user = request.user
p_reg_form = ProfileRegisterForm(request.POST, instance=credentials.profile)
p_reg_form.full_clean()
p_reg_form.save()
credentials.is_active = False
credentials.save()
current_site = get_current_site(request)
email_subject = "Activate Your Account"
message = render_to_string(
"users/activate_account.html",
{
"user": credentials,
"domain": current_site.domain,
"uid": urlsafe_base64_encode(force_bytes(credentials.pk)),
"token": account_activation_token.make_token(credentials),
},
)
to_email = form.cleaned_data.get("email")
email = EmailMessage(email_subject, message, to=[to_email])
email.send()
messages.success(
request,
f"Account successfully created for: {first_name} {last_name} , "
f"Please verify your email: {to_email} for access to your account",
)
# return HttpResponse('We have sent you an email,
# please confirm your email address to complete registration')
return TemplateResponse(
request, "users/register_email_sent_confirmation.html"
)
else:
form = UserRegistrationForm()
p_reg_form = ProfileRegisterForm()
context = {"form": form, "p_reg_form": p_reg_form}
return render(request, "users/register.html", context)

forms.py:

BIRTH_YEAR_CHOICES = [x for x in range(1909, 2021)]

class UserRegistrationForm(UserCreationForm):
"""This class lists the model and fields for the User model Registration Form"""
email = forms.EmailField()
first_name = forms.CharField()
last_name = forms.CharField()
class Meta:
"""The model called and the field/s to be filled by the form for rendering"""
model = User
fields = [
"first_name",
"last_name",
"email",
"username",
"password1",
"password2",
]
widgets = {"country": CountrySelectWidget()}
def clean_email(self):
"""This definition checks to see if any users already exist with this email."""
# Get the email
email = self.cleaned_data.get("email")
# Check to see if any users already exist with this email.
try:
match = User.objects.get(email=email)
except User.DoesNotExist:
# Unable to find a user, this is fine
return email
# A user was found with this as a username, raise an error.
raise forms.ValidationError(f"This email ({email}) address is already in use.")

class ProfileRegisterForm(forms.ModelForm):
"""This class lists the model and fields for the User model Profile Registration Form"""
date_birth = forms.DateField(
label="Date of birth",
initial=datetime.date.today,
widget=forms.SelectDateWidget(years=BIRTH_YEAR_CHOICES),
)
class Meta:
"""The model called and the field/s to be filled by the form for rendering"""
model = Profile
fields = ["date_birth",]

信号.py:

@receiver(post_save, sender=User)
def create_profile(instance, created):
"""This function lists the model to be created and saved for the classes relating to
other apps withing the project"""
if created:
Profile.objects.create(user=instance)
Profile1.objects.create(user=instance)

@receiver(post_save, sender=User)
def save_profile(instance):
"""This function lists the model to be created and saved for the classes relating to
other apps withing the project"""
instance.profile.save()
instance.profile1.save()

settings.py:

AUTH_USER_MODEL = "users.User"

错误:

RelatedObjectDoesNotExist at /register/
User has no profile.
Request Method: POST
Request URL:    http://localhost:5000/register/
Django Version: 3.0.7
Exception Type: RelatedObjectDoesNotExist
Exception Value:    
User has no profile.

该代码以前有效,但最近才开始失败,我们将不胜感激。

问题来自

p_reg_form = ProfileRegisterForm(request.POST, instance=credentials.profile)

在此阶段,您的凭据没有配置文件,因此出现错误。

尝试替换:

p_reg_form = ProfileRegisterForm(request.POST, instance=credentials.profile)
p_reg_form.full_clean()
p_reg_form.save()

比如:你可能需要调整一下

profile = p_reg_form.save()
profile.user = request.user
p_reg_form.full_clean()
p_reg_form.save()

当未为查询的给定参数找到对象时,将引发DoesNotExist异常。Django提供了一个DoesNotExist异常作为每个模型类的属性,以标识找不到的对象的类,并允许您使用try/except捕获特定的模型类。

最新更新