在Django Updateview中保存表单集的问题

时间:2019-08-11 03:39:40

标签: python django formset

我是Django和Stackoverflow的新手,所以如果我的代码不标准,请接受我的道歉。 我尝试创建一个博客网站。用户可以创建和更新帖子,每个帖子可以具有一个或多个类别,也可以没有类别。我将表单用于Post,将Formset用于Category。但是,由于某种原因,在Updateview中我无法保存表单集!!!!

models.py

class Post(models.Model):
    title = models.CharField(max_length=128)
    text = models.TextField(blank=True)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    created_date = models.DateTimeField(auto_now_add=True)
    modified_date = models.DateTimeField(auto_now=True)
    published_date = models.DateTimeField(blank=True, null=True)

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('post-detail', kwargs={'pk': self.pk})


class Category(models.Model):
    name = models.CharField(max_length=128, unique=True)
    description = models.TextField(blank=True)
    posts = models.ManyToManyField(Post, 
            blank=True,related_name='categories')

    class Meta:
        verbose_name_plural = 'Categories'

    def __str__(self):
        return self.name

forms.py

from django import forms
from blogging.models import Post, Category

class PostUpdateForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = ['title', 'text', 'published_date']

CATEGORY_CHOICES = [('', 'Choose from the list')]
for c in Category.objects.all():
    CATEGORY_CHOICES.append((c, c))


class CategoryUpdateForm(forms.ModelForm):
    class Meta:
        model = Category
        fields = ['name']
        labels = {'name': 'Category'}
        help_texts = {'name': 'Choose category for your post'}
        widgets = {
            'name': forms.Select(choices=CATEGORY_CHOICES)
        }


 CategoryFormset = forms.modelformset_factory(Category, 
                                        form=CategoryUpdateForm, extra=1,
                                             max_num=3, can_delete=True)

views.py

from blogging.models import Post, Category
from blogging.forms import PostUpdateForm, CategoryFormset

class PostUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
    model = Post
    template_name = 'blogging/post_update.html'
    form_class = PostUpdateForm
    formset_class = CategoryFormset

    def form_valid(self, form):
        form.instance.author = self.request.user
        context = self.get_context_data()
        formset = context['formset']
        if formset.is_valid():
            category_form = formset.save(commit=False)
            category_form.posts.add(self.get_object())
            category_form.save()
            formset.save()

        return super().form_valid(form)

    def test_func(self):
        post = self.get_object()
        if self.request.user == post.author:
            return True
        return False

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        post = self.get_object()
        if self.request.POST:
            context['formset'] = self.formset_class(self.request.POST)
        else:
            context['formset'] = 
                     self.formset_class(queryset=post.categories.all())
        return context

模板

<form method="POST" enctype="multipart/form-data">
        {% csrf_token %}
        <fieldset class="form-group">
            <legend class="border-bottom mb-4">Profile Info</legend>
            {{ u_form | crispy }}
            {{ p_form | crispy }}
        </fieldset>
        <div class="form-group">
            <button class="btn btn-outline-info" 
               type="submit">Update</button>
        </div>
</form>

1 个答案:

答案 0 :(得分:0)

我可以找到答案。通过使用Extra-view包并使用CreateInlineView和UpdateInlineView,都可以解决。 https://django-extra-views.readthedocs.io/en/latest/