0

I'm developping my Django web application and I would like to insert usernames field in my table when any users are adding a row in the database. Obviously, users have to be logged in my application.

My form.py file looks like this :

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'}) 

How I can write this line :

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

In order to know which user has added, modified or deleted row(s) ? user.username works in my html template as example, but I don't know How I can pick up this variable and put it directly in my form ?

Thank you by advance !

Essex
  • 6,042
  • 11
  • 67
  • 139
  • You should set the user in the view, not the form. If you use a hidden input, the user could change the value before submitting the form. – Alasdair May 22 '17 at 15:14
  • I don't want to use ForeignKey, but just username, it's different, because both databases (users and BirthCertificate) are not in the same place .. And I have some local databases which are connected to a global database – Essex May 22 '17 at 15:15
  • @Alasdair Something like this in my view : `form.fields['user'].initial = user.username` ? – Essex May 22 '17 at 15:17
  • You can use the same approach with a `CharField`. Just set the value to `request.user.username` instead of `request.user`. – Alasdair May 22 '17 at 15:18
  • I defined in my model this field : `user = models.CharField(max_length=30, null=False, verbose_name="utilisateur")`. I will try to follow your advice – Essex May 22 '17 at 15:19

0 Answers0