我正在建立一个游戏链接网站,用户可以在其中发布链接 最喜欢的网页游戏 当人们发布游戏时,他们应该检查什么类别 游戏落入。 我决定允许每个游戏的许多类别,因为一些游戏可以 分为很多类别。 所以问题是,我如何处理这个问题? 我怎样才能将它显示为Checkboxes,其中至少有一个必须是 检查? 如何在管理员中将其显示为复选框?
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')
谢谢!
答案 0 :(得分:38)
以下是我如何解决它(编辑:和管理员事务)
cats = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple, queryset=Category.objects.all())
(这是我找不到的查询集部分..)
cats = form.cleaned_data['cats']
game.cats = cats
这就是保存数据所需的所有代码。
编辑: 这是管理员的解决方案
from django.contrib import admin
from django.forms import CheckboxSelectMultiple
class MyModelAdmin(admin.ModelAdmin):
formfield_overrides = {
models.ManyToManyField: {'widget': CheckboxSelectMultiple},
}
from gamesite.games.models import Game, MyModelAdmin
admin.site.register(Game, MyModelAdmin)
外表有点古怪,但有效! 如果有人找到让它更“干净”的方法,请发帖!
干杯!
答案 1 :(得分:36)
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')
应该修复你的观点,但我不确定管理员。如果我找到任何东西,仍然会看... ...
答案 2 :(得分:0)
Dropbox工程经理Chase Seibert对此进行了研究
from django.db import models
from django.forms.models import ModelForm
from django.forms.widgets import CheckboxSelectMultiple
class Company(models.Model):
industries = models.ManyToManyField(Industry, blank=True, null=True)
class CompanyForm(ModelForm):
class Meta:
model = Company
fields = ("industries")
def __init__(self, *args, **kwargs):
super(CompanyForm, self).__init__(*args, **kwargs)
self.fields["industries"].widget = CheckboxSelectMultiple()
self.fields["industries"].queryset = Industry.objects.all()