简体   繁体   中英

Setting the UserProfile values

I have created my UserProfile model as instructed in the docs but how can I pass the values to be saved from my view. This is how my view looks like:

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

Update 1

Since, you are using post_save() signal on User model to create UserProfile object, you can access newly created profile user after calling user.save()

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

I assume, you have UserProfile model in your 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()

However, I don't understand why are you not using your RegistrationForm even after initializing and validating it.

Well if the request is a POST, all of your form data is collected and you can pass it back to the view just by passing it to a dictionary.

d=dict(username=form.cleaned_data["username"]), ... )
...
return render_to_resopnse("mytemplate.html", d, context_instance)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM