how to add post to django user model using foreignkey

i created a model

class ThisUser(models.Model):
     created = models.DateTimeField(auto_now=True)
     message = models.CharField(max_length=120)
     user = models.ForeignKey(User, on_delete=models.CASCADE)

   def __str__(self):
       return self.user

I want to store message specifically for the user who is authenticated. right now this will give me all user who is available in my user model. Please help

3 answers

  • answered 2018-02-18 08:54 Rasovica

    Well you are suppose to take care of that at view level and not model level, for example this is how I create a new Album:

    def make_album(request):
    if request.method == 'POST':
        form = AlbumCreationForm(request.POST)
        if form.is_valid():
            new_album = core_models.Album(name=form.cleaned_data['name'], description=form.cleaned_data['description'], user=request.user)`

  • answered 2018-02-18 08:54 Vipin Mohan

    user = models.OneToOneField(User, on_delete=models.CASCADE)

    Instead of foriegn key use one to one relation

  • answered 2018-02-18 08:54 Peter R.

    You can use to get user's id for further use.