如何将单个表单中的ManyToMany关系与单个提交相关联

时间:2016-09-10 19:03:44

标签: django django-forms django-views

我有两个具有ManyToMany关系,Category和Post的模型。我试图将两个模型,post_form和category_form合并为一个提交按钮。保存时如何显示关系?

目前,当我为两个不同的帖子添加相同的category_name时,它会向我发出警告,说它已经存在。我希望能够在下拉列表中选择相同的category_name或类似的东西。请帮忙。如果这不可能,我的替代方案是什么?

Models.py
class Category(models.Model):
    category_name       = models.CharField(max_length=250, unique=True)
    category_slug       = models.SlugField(max_length=250, unique=True)

class Post(models.Model):
    STATUS_CHOICES      = (
                        ('draft', 'Draft'),
                        ('published', 'Published'),
                        )

    title               = models.CharField(max_length=250)
    slug                = models.SlugField(max_length=250, 
                                        unique_for_date='publish')
    body                = models.TextField()
    publish             = models.DateTimeField(default=timezone.now)
    created             = models.DateTimeField(auto_now_add=True)
    updated             = models.DateTimeField(auto_now=True)
    status              = models.CharField(max_length=10, 
                                        choices=STATUS_CHOICES,
                                        default='draft')
    categories          = models.ManyToManyField(Category)

    def get_absolute_url(self):
    return reverse('posts:post_detail',
            args=[self.publish.year,
                self.publish.strftime('%m'),
                self.publish.strftime('%d'),
                self.slug])

Views.py

def post_list(request):
    queryset = Post.objects.all()
    return render(request, 'posts/post_list.html', {'post_list': queryset})

def post_detail(request, year, month, day, post):
    instance = get_object_or_404(Post, slug            = post,
                                   status          = 'published',
                                   publish__year   = year,
                                   publish__month  = month,
                                   publish__day    = day)
    return render(request, 'posts/post_detail.html', {'post':instance})

def post_create(request):
    post_form = PostForm(request.POST or None)
    category_form = CategoryForm(request.POST or None)

    if post_form.is_valid() and category_form.is_valid():
    post_form_instance = post_form.save()
    category_form_instance = category_form.save()
    print (request.POST)
    print (post_form.is_valid)

    context = {'post_form':post_form, 'category_form':category_form}
    return render(request, 'posts/post_form.html', context)

forms.py
class PostForm(forms.ModelForm):
    class Meta:
    model   = Post
    fields  = [
            'title',
            'slug',
            'body',
            'publish',
            'status',
            ]


class CategoryForm(forms.ModelForm):
    class Meta:
    model   = Category
    fields  = [
            'category_name',
            'category_slug',                
            ]
post_form.html

<!--DOCTYPE html -->

<html>
    <head>
    </head>


    <body>
    <form method='POST'>{% csrf_token %}

    <h1>Form</h1>


    {{ post_form.as_p }} 
    {{ category_form.as_p }}

    <input type="submit" value="Create Post" />

    </form>
    </body>

</html> 

1 个答案:

答案 0 :(得分:0)

你到底想要实现什么,你究竟在问什么?根据您的代码,您将为帖子的类别和条目创建条目。你应该做的是做一些帖子,同时提供选择与之相关的类别的选项。请更好地了解您的情况和当前的代码。

试试这个:

forms.py
class PostForm(forms.ModelForm):
    class Meta:
    model   = Post
    fields  = [
            'title',
            'slug',
            'body',
            'publish',
            'status',
            'categories',
            ]
views.py
def post_create(request):
    post_form = PostForm(request.POST or None)

    if post_form.is_valid() and category_form.is_valid():
    post_form_instance = post_form.save()
    context = {'post_form':post_form,}
    return render(request, 'posts/post_form.html', context)

post_form.html
<html>
    <head>
    </head>


    <body>
    <form method='POST'>{% csrf_token %}

    <h1>Form</h1>


    {{ post_form.as_p }} 

    <input type="submit" value="Create Post" />

    </form>
    </body>

</html>