Search code examples
djangosqlitedjango-modelsdjango-formsdjango-database

How to retrieve current Django user and feed it into a db entry


Question Closed: Please see response posted by Alasdair for solution.

I am adding instances of Pets to a table:

class Pet(models.Model):
   petName = models.CharField(max_length=100, default='My Pet')
   petImage = models.ImageField(default='default.png', blank=True)
   author = models.ForeignKey(User, on_delete=models.CASCADE, default=None)

The code above is fine, however "User" on the last line gives me all the Users ever signed up on my app in a dropdown menu (when viewed as a form). I want the author (i.e. the User that is logged in) to be automatically associated with this new pet object.

I dont know the ins and outs of the inbuilt auth_user database, so I dont know how to reference this specific instance of user, meaning the one who is logged in. I know that request.user on the other pages returns the user logged in, I just dont know how to feed that variable into this model. Any ideas?

* UPDATE: Included views.py *

@login_required(login_url="/accounts/login/")
def add_pet(request):
    if request.method == 'POST':
        form = forms.AddPet(request.POST, request.FILES)
        if form.is_valid():
            instance = form.save(commit=False)
            instance.save()
            return redirect('yourPet')
    else:
        form = forms.AddPet()
    return render(request, 'records/pet_create.html', {'form': form},)

Solution

  • First, edit your model form to remove the author field.

    class AddPet(forms.ModelForm):
        class Meta:
            model = Pet
            fields = ['petName', 'petImage']  # leave out author
    

    Then in your view, you can set instance.author to request.user before you save the instance.

    if request.method == 'POST':
        form = forms.AddPet(request.POST, request.FILES)
        if form.is_valid():
            instance = form.save(commit=False)
            instance.author = request.user
            instance.save()
            return redirect('yourPet')
    

    The last step is to consider the case when the user is not logged in, but you have already covered this by using the login_required decorator.