Jin Lee
Jin Lee

Reputation: 3

Django: How to save data to ManyToManyField

Your help will be nice for me. Here are that codes:

models.py:

from django.db import models

class TagModel(models.Model):
    tag = models.CharField(max_length=50)
    def __str__(self):
        return self.tag

class MyModel(models.Model):
    title = models.CharField(max_length=50)
    tag = models.ManyToManyField(TagModel)

forms.py:

from django import forms
from .models import *

class MyForm(forms.ModelForm):
    class Meta:
        model = MyModel
        fields = '__all__'

views.py:

from django.shortcuts import render, get_object_or_404, redirect
from .models import *
from .forms import *

def MyWriteView(request):
    if request.method == "POST":
        mywriteform = MyForm(request.POST)
        if mywriteform.is_valid():
            confirmform = mywriteform.save(commit=False)
            confirmform.save()
            return redirect('MyDetail', pk=confirmform.pk)
    else:
        mywriteform = MyForm()
    return render(request, 'form.html', {'mywriteform': mywriteform})

form.html(1st trial):

<form method="post">
  {% csrf_token %}
  {{ mywriteform }}
<button type="submit">Save</button>
</form>

form.html(2nd trial):

<form method="post">
  {% csrf_token %}
  {{ mywriteform.title }}
  <select name="tags" required="" id="id_tags" multiple="">
    {% for taglist in mywriteform.tags %}
    <option value="{{taglist.id}}">{{taglist}}</option>
    {% endfor %}
  </select>
<button type="submit">Save</button>
</form>

I am trying to add tags on my post. I made a simple manytomany tagging blog but it does not work. I submitted a post by clicking the save button, and the title was saved, but the tag was not. In the admin, it worked well.

Thank you in advance.

Upvotes: 0

Views: 145

Answers (1)

Shihabudheen K M
Shihabudheen K M

Reputation: 1397

update the code like this

if mywriteform.is_valid():
        confirmform = mywriteform.save(commit=False)
        confirmform.save()
        mywriteform.save_m2m()
        return redirect('MyDetail', pk=confirmform.pk)

for more details Refer here

Upvotes: 1

Related Questions