[Django]-Django Many-To-Many Relationship (category)

3👍

the main problem is that you havent saved the post object to the database before assigning the Category. so change the view a bit to this

def post(request):
if request.method == 'POST':
    form = Post_form(request.POST, request.FILES)
    if form.is_valid():
        post = form.save(commit=False)
        post.user = request.user
        post.save()
        for k in form.cleaned_data['category']:
            p1 = Category.objects.create(title=k)
            p1.save()
            post.category.add(p1)

0👍

Edit your view like this,

if form.is_valid():
    title = form.cleaned_data['category']
    post = form.save(commit=False)
    post.user = request.user
    post.save()
    category = Category.objects.create(title=title)
    post.category.add(category)
    post.save_m2m()
    return redirect('home:home')

Leave a comment