Используя виджет, я использовал поле CheckboxSelectMultiple, в результате queryset возвращает None

Я поместил форму в шаблон и реализовал добавление статьи. В результате пользователь заполняет информацию, особенно категории, которые используются в нескольких отношениях, и нажимает кнопку отправить. Информация может быть сохранена. Здесь важно, чтобы пользователь щелкнул по одной из категорий. Все, но в результате статья с правильной информацией, но категории возвращаются None, это моя проблема.

models.py

class CategoryArticle(models.Model):
    title = models.CharField(max_length=200, verbose_name='عنوان')
    url_title = models.CharField(max_length=200, verbose_name='عنوان در url')
    is_active = models.BooleanField(default=True, verbose_name='فعال / غیرفعال')

    def __str__(self):
        return self.url_title

    class Meta:
        verbose_name = 'دسته بندی مقاله'
        verbose_name_plural = 'دسته بندی های مقاله'


class Article(models.Model):
    title = models.CharField(max_length=200, verbose_name='عنوان مقاله')
    slug = models.SlugField(null=True, blank=True, verbose_name='اسلاگ')
    article_category = models.ManyToManyField(CategoryArticle, verbose_name='دسته بندی مقاله')
    short_description = models.TextField(verbose_name='توضیح مختصر')
    author = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='نویسنده')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='تاریخ ایجاد مقاله')
    views = models.PositiveIntegerField(default=0, verbose_name='تعداد بازدید', editable=False)
    preview_image = models.ImageField(upload_to='images/previews_articles/', verbose_name='پیش نمایش مقاله')
    content = CKEditor5Field('Text', config_name='extends')
    audio_file = models.FileField(upload_to='audio_files/', null=True, blank=True, verbose_name='فایل صوتی',
                                  validators=[validate_audio_file])
    video_file = models.FileField(upload_to='videos/', null=True, blank=True, verbose_name='فایل ویدیویی',
                                  validators=[validate_videos_file])
    is_active = models.BooleanField(default=True, verbose_name='فعال / غیرفعال')
    is_important_new = models.BooleanField(default=False, verbose_name='اخبار مهم')
    is_special = models.BooleanField(default=False, verbose_name='ویژه')

forms.py

class CreateArticleForm(forms.ModelForm):
    categories = forms.ModelMultipleChoiceField(
        label="دسته بندی مقاله",
        queryset=CategoryArticle.objects.filter(is_active=True),
        widget=forms.CheckboxSelectMultiple(),
        required=False,
    )

    def __init__(self, *args, **kwargs):
        super(CreateArticleForm, self).__init__(*args, **kwargs)
        self.fields["content"].required = False

    class Meta:
        model = Article
        fields = ['title', 'categories', 'short_description', 'preview_image', 'content', 'audio_file',
                  'video_file', 'is_active', 'is_important_new', 'is_special']
        widgets = {
            'title': forms.TextInput(attrs={'class': 'form-control'}),
            'short_description': forms.Textarea(attrs={'class': 'form-control', 'rows': 3}),
            'preview_image': forms.FileInput(attrs={'class': 'form-control'}),
            'audio_file': forms.FileInput(attrs={'class': 'form-control'}),
            'video_file': forms.FileInput(attrs={'class': 'form-control'}),
            'is_active': forms.TextInput(attrs={'class': 'form-control'}),
            'is_important_new': forms.CheckboxInput(attrs={'class': 'form-check-input'}),
            'is_special': forms.CheckboxInput(attrs={'class': 'form-check-input'}),
        }

views.py

class CreateArticleView(View):
    def get(self, request: HttpRequest):
        form_article = CreateArticleForm()
        context = {'form': form_article}
        return render(request, 'author_module/add_article_author.html', context)

    def post(self, request: HttpRequest):
        form_article = CreateArticleForm(request.POST, request.FILES)
        if form_article.is_valid():
            article = form_article.save(commit=False)
            article.author = request.user
            article.save()
            messages.success(request, 'مقاله شما پس از تصویب توسط مدیریت، به وبسایت منتقل خواهد شد.')
        else:
            for field, errors in form_article.errors.items():
                for error in errors:
                    messages.error(request, f"{field}: {error}")
        context = {'form': form_article}
        return render(request, 'author_module/add_article_author.html', context)

```[enter image description here](https://i.stack.imgur.com/vxTP3.png)
[enter image description here](https://i.stack.imgur.com/stSEZ.png)

--------------



[enter image description here][1]
[enter image description here][2]
Return the category selected by the user successfully


  [1]: https://i.stack.imgur.com/r7aII.png
  [2]: https://i.stack.imgur.com/VigIE.png
Вернуться на верх