我正在尝试实现ModelForm,我遇到的问题是模型不仅不保存,而且还没有重定向帖子。当我直接将表单作为HTML编写时,我没有遇到这些问题。
models.py:
class Foo(models.Model):
foo = models.IntegerField(null=True)
class FooBar(models.Model):
foo = models.ForeignKey('ZipCode')
title = models.CharField(max_length=100)
description = models.CharField(max_length=400, null=False, blank=True )
slug = models.SlugField(unique=True)
forms.py:
class FooForm(forms.ModelForm):
class Meta:
model = Foo
fields= ['foo',]
class FooBar(forms.ModelForm):
title= forms.CharField(max_length=100, help_text="FooBar title")
description = forms.CharField(help_text="FooBar description",
widget=forms.Textarea(attrs={'paceholder':'Please enter your description'}))
slug = forms.CharField(widget=forms.HiddenInput(), required=False)
class Meta:
model = Movement
exclude = ['foo']
view.py:
def new_foobar(request):
template_name = 'new_foobar.html'
if request.method == 'POST':
foo_form = fooForm(data=request.POST)
foobar_form = FooBarForm(data=request.POST)
if foo_form.is_valid() and foobar_form.is_valid():
foo, create = FooBar.objects.get_or_create(**form.cleaned_data)
foobar = foobar_form.save(commit=False)
foobar.foo = foo
foobar.save(commit=True)
return redirect('/results/%d' %zipcode.id)
else:
foo_form = FooForm()
foobar_form = FooBarForm()
答案 0 :(得分:2)
你的意思是?:
if request.method == 'POST':
...