0

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},)
Ally Alfie
  • 131
  • 11
  • Hey Ålasa, this is a very common pattern. Usually you exclude the user field from the form and assign this automatically when saving based on the currently logged in user. The form is in the admin or in a view you wrote? Check http://books.agiliq.com/projects/django-admin-cookbook/en/latest/current_user.html – Paulo Scardine Nov 22 '18 at 11:46
  • Please show your view/form, or if you are using the Django admin, your model admin class. – Alasdair Nov 22 '18 at 11:46
  • 1
    You don't do this in the model, you do it in the view, which you have not shown. – Daniel Roseman Nov 22 '18 at 11:52

1 Answers1

0

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.

Alasdair
  • 298,606
  • 55
  • 578
  • 516