Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can I render a ManyToManyField as checkboxes?
    text
    copied!<p>I'm making a game link site, where users can post links to their favorite web game. When people post games they are supposed to check what category the game falls into. I decided to allow many categories for each game since some games can fall into many categories. So the question is, how do I handle this in my view? And how can I show it as Checkboxes, where at least one has to be checked? And how can I show this as checkboxes in the Admin as well? </p> <h2>Here is the code</h2> <h2>Models:</h2> <pre><code>class Category(models.Model): category = models.CharField(max_length=200) def __unicode__(self): return self.category class Game(models.Model): name = models.CharField(max_length=200) url = models.CharField(max_length=200) poster = models.ForeignKey(User, related_name='game_poster_set') postdate = models.DateTimeField(default=datetime.now) cats = models.ManyToManyField(Category) hits = models.IntegerField(default=0) post = models.BooleanField(default=False) </code></pre> <hr> <h2>Views:</h2> <pre><code>def submit(request): form = GameForm(request.POST or None) if form.is_valid(): game = form.save(commit=False) game.poster = request.user game.save() next = reverse('gamesite.games.views.favorites') return HttpResponseRedirect(next) return render_to_response( 'games/submit.html', {'form': form}, context_instance = RequestContext(request),) </code></pre> <hr> <h2>Forms:</h2> <pre><code>class GameForm(forms.ModelForm): name = forms.CharField(max_length=15, label='Name') url = forms.URLField(label='URL', initial='http://') class Meta: model = Game fields = ('name','url') </code></pre> <p>Thanks! </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload