Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

190
Visualizações
Dynamically generated form choices in Django

I have a form for submitting new articles in Django, in this form you're allowed to place the post into a 'user_group', just a many many relationship between groups and users. However, you're only allowed to add it into groups you belong to. Using the init function of the form class i can pass in an extra field, and I do get the correct choices I need, however on submit I get an error ''QueryDict' object has no attribute 'all''

I'm not sure whats going wrong, heres 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 heres the view where the error is being thrown:

@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())

Is where I pass in the choices for groups, which does give you the correct choices. The fact that the error happens on submitting make me think its an error in how the view processes it, but Im not sure where.

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

You need to pass groups to the form for GET and POST requests. At the moment you're only doing it for GET requests. It should be

if request.method == "POST":
    form = PostForm(request.user.user_groups.all(), request.POST, request.FILES)
    ...
over 4 years ago · Santiago Trujillo Relatório

0

I think you have to query for the groups in the form:

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

It's important to define queryset as None, and in __init__ make the query when the form instance is created.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda