How can I get the ids of a queryset from a model and store them into a different model using a form?

无人久伴 提交于 2021-02-08 09:38:06

问题


I have a model called 'Competicion', with some objects and another model called 'Participante'. This second model has two fields: a foreignkey with the user and another foreingkey to 'Competicion'.

In the view, I've made queryset from 'Competicion' and with a for loop in the template I've given each object the button of the form. With storing the user of the current session I have no problem but I want the form to know which object of the queryset it is to grab its id. #I have no problem with choices I just don't include them to save space

Models.py

 class Competicion(models.Model):
   ciudad          = models.CharField(max_length=50, null=True, choices=Ciudades_a_elegir, default="Ninguna")
   nombre          = models.CharField(max_length=20, null=True, choices=Competiciones_a_elegir, default="Ninguna")
   titulo          = models.CharField(max_length=40, null=True)
   fecha           = models.DateField(null=True)
   participantes   = models.IntegerField(null=True)
   flyer = models.ImageField(null=True, upload_to='imagenes', default='Ninguna')

def __str__(self):
    return self.nombre + " " + self.titulo


class Participante(models.Model):
   competicion   = models.ForeignKey(Competicion, on_delete=models.CASCADE, null=True, blank=True)
   participantes = models.ForeignKey(User, on_delete=models.CASCADE, null=True)

def __str__(self):
    return self.competicion.nombre + " " +  self.competicion.titulo

forms.py

class ParticipanteForm(ModelForm):
  class Meta:
    model   = Participante
    exclude = ['competicion', 'participantes']

views.py

def competiciones(request):

qs = Competicion.objects.all()

form = ParticipanteForm(request.POST or None)
if form.is_valid():

    nombres = form.save()
    nombres.competicion     = ???#Help me
    nombres.participantes   = request.user 
    nombres.save()
    return redirect('home')

context = {
    'object_list':qs,
    'form':form,
}   
return render(request, "competiciones.html", context)

template

{% for i in object_list %}
<ul>
    
    <li>{{i.nombre}}</li>
    <li>{{i.ciudad}}</li>
    <li>{{i.titulo}}</li>
    <li>{{i.fecha}}</li>
    <li>{{i.participantes}}</li>

    {% if i.flyer  %}
    <img src="{{i.flyer.url}}" width="100px" >
    {% endif %}

    <li><form action="" method="POST">
        {% csrf_token %}

        <p> {{ form.competicion}} </p>
        
        <p>{{form.participantes}}</p>
        
        <input type="submit" name="Inscribirse" value="Inscribirse"> 
    </form>  </li>
</ul>

{% endfor %}

This is only like 1 course. In number one there is the different fields of the Competicion Model. And number two is the button of the form to the Participante Model, which fields are hidden and take the id of the course and the user. So I have a lot of these both courses displayed in the web. The function of the Particpante Model is to store the people who register in the course and the course itself.

def competiciones(request):
 qs = Competicion.objects.all()
 form = ParticipanteForm(request.POST or None)
 if form.is_valid():
  data = form.save()
  data.participantes_id   = request.user
   for i in qs:
    data.competicion_id = i.id

    data.save()

    return redirect('home')

回答1:


I think you should try to store user id in Competicion model instead of Participante

 class Competicion(models.Model):
 participantes = models.ForeignKey(User, on_delete=models.CASCADE, 
null=True)
 def __str__(self):
     return self.nombre + " " + self.titulo

and inside your views.py

def competiciones(request):

form = ParticipanteForm(request.POST or None)
if form.is_valid():
    nombres = form.save()
    nombres.participantes_id   = request.user 
    nombres.save()
    return redirect('home')

context = {
    'object_list':qs,
    'form':form,
}   
return render(request, "competiciones.html", context)

Python

def competiciones(request):
qs = Competicion.objects.all()
form = ParticipanteForm(request.POST or None)
if form.is_valid():
    data = form.save()
    data.participantes_id   = request.user
    for i in qs:
        data.competicion_id = i.id
    
    data.save()

    return redirect('home')

This is partly working. The competicion_id only gets the last Competicion object created and that's not what I want.



来源:https://stackoverflow.com/questions/65600155/how-can-i-get-the-ids-of-a-queryset-from-a-model-and-store-them-into-a-different

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!