在数据库中创建对象时插入当前用户?

时间:2017-05-22 15:07:21

标签: django django-forms

我正在开发我的Django web application,当任何用户在数据库中添加行时,我想在我的表中插入usernames field。显然,用户必须登录我的应用程序。

我的form.py文件如下所示:

class CustomLabelModelChoiceField(forms.ModelChoiceField):

    def __init__(self, *args, **kwargs):
        self._label_from_instance = kwargs.pop('label_func', force_text)
        super(CustomLabelModelChoiceField, self).__init__(*args, **kwargs)

    def label_from_instance(self, obj):
        return self._label_from_instance(obj)

class BirthCertificateForm(forms.ModelForm):
    fk_parent1 = CustomLabelModelChoiceField(Person.objects.filter(), required=False, label = "Père", label_func=lambda obj: '%s %s %s' % (obj.lastname, obj.firstname, obj.social_number))
    fk_parent2 = CustomLabelModelChoiceField(Person.objects.filter(), required=False, label = "Mère", label_func=lambda obj: '%s %s %s' % (obj.lastname, obj.firstname, obj.social_number))
    mairie = forms.CharField(widget=forms.HiddenInput(), initial=Mairie.objects.using('default').last().city.encode('utf-8'))
    user = forms.CharField(widget=forms.HiddenInput(), initial=user.username)
    social_number = forms.CharField(widget=forms.HiddenInput(),required=False)


    class Meta :
        model = BirthCertificate
        fields = ['lastname', 'firstname', 'sex', 'birthday', 'birthhour', 'birthcity', 'birthcountry','fk_parent1', 'fk_parent2', 'mairie', 'user', 'social_number']
        widgets = {'country': CountrySelectWidget()}

        def __init__(self, *args, **kwargs):    
            super(BirthCertificateForm, self).__init__(*args, **kwargs)
            for key, value in self.fields.iteritems() :
                self.fields[key].widget.attrs.update({'class':'form-fields'}) 

我怎么写这一行:

user = forms.CharField(widget=forms.HiddenInput(), initial=user.username)

为了知道哪些用户添加,修改或删除了行? user.username在我的html模板中作为示例,但我不知道如何获取此变量并将其直接放在我的表单中?

提前谢谢你!

0 个答案:

没有答案