custom form author - auto save author to DB
I have a custom form... I'd like to auto save the author (authenticated user) for the form data. I'm using ModelForm for creating the form.
models.py
class Tracker(models.Model):
client = models.ForeignKey(Clients)
user = models.ForeignKey(User)
description = models.TextField()
...
I have also linked the custom profile to the django users table... also the auth works fine... I can read the user and id...
forms.py
class TrackerForm(ModelForm):
def __init__(self, *args, **kwargs):
super(TrackerForm, self).__init__(*args, **kwargs)
self.fields.keyOrder = ['date_job_start','date_job_end','description','onsite','billable','client']
class Meta:
model = Tracker
widgets = {
'cl开发者_Python百科ient': HiddenInput(),
}
When the form is created from the upper class and I try to save it... it wants the user data (missing warning). How can I change it so that it would automatically save the authenticated user instead of asking for it?? I know that I dont' have the user field defined here... that's because I don't want a dropdown for it... I want the user to be saved from the auth...without any selection or display...
P.S.: I know about the initial
option... there must be a better way?
Thanks! BR
class TrackerForm(ModelForm):
def __init__(self, *args, **kwargs):
self.user = kwargs.pop('user')
super(TrackerForm, self).__init__(*args, **kwargs)
self.fields.keyOrder = ['date_job_start','date_job_end','description','onsite','billable','client']
class Meta:
model = Tracker
widgets = {
' client': HiddenInput(),
}
exclude = ('user',)
def save(self):
obj = super(TrackerForm, self).save(commit=False)
obj.user = self.user
obj.save()
return obj
And in view:
form = TrackerForm(user=request.user) #and other parameters
精彩评论