user1781245
user1781245

Reputation: 21

Store the current user in a field of a django model

I'm trying to find the way of store the user who creates an object and I want to do it automatically. I've found some things but nothing works for me. Here is the code:

Models.py:

class Track(models.Model):
    ...
    usuari = models.ForeignKey(User)

Forms.py:

class TrackForm(forms.ModelForm):   
    class Meta:
        model = Track

Views.py

def pujar_track(request):
if request.method=='POST':
    formulari = TrackForm(request.POST, request.FILES)
    if formulari.is_valid():                    
        formulari.save()                    
        return HttpResponseRedirect('/inici')
else:
    formulari = TrackForm()

return render(request,'principal/trackForm.html',
    {'formulari':formulari})

I've seen about put:

usuari = models.ForeignKey(User, blank=True, editable=False) but

But I don't know when can I set the user in the field.

Thanks in advice!

Upvotes: 1

Views: 432

Answers (1)

Maik Hoepfel
Maik Hoepfel

Reputation: 1797

You can hide usuari from your TrackForm, so the user can't select it:

class TrackForm(forms.ModelForm):   
    class Meta:
        model = Track
        exclude = ('usuari',)

And then, replace your formulari.save() with:

track = formulari.save(commit=False)
track.user = request.user
track.save()

This is a common use case and detailed in the Django docs.

Upvotes: 3

Related Questions