Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

187
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda