设置UserProfile值

时间:2013-01-20 19:49:55

标签: python django

我已将我的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()

2 个答案:

答案 0 :(得分:2)

更新1

因为您在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)