如何将MultipleToManyField渲染为复选框? [英] How can I render a ManyToManyField as checkboxes?

查看:107
本文介绍了如何将MultipleToManyField渲染为复选框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个游戏链接站点,用户可以在其中发布链接到
最喜爱的网络游戏。
当人们发布游戏时,他们应该检查
游戏属于哪个类别。
我决定允许每个游戏的许多类别,因为一些游戏可以
属于许多类别。
所以问题是,我该如何处理这个?
我如何将其显示为复选框,至少有一个必须是
检查?
如何在管理员中显示为复选框?

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?

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) 






视图:




Views:

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






表单:




Forms:

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(widget=forms.CheckboxSelectMultiple(),required=True)
        class Meta: 
                model = Game 
                fields = ('name','url','cats')

应该修复您的视图,但我不确定管理员。仍然看着...会编辑,如果我找到任何东西。

that should fix your view, but i'm not sure about the admin. still looking... will edit if i find anything.

这篇关于如何将MultipleToManyField渲染为复选框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆