我已将我的UserProfile模型创建为instructed in the docs,但如何传递要从我的视图中保存的值。这就是我的观点:
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
now = timezone.now()
user = User.objects.create(
username = form.cleaned_data['username'],
first_name = form.cleaned_data['username'],
last_name = form.cleaned_data['username'],
email = form.cleaned_data['email'],
is_staff = False,
is_active = False,
is_superuser = False,
last_login = now,
date_joined = now
)
user.set_password(form.cleaned_data['password'])
user.save()
答案 0 :(得分:2)
因为您在User
模型上使用post_save()信号来创建UserProfile
对象,所以在调用user.save()后可以访问新创建的配置文件用户
profile = user.get_profile()
profile.verified = False
profile.ip_address = get_client_ip()
profile.save()
我认为您的UserProfile
中有models.py
模型。
## Create a forms.py file inside your app and define an UserProfileForm similar to this
from django.forms import ModelForm
## using relative import because it's good practice, and I don't know what's name of your app
from .models import UserProfile
class UserProfileForm(ModelForm)
class Meta:
model = UserProfile
exclude = ("user",)
## In views.py
if request.method == 'POST':
form = RegistrationForm(request.POST)
profile_form = UserProfileForm(request.POST)
if form.is_valid() and profile_form.is_valid():
now = timezone.now()
user = User.objects.create(
username = form.cleaned_data['username'],
first_name = form.cleaned_data['username'],
last_name = form.cleaned_data['username'],
email = form.cleaned_data['email'],
is_staff = False,
is_active = False,
is_superuser = False,
last_login = now,
date_joined = now
)
user.set_password(form.cleaned_data['password'])
user.save()
profile = profile_form.save(commit=False)
profile.user = user
profile.save()
但是,我不明白为什么即使在初始化和验证之后你还没有使用RegistrationForm
。
答案 1 :(得分:0)
如果请求是POST,则会收集所有表单数据,只需将其传递给字典即可将其传递回视图。
d=dict(username=form.cleaned_data["username"]), ... )
...
return render_to_resopnse("mytemplate.html", d, context_instance)