简体   繁体   English

如何将注册期间指定的信息自动添加到“个人资料”? Django 2.1.5

[英]How automatically add info, specified during registration, to "Profile"? Django 2.1.5

I matched Profile with User by OneToOne with signals.我通过OneToOne ProfileUser与信号进行了匹配。 I created SignUpForm with additional fields ( location , email , firstname etc) and email confirmation.我创建SignUpForm带有附加字段( locationemailfirstname等)和电子邮件确认的SignUpForm

How make the this info ( location , email , firstname etc) automacally added to Profile ?如何将此信息( locationemailfirstname等)自动添加到Profile

I think, this really make with我想,这真的让

user.refresh_from_db()
user.profile.<...>=form.cleaned_data.get('<...>')

but I don't know how.但我不知道怎么做。

models.py模型.py

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    first_name = models.CharField(max_length=30, blank=True, default='', null=True)
    location = models.CharField(max_length=30, blank=True, default='')
    email = models.EmailField(max_length=30, blank=True, default='', null=True)

    class Meta:
        ordering = ["location"]

    def get_absolute_url(self):
        return reverse('profile-detail', args=[str(self.id)])

    def __str__(self):
        return self.user.username

forms.py表格.py

class SignupForm(UserCreationForm):
    email = forms.EmailField()
    location = forms.CharField()

    class Meta:
        model = User
        fields = ('username', 'email', 'location', 'password1', 'password2')


class ProfileForm(forms.ModelForm):
    class Meta:
        model = Profile
        exclude = ('user', )

signals.py信号.py

@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance)

admin.py管理文件

class ProfileAdmin(admin.ModelAdmin):
    list_display = ('user', 'location', 'email', 'first_name')

views.py视图.py

def signup(request):
    if request.method == 'POST':
        form = SignupForm(request.POST)
        if form.is_valid():
            user = form.save(commit=False)
            user.is_active = False
            user.save()
            current_site = get_current_site(request)
            mail_subject = 'Activate your blog account.'
            message = render_to_string('acc_active_email.html', {
                'user': user,
                'domain': current_site.domain,
                'uid':urlsafe_base64_encode(force_bytes(user.pk)).decode(),
                'token':account_activation_token.make_token(user),
            })
            to_email = form.cleaned_data.get('email')
            email = EmailMessage(
                        mail_subject, message, to=[to_email]
            )
            email.send()
            return HttpResponse('Please confirm your email address to complete the registration')
    else:
        form = SignupForm()
    return render(request, 'signup.html', {'form': form})


def activate(request, uidb64, token):
    try:
        uid = force_text(urlsafe_base64_decode(uidb64))
        user = User.objects.get(pk=uid)
    except(TypeError, ValueError, OverflowError, User.DoesNotExist):
        user = None
    if user is not None and account_activation_token.check_token(user, token):
        user.is_active = True
        user.save()
        login(request, user)
        # return redirect('home')
        return HttpResponse('Thank you for your email confirmation. Now you can login your account.')
    else:
        return HttpResponse('Activation link is invalid!')

template profile_detail.html模板profile_detail.html

...
<h1>User: {{ profile.user }}</h1>
  <p>{{ profile.first_name|safe }}</p>
  <p>{{ profile.email|safe }}</p>
  <p>{{ profile.location|safe }}</p>
...

I think you can put the additional data in the view method .我认为您可以将附加数据放在view方法中。 You can try like this:你可以这样试试:

# form

class SignupForm(UserCreationForm):
    location = forms.CharField()

    class Meta:
        model = User
        fields = ('username', 'email', 'location', 'password1', 'password2')

# view

def signup(request):
   ...
   location = form.cleaned_data.get('location')
   user = form.save(commit=False)
   user.is_active = False
   user.save()
   profile = user.profile
   profile.location = location
   profile.save()
   ...

Here I am not adding email and firstname in the form or in the profile, because if you are using default auth.User model, then these data are available in the Model already.在这里,我没有在表单或配置文件中添加电子邮件名字,因为如果您使用默认的auth.User模型,那么这些数据已经在模型中可用。 For that, please see then AbstractBaseUser implementation.为此,请参见AbstractBaseUser实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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