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












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},)









share|improve this question

























  • 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 books.agiliq.com/projects/django-admin-cookbook/en/latest/…

    – 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
















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},)









share|improve this question

























  • 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 books.agiliq.com/projects/django-admin-cookbook/en/latest/…

    – 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














0












0








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},)









share|improve this question
















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},)






django sqlite django-models django-forms django-database






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 22 '18 at 13:26







Ålasa Fidler

















asked Nov 22 '18 at 11:42









Ålasa FidlerÅlasa Fidler

33




33













  • 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 books.agiliq.com/projects/django-admin-cookbook/en/latest/…

    – 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



















  • 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 books.agiliq.com/projects/django-admin-cookbook/en/latest/…

    – 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

















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 books.agiliq.com/projects/django-admin-cookbook/en/latest/…

– Paulo Scardine
Nov 22 '18 at 11:46







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 books.agiliq.com/projects/django-admin-cookbook/en/latest/…

– 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





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




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





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 Answer
1






active

oldest

votes


















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.






share|improve this answer
























  • This worked like a charm, thank you so much :)

    – Ålasa Fidler
    Nov 22 '18 at 13:22











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53430255%2fhow-to-retrieve-current-django-user-and-feed-it-into-a-db-entry%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









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.






share|improve this answer
























  • This worked like a charm, thank you so much :)

    – Ålasa Fidler
    Nov 22 '18 at 13:22
















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.






share|improve this answer
























  • This worked like a charm, thank you so much :)

    – Ålasa Fidler
    Nov 22 '18 at 13:22














0












0








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.






share|improve this answer













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.







share|improve this answer












share|improve this answer



share|improve this answer










answered Nov 22 '18 at 13:16









AlasdairAlasdair

180k26305308




180k26305308













  • This worked like a charm, thank you so much :)

    – Ålasa Fidler
    Nov 22 '18 at 13:22



















  • This worked like a charm, thank you so much :)

    – Ålasa Fidler
    Nov 22 '18 at 13:22

















This worked like a charm, thank you so much :)

– Ålasa Fidler
Nov 22 '18 at 13:22





This worked like a charm, thank you so much :)

– Ålasa Fidler
Nov 22 '18 at 13:22


















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53430255%2fhow-to-retrieve-current-django-user-and-feed-it-into-a-db-entry%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

404 Error Contact Form 7 ajax form submitting

How to know if a Active Directory user can login interactively

Refactoring coordinates for Minecraft Pi buildings written in Python