0

我已经按照文档中的说明创建了我的 UserProfile 模型,但是如何传递要从我的视图中保存的值。这就是我的观点:

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()
4

2 回答 2

2

更新 1

由于您在模型上使用 post_save() 信号User来创建UserProfile对象,因此您可以在调用 user.save() 后访问新创建的配置文件用户

profile = user.get_profile()
profile.verified = False
profile.ip_address = get_client_ip()
profile.save()

我假设,您UserProfilemodels.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即使在初始化和验证之后你也不使用它。

于 2013-01-20T20:30:59.167 回答
0

好吧,如果请求是 POST,则收集所有表单数据,您只需将其传递给字典即可将其传递回视图。

d=dict(username=form.cleaned_data["username"]), ... )
...
return render_to_resopnse("mytemplate.html", d, context_instance)
于 2013-01-20T19:54:33.513 回答