Django ManyToManyField在自定义模板中?

时间:2014-07-01 23:20:38

标签: python django forms django-forms manytomanyfield

我正在尝试创建添加模板的自定义对象。我做了标题,描述等部分,但是我无法弄清楚那些很多东西。

这是我的观点:

def add_product(request):
    form = ProductForm(request.POST or None)
    categories = Category.objects.all()
    if form.is_valid():
        product = form.save(commit=False)
        product.user = request.user

        at = slugify(form.cleaned_data['title'])
        if at in sluglist:
            n = 0
            while at in sluglist:
                n += 1
                at = slugify(form.cleaned_data['title'])+str(n)
            product.slug = at
            sluglist.append(product.slug)
            product.active = True
            product.save()
            return HttpResponseRedirect('/products/%s'%(product.slug))
        else:
            product.slug = slugify(form.cleaned_data['title'])
            sluglist.append(product.slug)
            product.active = True
            product.save()
            return HttpResponseRedirect('/products/%s'%(product.slug))


    return render_to_response("products/add.html", locals(), context_instance=RequestContext(request))

这是我的模特:

class Category(models.Model):
    title = models.CharField(max_length=120)
    description = models.CharField(max_length=500)
    slug = models.SlugField()
    timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
    updated = models.DateTimeField(auto_now_add=False, auto_now=True)

    def __unicode__(self):
        return str(self.title)

    class Meta:
        verbose_name = "Category"
        verbose_name_plural = "Categories"



class Product(models.Model):
    user = models.ForeignKey(User, null=True, blank=True)
    title = models.CharField(max_length=50)
    description = models.TextField(max_length=500)
    price = models.DecimalField(max_digits=20, decimal_places=2)
    categories = models.ManyToManyField(Category)
    slug = models.SlugField()
    order = models.IntegerField(default=0)
    timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
    updated = models.DateTimeField(auto_now_add=False, auto_now=True)
    active = models.BooleanField(default=True)

    def __unicode__(self):
        return str(self.title)

    class Meta:
        ordering = ['-order']

    def get_absolute_url(self, ):
        return reverse('single_product', args=[self.slug])

这是我的admin.py:

class CategoryAdmin(admin.ModelAdmin):
    prepopulated_fields = {"slug": ('title',)}
    class Meta:
        model = Category

admin.site.register(Category, CategoryAdmin)




class ProductAdmin(admin.ModelAdmin):
    list_display = ('__unicode__','description','price','order','live_link')

    inlines = [TagInline, ProductImageInline]
    search_fields = ['title','description','price', 'tag__tag']
    list_filter = ['price', 'timestamp', 'updated']
    prepopulated_fields = {"slug": ('title',)}

    readonly_fields = ['live_link', 'timestamp', 'updated']

    class Meta:
        model = Product


    def live_link(self,obj):
        link = "<a href='/products/" + str(obj.slug)+ "/'>" + obj.title + "<a/>"
        return link

    live_link.allow_tags = True

admin.site.register(Product, ProductAdmin)

这是我的forms.py:

class ProductForm(ModelForm):
    categories = forms.ModelMultipleChoiceField
    class Meta:
        model = Product
        fields = ('title', 'description', 'price', 'categories')

这是我的add.html(添加内容)

<form method='POST' action='' >
{% csrf_token %}
    <div class="form-group">
                <input type="text" placeholder="Başlık" class="form-control" name="title" value="" >
    </div>
    <div class="form-group">
                <textarea type="text" placeholder="Description" class="form-control" name="description" value="" ></textarea>
    </div>
    <div class="form-group">
                <input type="text" placeholder="Price" class="form-control" name="price" value="" >
    </div>

    <div class="form-group">
        <select multiple="multiple" name="categories" id="id_categories">
            {% for cat in categories %}
            <option>{{ cat }}</option>
            {% endfor %}
        </select>
    </div>
<input type='submit' value='Kaydet/Save' class="btn btn-info"/>

</form>

如果没有类别部分在forms.py和add.html中它可以工作,但我也想添加类别选择。 当我添加我在上面的代码中包含的类别部分时,它不保存表单而不添加对象。 我怎么解决这个问题。 感谢。

1 个答案:

答案 0 :(得分:1)

标签的值不是来自标签之间的元素(填充菜单),而是来自&#39;值&#39;标签本身的属性。您需要更改此行:

<option>{{ cat }}</option>

到此:

<option value="{{cat.id}}">{{cat}}</option>

ModelChoiceField(ManyToMany对象使用的表单字段)期望一个模型ID号(尽管您可以选择使用另一个带有&#39; to_field_name&#39;属性的模型字段)。没有&#39;值&#39;在选项标记中,ModelChoiceField永远不会收到有效值,这就是模型永远不会保存的原因。

有关详细信息,请参阅the documentation on ModelChoiceFields