Django 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])

This is my 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)

这是我的form .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它的工作,但我想添加类别选择太。当我添加包含在上面代码中的类别部分时,它不会保存表单,也不会添加对象。我怎样才能解决这个问题?谢谢。

标签in的值不是来自标签之间的元素(它们填充菜单),而是来自标签本身的'value'属性。您需要更改这一行:

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

:

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

ModelChoiceField (manymany对象使用的表单字段)正在等待一个模型id号(尽管您可以选择使用带有'to_field_name'属性的另一个模型字段)。如果在选项标签中没有'value'属性,ModelChoiceField就永远不会收到一个有效值,这就是模型永远不会保存的原因。

查看ModelChoiceFields的文档获取更多信息

相关内容

  • 没有找到相关文章

最新更新