在Django中向数据库添加对象后添加多对多值

时间:2012-11-25 21:06:58

标签: django

我有一个表单,要求用户为他们上传的文件添加一个类别,即ManytoManyField。但是,此字段的值未添加到数据库中,我无法弄清楚原因。以下代码中的变量为descategories

<form enctype="multipart/form-data" method="POST" action="" class="uniForm">
        <fieldset class="inlineLabels">
            {% csrf_token %}
            <table>
            <tr>
            <td>Design Title:</td><td>{{ formtoadddesign.modelname}}</td></td></tr>
            <tr><td>Author:</td> <td>{{ formtoadddesign.author }}</td></tr>
            <tr><td>Description:</td> <td>{{ formtoadddesign.description }}</td></tr>
            {% comment %}<tr><td>Design Image:&nbsp&nbsp&nbsp</td><td>{{ formtoadddesign.partimage }}</td></tr>{% endcomment %}
            <tr><td>Tags:</td><td>{{formtoadddesign.tags}}</td></tr>
            <tr><td>Format:</td><td>{{formtoadddesign.format}}</td></tr>
            <tr><td>Category:</td><td>{{formtoadddesign.descategories}}</td></tr>
            <tr><td>Attach File</td><td>{{formtoadddesign.content}}</td></tr>
                    </div>
            </table>
            <br>
            <div class="form_block">
                <input type="submit" class="btn btn-success" value="{% trans 'Add Design' %}">
            </div>
            <br>
        </fieldset>
    </form>

我的views.py中有以下代码:

def add_design (request):
    # POST request  
    if request.method == "POST":
        formtoadddesign = designform(request.POST, request.FILES)
        if formtoadddesign.is_valid():
            new_design = formtoadddesign.save(commit=False)
            new_design.adder = request.user
            designname = new_design.modelname
            format = new_design.format
            adder_id = new_design.adder.id
            file = request.FILES['content']
            filename = file.name
            filecontent = file.read()
            file.seek(0)
            new_design.content=store_in_s3_design(filename, filecontent, designname, format, adder_id)
            new_design.save()
            cats = new_design.descategories
            print "new_design id:", repr(new_design.id)
            print cats
            for cat in cats.all():
                new_design.designcategory_id.add(cat)
                print "added %s" % cat

基本上我似乎无法从ManytoManyField中获取值,这基本上是人们可以选择的表单中的列表。如何访问这些值 - cats.all()什么都不返回,所以我一定做错了...

这是我的表格:

class designform(ModelForm):
    def __init__(self, *args, **kwargs):
        super(designform, self).__init__(*args,**kwargs)
        self.is_update=False

    def clean(self):
        """
        Do Validation stuff
        """
        if 'modelname' not in self.cleaned_data:
                return
        if not self.is_update:
            return self.cleaned_data

    class Meta:
        model = Design

1 个答案:

答案 0 :(得分:1)

因为您使用save(commit=False),所以需要save_m2m

请参阅https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#the-save-method