我正在制作一个游戏链接网站,用户可以在其中发布指向自己喜欢的网络游戏的链接。人们发布游戏时,应该检查游戏属于哪一类。我决定允许每个游戏包含多个类别,因为某些游戏可以分为多个类别。所以问题是,我该如何处理呢?以及如何将其显示为“复选框”,其中必须选中至少一个?以及如何在“管理”中将其显示为复选框?
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)
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),)
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')
谢谢!
class GameForm(forms.ModelForm): name = forms.CharField(max_length=15, label='Name') url = forms.URLField(label='URL', initial='http://') cats = forms.ModelMultipleChoiceField( queryset=Category.objects.all(), widget=forms.CheckboxSelectMultiple, required=True) class Meta: model = Game fields = ('name','url','cats')
那应该可以解决您的观点,但是我不确定管理员。仍在寻找…如果我发现任何东西,将进行编辑。