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

用户10898133

我匹配ProfileUser通过OneToOne信号的方式。我创建SignUpForm额外的字段(locationemailfirstname等)和电子邮件确认。

如何使这种信息(locationemailfirstname等)automacally加入Profile

我想,这真的让

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

但我不知道怎么做。

模型.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

表格.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', )

信号.py

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

管理文件

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

视图.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!')

模板profile_detail.html

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

我认为您可以将附加数据放入view方法中。你可以这样试试:

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

在这里,我没有在表单或配置文件中添加电子邮件名字,因为如果您使用的是默认auth.User模型,那么这些数据已经在模型中可用。为此,请参见AbstractBaseUser实现。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

在Python字典中,((j * 5)+1)%2 ** i如何遍历所有2 ** i

生成系列1,2,1,3,2,1,4,3,2,1,5,4,3,2,1

如何将HTML5自动对焦添加到Rails表单?

vector <int> + = 1,1,2,2,2,3,4,5,6如何; 可能?

如何在JavaScript中[1,2] + [4,5,6] [1] = 1,25

如何将Mysql ASC命令1,2,3,4,5而不是1,10,11,12?

如何递归求解T(n)= 5T(n / 2)+ n ^ 2,T(1)= 2

如何使5的条件只有1如果2否则1其他?

Android Studio:如何将项目从listview1添加到listview2 onClick

如何将array1(2D)添加到array2(3D)?

如何将3个不同的数字添加到数组的i,i + 1和i + 2

如何将2个动画添加到1个关键帧中

将数组的元素添加为a [0],a [1] + a [2],a [3] + a [4] + a [5],a [6] + a [7] + a [8] + a [9] ...等等

给定一个升序排列的int数组,编写一种算法将所有重复项推回back.ex [1,2,2,4,5,5]变为[1,2,4,5,2,5]

R:如何制作序列(1,1,1,2,3,3,3,4,5,5,5,6,7,7,7,8)

如何将libgtkmm-2.4-1v5降级为libgtkmm-2.4-1c2a?

如何生成图案5 5 5 5 5 4 4 4 4 3 3 3 2 2 1

python 将列表 [0, 1, 2, 3, 4, 5] 转换为 [0, 1, 2], [1,2,3], [2,3,4]

如何将表 1 中的数据添加到 mysql 中的表 2?

如何使用张量流将 [1,2,3,4,5,6] 重塑为 [[1,3,5],[2,4,6]]?

将 Angular[2] V3, Dart 1 的路由转换为 Angular 5, Dart 2

如何将 1 添加到 2 列的列的值?

将 int ([3,6]) 数组转换为 [[1,2,3],[1,2,3,4,5,6]]

如何将 1 个月添加到 1 月 30 日或 31 日以及 2 月之后,分别需要 30 日或 31 日

如何使用 dcast() 将 5x2 data.table 转换为 1x5 data.tabe?

如何将 Select2 添加到 Shopware 5 插件中的 smarty 模板?

Java将字符串转换为数组“[1,2,3,4,5,5]”到[1,2,3,4,5,5]

仅在引导程序 5 中使用 1 个 div 时如何将第二个浮动标签添加到输入

如何在列表类型的DataFrame列中将`[1, 5]`变成`[1, 2, 3, 4, 5]`?