Django - Modify widget Select custom list?

2

Very good, I would like to know how to modify my select with a modified query, I make myself explain ...

models.py

class Equipo(models.Model):
    nombre = models.CharField(max_length=200)
    color = RGBColorField()
    torneo = models.ForeignKey(Torneo, on_delete=models.CASCADE)
    user = models.ForeignKey(User, on_delete=models.CASCADE)

    def __str__(self):
        return (self.nombre)

forms.py

class Equipo_Form(forms.ModelForm):
    class Meta:
        model = Equipo
        fields =[
            'nombre',
            'color',
            'torneo',
        ]

        labels={
            'nombre':'Nombre del Equipo',
            'color':'Color Uniforme',
            'torneo':'Participar Torneo',
        }

        widgets={
            'nombre': forms.TextInput(attrs={'class':'form-control'}),
            'color': RGBColorField(),
            'torneo': forms.Select(attrs={'class':'form-control'}),
        }

This way it shows me in my forms.Select widget All the existing tournaments without importing the user, I want you to show me the list of tournaments created by the user.

I have a listView view where it shows the tournaments according to the logged in user this way:

views.py

class Torneo_ListView(ListView):    
    template_name = 'torneos/torneo_listar.html'

    def get_queryset(self, *args, **kwargs):
        return Torneo.objects.filter(user=self.request.user) 

some form of filtering in my models.select a list of tournaments according to the user.

I know that with the "chouce" are the values to be displayed but I do not know how to integrate the user to the query

widgets={
    'torneo': forms.Select(chouse=Torneos.objects.filter(user=¿??)attrs={'class':'form-control'}),
        }

that I should go there, I've tried "(user = self.request.user)" just like in the ListView but obviously it does not work.

See the documentation for the Select class link

I do not understand very well how to apply it. Beforehand I apologize if the solution is easy and I did not know how to fix it.

SOLUTION:

views.py

class Equipo_CreateView(CreateView):
    model = Equipo
    template_name = "torneos/equipo_crear.html"
    form_class = Equipo_Form
    success_url = reverse_lazy('torneos:equipo_crear')

    def get_form_kwargs(self):
        kwargs = super(Equipo_CreateView, self).get_form_kwargs()
        kwargs.update({'request': self.request})

    def form_valid(self, form_class):
        form_class.instance.user_id = self.request.user.id
        return super(Equipo_CreateView, self).form_valid(form_class)

forms.py

class Equipo_Form(forms.ModelForm):

    def __init__(self, request, *args, **kwargs):
        super(Equipo_Form, self).__init__(*args, **kwargs)
        self.fields['torneo'].queryset =  Torneo.objects.filter(user=request.user)

    class Meta:
        model = Equipo
        fields =[
            'nombre',
            'color',
            'torneo',
        ]

        labels={
            'nombre':'Nombre del Equipo',
            'color':'Color Uniforme',
            'torneo':'Participar Torneo',
        }


        widgets={
            'nombre': forms.TextInput(attrs={'class':'form-control'}),
            'color': RGBColorField(),
        }
    
asked by jhon perez 06.04.2017 в 20:58
source

1 answer

2

When you work with select that come from a model, you do not need to use a widget Select , Django one day created a magic widget called ModelChoiceField which is responsible for rendering a queryset making it select and options , This widget, already comes by default when you generate a ModelForm , so you do not need to specify it. That is, in your forms.py file, on the line where you put the tournament widget on a select, you could delete it and add the following:

...
def __init__(self, request, *args, **kwargs):
    super().__init__(*args, **kwargs)
    self.fields['torneo'].queryset = Torneo.objects.filter(user=request.user)
...

And the only thing you should keep in mind is that now every time you use the form in your view, you must add the request, like this:

class Equipo_CreateView(CreateView):
    ...
    def get_form_kwargs(self):
       kwargs = super().get_form_kwargs()
       kwargs.update({'request': self.request})
       return kwargs
...

I hope I helped you. Any questions, comments.

    
answered by 06.04.2017 / 21:35
source