简体   繁体   English

我在 Django 中有一个带有 ManyToManyField 的表。 无法弄清楚如何更新表条目

[英]I have a table in Django with ManyToManyField. Can't figure out how to update a table entry

I have a table with posts that can have multiple categories, and a table with categories that can have multiple posts.我有一个包含多个类别的帖子的表格,以及一个包含多个帖子的类别的表格。 models.py:模型.py:

class Category(models.Model):
   name = models.CharField(max_length=20)

    def __str__(self):
        return self.name

class Post(models.Model):
    title = models.CharField(max_length=25)
    body = models.TextField()
    image = models.ImageField(blank=True)
    created_on = models.DateTimeField(auto_now_add=True)
    last_modified = models.DateTimeField(auto_now=True)
    categories = models.ManyToManyField('Category', related_name='posts', blank=True)
    profile = models.ForeignKey('Profile', verbose_name='User',
                                on_delete=models.CASCADE,
                                related_name='profile')

    def __str__(self):
        return self.title

views.py视图.py

Сlass ListCategoryView(generic.ListView):

    def get(self, request, *args, **kwargs):
        category = kwargs['category']
        posts = Post.objects.filter(categories__name__contains=category).order_by('-created_on')
        context = {
            "category": category,
            "posts": posts
        }
        return render(request, "list_category.html", context)

class ListPostView(generic.ListView):

    model = Post
    context_object_name = 'posts'
    template_name = 'list_post.html'

    def get_queryset(self):
        queryset = super().get_queryset()
        queryset = queryset.order_by('-created_on')
        return queryset

class CreatePostView(LoginRequiredMixin, generic.CreateView):

    model = Post
    template_name = 'create_post.html'
    form_class = PostDocumentForm

    def post(self, request, *args, **kwargs):
        blog_form = PostDocumentForm(request.POST, request.FILES)
        if blog_form.is_valid():
            categories = Category.objects.create(name=blog_form.cleaned_data['categories'])
            title = blog_form.cleaned_data.get('title')
            body = blog_form.cleaned_data.get('body')
            profile = request.user.profile
            image = self.get_image(blog_form)
            instance = Post.objects.create(title=title, body=body, profile=profile, image=image)
            instance.categories.set([categories])
            return HttpResponseRedirect('/blog/')
        return render(request, 'create_post.html', context={'form': blog_form})

    def get_image(self, form):
        image = form.cleaned_data.get('image')
        return image


class EditPostView(generic.UpdateView):

    form_class = PostDocumentForm
    model = Post
    template_name = 'edit_post.html'
    success_url = '/blog/'

forms.py: forms.py:

class CategoryDocumentForm(forms.ModelForm):
    class Meta:
        model = Category
        fields = ('name',)


class PostDocumentForm(forms.ModelForm):
    categories = forms.CharField(min_length=3, max_length=100, required=False)

    class Meta:
        model = Post
        fields = ('title', 'body', 'image', 'categories')

I can't figure out how to update the post so that the categories are updated as well.我不知道如何更新帖子以便更新类别。 I looked for many solutions, but none of them helped.我寻找了许多解决方案,但没有一个有帮助。 I tried get_or_create, update, delete, then create again, but nothing worked.我尝试了 get_or_create、更新、删除,然后再次创建,但没有任何效果。 Better, as in most social networks - add a tag(here a category) manually, without selecting from the list of possible ones更好,就像在大多数社交网络中一样 - 手动添加一个标签(这里是一个类别),而不是从可能的列表中选择

This might help you:这可能会帮助您:

class PostEditView(UpdateView):
     def form_valid(self, form):
        # Take care of creating of updating your post with cleaned data
        # by yourself

        category_tokens = form.cleaned_data['categories'].split()
        categories = set()
        for token in category_tokens:
            try:
                category = Category.objects.get(name=token)
            except ObjectDoesNotExist:
                category = Category.objects.create(name=token)
            
            categories.add(category)

        # now you need to add the categories which are new to this post
        # and delete the categories which do not belong anymore to your post
        current_posts_categories = set(post_instance.categories_set.all())
        categories_to_add = categories - current_posts_categories
        categories_to_delete = current_posts_categories - categories

        # further handling is up to you ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Django框架ManyToManyField。 如何在索引列表页面中获取特定值 - Django Framework ManyToManyField. How can i get a specific value in my index list page 无法弄清楚如何将文本放在表格中(公平密码) - can't figure out how to put the text in the table (playfair cipher) 我似乎无法弄清楚如何更新 tkinter 标签 - I can't seem to figure out how to update tkinter labels 如何从网站上抓取股票表。 我认为 class 或标签是一个问题,但我不知道 - How to scrape a stock table from a website. I think class or tag is a problem but I can't figure out 我有一个争论的问题,我不知道为什么? - I have an argument issue and I can't figure out why? 我如何按Django中的ManyToManyField的id排序? - How can I sort by the id of a ManyToManyField in Django? 如何将选择限制为 django ManyToManyField? - How can I limit choices to django ManyToManyField? Django测试:DatabaseError:没有用于ManyToManyField的这样的表 - Django testing: DatabaseError: no such table for ManyToManyField 如何检查 ManyToManyField 表以更新 m2m 取决于父字段 django - how to check to ManyToManyField table to update m2m depend on a parent field django 我有一个不知道如何解决的缩进错误 - I have an unindentation error that I can't figure out how to fix
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM