我正在尝试让一个用户注册表单提交到两个模型(user和UserProfile)中,并立即创建UseProfile属于用户的关系。我认为问题在于通过考试请求.user.id到UserProfile模型,以便它知道它属于谁。你知道吗
你知道吗型号.py你知道吗
from django.db import models
from django.contrib.auth.models import User
class UserProfile(models.Model):
age = models.CharField(max_length=100)
interests = models.TextField(default="")
user = models.ForeignKey(User)
你知道吗视图.py你知道吗
from django.shortcuts import render
from django.contrib.auth.models import User
from .models import UserProfile
from django.contrib.auth import authenticate, login
def user_creation_view(request):
if request.method == "POST":
username = request.POST.get('username', None)
password = request.POST.get('password', None)
user = User.objects.create_user(username=username, password=password)
user.save()
user = authenticate(username=username, password=password)
login(request, user)
interests = request.POST.get('interests', None)
age = request.POST.get('age', None)
pk = request.user.id
user_profile = UserProfile.objects.create(age=age, interests=interests, user=pk)
return render(request, "profiles/user_creation_template.html")
用户创建_模板.html你知道吗
<!DOCTYPE html>
<html>
<head></head>
<body>
<form method="post" action="{% url "user_creation" %}">
{% csrf_token %}
<input type="text" name="username" placeholder="Username">
<input type="password" name="password" placeholder="Password">
<input type="text" placeholder="Interests" name="interests">
<input type="text" placeholder="age" name="age">
<input type="submit">
</form>
</body>
</html>
谢谢!你知道吗
我先把你的关系改成
OneToOneField
。你知道吗接下来,我将生成一个
post_save
信号来生成新的概要文件。你知道吗在创建用户时,创建UserProfile的推荐方法是使用post_save信号(here是说明它们是什么的docs页面)。你知道吗
基本上,当用户模型被创建(第一次保存)时,我们会创建一个链接到用户的UserProfile对象。像这样:
注意:如果您使用ForeignKey而不是OneToOneField,那么您最终会遇到这样的情况:一个用户有多个userprofile(因此您不能执行
user.user_profile
)。你知道吗当您执行
user.save()
时,信号将被触发,因此从那时起您可以执行以下操作(假设您将字段更改为OneToOneField):去完成你想做的事。你知道吗
相关问题 更多 >
编程相关推荐