I'm inserting entries into my database from the front end but the current logged in user foreign key is not populating. It get's entered as null.
here is my model:
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class WordsAndPhrases (models.Model):
word_or_phrase = models.CharField(max_length=20000)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
added_by = models.ForeignKey(User, null=True, on_delete=models.DO_NOTHING)
def __str__(self):
return self.word_or_phrase
here is my views.py code snippet.
def upload(request):
if request.method == 'POST':
wordOrPhrase = request.POST['word-or-phrase']
currentUser = request.user
print(currentUser)
newEntry = WordsAndPhrases(word_or_phrase = wordOrPhrase)
addedBy = WordsAndPhrases(added_by = currentUser)
newEntry.save()
return render(request, 'display_words_phrases_app/upload.html')
Thanks in advance.
CodePudding user response:
You need to define an id key in your model
id = models.AutoField(primary_key=True, )
CodePudding user response:
You are creating two entry objects. When you create a new object, you should insert both word_or_phrase
and added_by
like this:
def upload(request):
if request.method == 'POST':
wordOrPhrase = request.POST['word-or-phrase']
currentUser = request.user
print(currentUser)
newEntry = WordsAndPhrases(word_or_phrase = wordOrPhrase, added_by = currentUser)
newEntry.save()
return render(request, 'display_words_phrases_app/upload.html')
Your addedBy
object was useless.