I'm making a little Twitter-like app that you can "tweet" in. I've already set up the logic to log in, log out, register and write new posts. But now, when a user is logged in, I want the username to be automatically assigned to the user who logged in. models.py
class Tweet(models.Model):
image = models.ImageField(null=True, blank=True)
text = models.TextField(max_length=300, default='')
created_at = models.DateTimeField(default=timezone.now)
user = models.ForeignKey(User, on_delete=models.CASCADE)
forms.py
class NewTweet(forms.ModelForm):
class Meta:
model = Tweet
fields = ['image', 'text']
I only show the fields image and text. The created_at and user attributes should be filled in automatically. Now in my views.py I handle saving new posts (tweets): views.py
@login_required
def newTweet(request):
if request.method == 'POST':
new_tweet = NewTweet(request.POST)
if new_tweet.is_valid():
new_tweet.cleaned_data['user'] = request.user
new_tweet.save()
return redirect('homepage')
else:
new_tweet = NewTweet()
return render(request, 'homepage/new-tweet.html', {
'tweet': new_tweet
})
I tried to assign the user via clean_data attr. and the request.user but that doesn't work and throws an error
IntegrityError at /new-tweet NOT NULL constraint failed: homepage_tweet.user_id
Inside the html file I just paste {{ tweet }}
inside a form tag. I knew that I got the right user because when I print request.user the logged in user is shown correct. Does anyone have a solution to my problem?