user10634359
user10634359

Reputation:

Django : How to associate a user to a created post when post is created through a ModelForm

I've created a normal Django posts app, which basically let's users create posts and it's content. Now the thing is that I implemented the create post form as a ModelForm in forms.py. Now if it wasn't a ModelForm and just a html-form, I would have used request.POST.get('data') But now I use

class PostForm(forms.ModelForm):
class Meta:
    model = Post
    fields = (
        'title',
        'content',
        'image',
    )

Models.py

class Post(models.Model):
    title = models.CharField(max_length=100)
    image = models.ImageField(null=True,blank=True)
    content = models.TextField()
    user = models.ForeignKey(User,on_delete=models.CASCADE,null=True)

Views.py

def create(request):
    form = PostForm(request.POST or None)
    if form.is_valid():
        instance = form.save(commit=False)
        instance.save()
        return HttpResponseRedirect('/home')
    return render(request,'create.html',{'form':form})

How can I relate a user to a created post?

Upvotes: 2

Views: 1901

Answers (1)

ritlew
ritlew

Reputation: 1682

You can simply assign the user to the instance in between the two save functions:

instance = form.save(commit=False)
instance.user = request.user
instance.save()

Upvotes: 4

Related Questions