某些形式的另一个问题
这是我的模特
class TankJournal(models.Model): user = models.ForeignKey(User) tank = models.ForeignKey(TankProfile) ts = models.IntegerField(max_length=15) title = models.CharField(max_length=50) body = models.TextField()
这是我的模型
class JournalForm(ModelForm): tank = forms.IntegerField(widget=forms.HiddenInput()) class Meta: model = TankJournal exclude = ('user','ts')
这是我保存它的方法
def addJournal(request, id=0): if not request.user.is_authenticated(): return HttpResponseRedirect('/') # # checking if they own the tank # from django.contrib.auth.models import User user = User.objects.get(pk=request.session['id']) if request.method == 'POST': form = JournalForm(request.POST) if form.is_valid(): obj = form.save(commit=False) # # setting the user and ts # from time import time obj.ts = int(time()) obj.user = user obj.tank = TankProfile.objects.get(pk=form.cleaned_data['tank']) # # saving the test # obj.save() else: print form.errors else: form = JournalForm(initial={'tank': id})
当它保存..它抱怨坦克不是TankProfile而是整数..如何覆盖表单对象以使坦克成为TankProfile
谢谢
我想你想要这个:
class JournalForm(ModelForm): tank = forms.ModelChoiceField(label="", queryset=TankProfile.objects.all(), widget=forms.HiddenInput)