user1781245
user1781245

Reputation: 21

Save the current user id in django model

I new in Django and i have found in everywhere but I haven't found what I looking for and it seems an easy work. I need to safe de current user id in the model Track when de user uploads a new Track. I only have found this:

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

But this causes the user to choose between the differents users. I want to safe the current user automatically in a hidden camp or something.

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

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

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

Thanks!

Upvotes: 1

Views: 819

Answers (1)

miki725
miki725

Reputation: 27861

This is where instance parameter is useful.

# form
class TrackForm(forms.ModelForm):
    class Meta:
        model = Track
        exclude = ('useri',)

# view
@login_required()
def pujar_track(request):
    track = Track(usuari=request.user)

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

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

So the user will be pre-filled and that field will not be displayed to the user.

The full doc is here.

Upvotes: 2

Related Questions