Python 如何在自定义字段中保存数据。(从用户扩展)Django

Python 如何在自定义字段中保存数据。(从用户扩展)Django,python,django,Python,Django,我正在使用django身份验证系统。我有我的用户模型 class User(models.Model): first_name = models.CharField(max_length = 50) last_name = models.CharField(max_length = 50) username = models.CharField(max_length = 50, unique = True) password = models.CharField(max_length = 50)

我正在使用django身份验证系统。我有我的用户模型

class User(models.Model):
first_name = models.CharField(max_length = 50)
last_name = models.CharField(max_length = 50)
username = models.CharField(max_length = 50, unique = True)
password = models.CharField(max_length = 50)

def __str__(self):
    return "%s %s" %(self.first_name, self.last_name)

    class Meta:
        abstract = True
最近我发现在使用django auth时不能添加一些额外的字段(例如:contact字段)。谷歌说,你可以扩展它。因此,我通过创建一个UserProfile来扩展它:

class UserProfile(User):
contact = models.CharField(max_length=20, null=True)

def __str__(self):
    return self.contact_info
问题是,我不知道如何将数据(联系人)添加/保存到UserProfile。以及如何在我的模板中显示它。我尝试了一些,但如果失败了:

views.py

if request.method == 'POST':

        fname = request.POST['fname']
        lname = request.POST['lname']
        contact = request.POST['contact']
        username = request.POST['username']
        password = request.POST['password']

        user = User.objects.create_user(username, email=None, password=password)
        user.first_name = fname
        user.last_name = lname
        user.contact = contact
        user.save()

        user.contact = contact
        user.save()

        return redirect('system.views.user_login')

是否有其他方法保存它?

我不知道您在哪里看到无法向用户模型添加额外字段。您已经在定义自己的模型;没有什么能阻止你添加你喜欢的任何字段


但是,如果要这样做,则必须从AbstractBaseUser继承,并将
AUTH\u USER\u MODEL
设置设置为指向您的模型。此外,将用户模型定义为抽象模型对您来说毫无意义。

我不知道您在哪里看到无法向用户模型添加额外字段。您已经在定义自己的模型;没有什么能阻止你添加你喜欢的任何字段


但是,如果要这样做,则必须从AbstractBaseUser继承,并将
AUTH\u USER\u MODEL
设置设置为指向您的模型。此外,将用户模型定义为抽象模型对您来说毫无意义。

要扩展django auth用户模型,您可以使用AbstractUser

from django.contrib.auth.models import AbstractUser
class UserProfile(AbstractUser):
    contact = models.CharField(max_length=20, null=True)

    def __str__(self):
        return self.contact_info

要扩展django auth用户模型,可以使用AbstractUser

from django.contrib.auth.models import AbstractUser
class UserProfile(AbstractUser):
    contact = models.CharField(max_length=20, null=True)

    def __str__(self):
        return self.contact_info