Django manytomany models views and templates

0

I have the Gammer model that is the User extension and the Competition model. many players can play a competition and a competition can have many players ( ManyToMany )

class Gammer(User):

    competition = models.ManyToManyField(Competition)
    puntaje_global = models.IntegerField(default=0)
    ranking = models.IntegerField(default=0)


class Competition(models.Model):

    name = models.CharField(max_length=50)
    created_date = models.DateTimeField(default=timezone.now)
    published_date = models.DateTimeField(blank=True, null=True)
    finish_date = models.DateTimeField(blank=True, null=True)
    duration = models.DurationField(blank=True, null=True)

    def finish(self):
        self.finish_date = timezone.now()
        self.save()

    def publish(self):
        self.published_date = timezone.now()
        self.save()

    def __str__(self):
        return self.name

Add in admin.py:

admin.site.register (Gammer)

The admin can visualize competitions of player or assign them competitions: Now I want the players to choose the competitions they want to subscribe to.

I created GammerForm in forms.py (I do not know if it's correct)

class GammerForm(forms.ModelForm):

    competition = forms.ModelMultipleChoiceField(
        queryset=models.Competition.objects.all())

    class Meta:
        model=models.Gammer
        fields =('competition', )

How can I continue so that the user from his account can join the competitions and not the admin anymore? That is to say, that all the competences are listed and that the user can subscribe, and if everything goes well the admin could see the competences in which the user joined.

    
asked by Naomi 23.10.2017 в 23:14
source

1 answer

0

A very basic example (without using ModelForms) so you can pull the thread:

Views:

def competiciones(request):
   if request.post:
       comp_add = request.post.get('competition')
       Competition.objects.create(user=request.user, comp_id = comp_add)

   comp_disponibles = Competition.objects.all()
   render(request, 'comp_disponibles.html',{'comp_disponibles':comp_disponibles})

template (comp_available.html)

{% block content %}

<form method="POST">

<select id="competition" name="competition">
         {% for comp in comp_disponibles %}
           <option value="{{ comp.id }}">{{ comp.nombre }}</option>
         {% endfor %}
</select>
<input type="submit" value="añadirme a la competición">
<form>

{% endblock %}

This what it does is generate a new template that contains a form with a select that adds competitions one by one.

It could be more complicated by adding several competitions or doing it by ajax, but I think this is a starting point.

    
answered by 26.10.2017 в 14:28