Karan Yogi
Karan Yogi

Reputation: 91

Want to assign foreign key from views.py file

I created a post model that is linked to the user by the foreign key(author). I don't want the user to set the foreign key of the post. I want the active user(who wrote the post) to be the foreign key of the post.

Models.py file-
class Post(models.Model):
    author = models.ForeignKey(User, related_name="posts",on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now=True)
    heading = models.CharField(max_length=400)
    message = models.TextField()
    message_html = models.TextField(editable=False)

    def __str__(self):
        return self.message

    def save(self,*args,**kwargs):
        self.message_html = misaka.html(self.message)
        super().save(*args,**kwargs)

    def get_absolute_url(self):
        return reverse('posts:single',kwargs={'username':self.user.username,'pk':self.pk})

    class Meta:
        ordering = ['-created_at']
        unique_together = ['auther','message']

The form class of this model-

class PostForm(forms.ModelForm):
    class Meta():
        fields=("heading","message")
        model=Post

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields["heading"].label = "Heading"
        self.fields["message"].label = "Write Blog"

The view function that is creating the model post. In this function, I want to set the active user as foreign key.

@login_required
def CreatePost(request):
    if request.method == 'POST':
        post_form = PostForm(data=request.POST)
        if post_form.is_valid():
            post = post_form.save()
            post.author=request.user.username
            post.save()
            return redirect('/my_profile')
        else:
            print(post_form.errors)
    else:
        post_form=PostForm()
    return render(request,'create_post.html',{'post_form':post_form})

Upvotes: 1

Views: 190

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477210

The reason this does nto work is because post_form.save() will already try to save the Post object to the database. You can however simply alter the instance wrapped in the form.

Furthermore since the author is a ForeignKey to a User object, you should pass request.user, not request.user.username:

@login_required
def CreatePost(request):
    if request.method == 'POST':
        post_form = PostForm(data=request.POST)
        if post_form.is_valid():
            post_form.instance.author = request.user
            post = post_form.save()
            return redirect('/my_profile')
        else:
            print(post_form.errors)
    else:
        post_form=PostForm()
    return render(request,'create_post.html',{'post_form':post_form})

Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.

Upvotes: 1

Related Questions