Dynamically created shape selection in Django

I have a form for submitting new articles to Django, in this form you can put a message in "user_group", just a lot of relationships between groups and users. However, you can only add it to the groups to which you belong. Using the init function from the form class, I can pass in an additional field, and I get the right choice that I need, but when I submit, I get an error. QueryDict object does not have an attribute "all"

I'm not sure what is going wrong, here is my form:

class PostForm(BaseModelForm):
new_image = forms.ImageField(required=False)
#GROUPS = user.groups.all()
#group = forms.ChoiceField(choices=GROUPS, required=False )

def __init__(self,groups, *args, **kwargs):
    super(PostForm, self).__init__(*args, **kwargs)
    self.fields['group'].queryset = groups

    class Meta:
        model = Post
        fields = ('title','category', 'group', 'text', 'description', 'style')

        help_texts = {
            'group': _('Do you want this published under your account or a group?')
        }

and sees the view where the error occurs:

@login_required
def post_new(request):
    if request.method == "POST":
        form = PostForm(request.POST, request.FILES)
        if form.is_valid():
            post = form.save(commit=False)
            post.author = request.user
            post.save()
            return redirect('post_detail', pk=post.pk)
    else:
        form = PostForm(groups=request.user.user_groups.all())
    return render(request, 'blog/post_edit.html', {'form': form})

This line:

form = PostForm(groups=request.user.user_groups.all())

, . , , , , Im .

+4
2

groups GET POST. GET.

if request.method == "POST":
    form = PostForm(request.user.user_groups.all(), request.POST, request.FILES)
    ...
+1

, :

class PostForm(models.ModelForm):
    group = forms.ChoiceField(queryset = None)

    def __init__(self,groups, *args, **kwargs):
        super(PostForm, self).__init__(*args, **kwargs)
        self.fields['group'].queryset = request.user.user_groups.all()

https://docs.djangoproject.com/en/1.11/ref/forms/fields/#fields-which-handle-relationships

queryset None, __init__ , .

+1

Source: https://habr.com/ru/post/1675612/


All Articles