Set a models user field to the current logged in user before saving its django ModelForm
i have a model form as so below
class JobForm(ModelForm):
class Meta:
model = Job
exclude = ('date_added', 'date_modified','owner','status','tags','slug','winning_tech','completiondate')
The owner field is a foreignKey linked to the Django User model and it's excluded from being rendered in the form. I am trying to set the owner field to the current logged in user before i save开发者_JAVA百科 the form. My save function is contained in the following code.
def createJob(request):
bix_user=getBixUser(request.user)
if request.method == 'POST':
form = JobForm(request.POST)
form.fields['owner']=bix_user
if form.is_valid():
form.save()
return HttpResponseRedirect('/home')
else:
....
I am very sure that i am doing the wrong thing. I have not been in touch with my django side for a while so i would appreciate any help.
I always overwrite the save()
method and add a user to it.
Something like this:
class JobForm(ModelForm):
def save(self, user, commit=True):
job = ModelForm.save(commit=False)
job.owner = user
if commit:
job.save()
return job
I use a variation on WoLph above:
def save(self, *args, **kwargs):
# add defaut owner field if not already stated
if 'owner' not in self.__dict__:
self.creator = system_user()
super(MyModel, self).save(*args, **kwargs)
So answered my own question, use commit=false and modify whatever values you want. This code section draws in ideas from the two previous answers( wolPh and user*** )
def save(self,user, commit=True, *args, **kwargs):
job = super(JobForm, self).save(commit=False,*args, **kwargs)
job.owner = user
if commit:
job.save()
return job
精彩评论