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(),
}