(Django)如何在视图中将当前用户的用户名分配给其他模型?

时间:2019-03-17 11:40:26

标签: django django-models django-forms django-views django-admin

我想将Passengers模型的用户名字段分配给当前登录用户的用户名。我似乎做不到。下面是代码。

Models.py

class UserProfileInfo(models.Model):

        user = models.OneToOneField(User,on_delete=models.CASCADE)
        profile_pic = models.ImageField(upload_to='profile_pics',blank=True)

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

class Passengers(models.Model):
        username = models.CharField(max_length = 100)
        passenger_firstname = models.CharField(max_length = 100)
        passenger_lastname = models.CharField(max_length = 100)
        passenger_age = models.CharField(max_length = 100)
        passenger_gender =  models.CharField(max_length=6, choices=GENDER_CHOICES, default='female')

froms.py

class PassengerForm(forms.ModelForm):
    class Meta():
        model = Passengers
        fields = (
        'passenger_firstname',
        'passenger_lastname',
        'passenger_age',
        'passenger_gender')

views.py

def passenger_info(request):

    if request.method == "POST":

        passenger_details = PassengerForm(data=request.POST)

        if passenger_details.is_valid():
            passenger_details.username = request.user
            passenger_details.save()

    else:
        passenger_details = PassengerForm()

    return render(request,'passenger_info.html',{'passenger_details':passenger_details})

没有打印出任何错误消息,但用户名字段为空白,如下所示:

django-admin model object

2 个答案:

答案 0 :(得分:0)

首先,这样做是没有意义的。您应该为用户模型创建一个ForeignKey。

此外,request.user将返回用户对象而不是用户名,因此,如果您需要用户名,则应将其命名为:request.user.username

并解决您的问题:

class Passengers(models.Model):
    username = models.ForeignKey(User, null=False, blank=False)
    passenger_firstname = models.CharField(max_length = 100)
    passenger_lastname = models.CharField(max_length = 100)
    passenger_age = models.CharField(max_length = 100)
    passenger_gender =  models.CharField(max_length=6, choices=GENDER_CHOICES, default='female')

您也可以从用户模型中获取名字和姓氏。此外,性别和年龄应该采用UserProfileInfo模式,这更有意义,而Passengers模式应该是将用户链接至公共汽车,飞机等,以不保留不会改变的数据。

答案 1 :(得分:0)

虽然@ Navid2zp的答案是正确的,但您遇到的另一个问题是此行:

passenger_details.username = request.user

passenger_detailsModelForm,并且在初始化后没有属性username。它具有一个字段username,如果表单具有passenger_details['username'],则可以作为绑定字段(data)进行访问;也可以作为表单字段(passenger_details.fields['username'])进行访问。

通过赋予属性username,您将一事无成,因为它不会与字段username关联。

但是在保存表单之前,将附加参数分配给表单实例的最简单方法是:

profile = passenger_details.save(commit=False)  # gives you the instance
profile.user = request.user  # assuming you're using `ForeignKey` here, calling it `user` instead of `username` for clarity
profile.save()