django 获取表单页面复选框的值 报错
classBook(models.Model):title=models.CharField(max_length=100)authors=models.ManyToMa...
class Book(models.Model): title = models.CharField(max_length=100) authors = models.ManyToManyField(Author) publisher = models.ForeignKey(Publisher) publication_date = models.DateField() def __str__(self): return self.title
AuthorChoices = [(author.id,author.first_name + " " + author.last_name) for author in Author.objects.all()]PublisherChoices = [('','-----------')] + [(publisher.id,publisher.name) for publisher in Publisher.objects.all()]class AddBookForm(forms.Form): def __init__(self,*args,**kwargs): super(AddBookForm,self).__init__(*args,**kwargs) self.fields['authors'].choices = [(author.id,author.first_name + " " + author.last_name) for author in Author.objects.all()] self.fields['publisher'].choices = [('','-----------')] + [(publisher.id,publisher.name) for publisher in Publisher.objects.all()] title = forms.CharField(required = True) authors = forms.ModelMultipleChoiceField(queryset=AuthorChoices, widget=forms.CheckboxSelectMultiple()) publisher = forms.ChoiceField(choices=(),widget=forms.Select(attrs={'required':'true'})) publication_date = forms.DateField()AddBook.html 页面
<body> <h1>Add Book</h1> <form action="." method="POST"> {% csrf_token %} <table> {{form.as_table}} </table> <input type="submit" value = "Submit" /> </form></body>
addBook函数:
def addBook(request): if request.method == 'POST': form = AddBookForm(request.POST) if form.is_valid(): title = form.cleaned_data['title'] #authors = form.cleaned_data['authors'] #print authors publisher = form.cleaned_data['publisher'] publication_date = form.cleaned_data['publication_date'] #print authors, " ", publisher," ",publication_date article = Article(title=title,publisher_id=publisher,publication_date=publication_date) article.save() authorsIds = request.POST.getlist('authors') for authorId in authorIds: author = Author.objects.get(id=authorId) aritcle.authors.add(author) return render_to_response('articles/templates/addArticleSuccess.html',{'title':title},context_instance=RequestContext(request)) else: form = AddBookForm() return render_to_response('articles/templates/addBook.html', {'form': form},context_instance=RequestContext(request))表单在页面显示没有问题,但是提交表单的时候就出错了,错误如下:
请大侠帮忙,改怎样处理这个问题。 展开
AuthorChoices = [(author.id,author.first_name + " " + author.last_name) for author in Author.objects.all()]PublisherChoices = [('','-----------')] + [(publisher.id,publisher.name) for publisher in Publisher.objects.all()]class AddBookForm(forms.Form): def __init__(self,*args,**kwargs): super(AddBookForm,self).__init__(*args,**kwargs) self.fields['authors'].choices = [(author.id,author.first_name + " " + author.last_name) for author in Author.objects.all()] self.fields['publisher'].choices = [('','-----------')] + [(publisher.id,publisher.name) for publisher in Publisher.objects.all()] title = forms.CharField(required = True) authors = forms.ModelMultipleChoiceField(queryset=AuthorChoices, widget=forms.CheckboxSelectMultiple()) publisher = forms.ChoiceField(choices=(),widget=forms.Select(attrs={'required':'true'})) publication_date = forms.DateField()AddBook.html 页面
<body> <h1>Add Book</h1> <form action="." method="POST"> {% csrf_token %} <table> {{form.as_table}} </table> <input type="submit" value = "Submit" /> </form></body>
addBook函数:
def addBook(request): if request.method == 'POST': form = AddBookForm(request.POST) if form.is_valid(): title = form.cleaned_data['title'] #authors = form.cleaned_data['authors'] #print authors publisher = form.cleaned_data['publisher'] publication_date = form.cleaned_data['publication_date'] #print authors, " ", publisher," ",publication_date article = Article(title=title,publisher_id=publisher,publication_date=publication_date) article.save() authorsIds = request.POST.getlist('authors') for authorId in authorIds: author = Author.objects.get(id=authorId) aritcle.authors.add(author) return render_to_response('articles/templates/addArticleSuccess.html',{'title':title},context_instance=RequestContext(request)) else: form = AddBookForm() return render_to_response('articles/templates/addBook.html', {'form': form},context_instance=RequestContext(request))表单在页面显示没有问题,但是提交表单的时候就出错了,错误如下:
请大侠帮忙,改怎样处理这个问题。 展开
展开全部
class AddBookForm(forms.Form):
def __init__(self,*args,**kwargs):
...
self.fields['authors'].choices = [(author.id,author.first_name + " " + author.last_name) for author in Author.objects.all()]
self.fields['publisher'].choices = [('','-----------')] + [(publisher.id,publisher.name) for publisher in Publisher.objects.all()]
...
form里这两行有问题,这行如果你想重新赋值的话应该给一个queryset,而不是列表。如果你想测试一下的话可以先把这行注释掉,然后你在提交看看表单验证是否能通过。如果通过了那确定问题就是这里了。我想我应该不会错。。。
追问
其实我并不是想重新赋值,只是注掉的化我这块就报
错,我见好多是不初始化比如这样role =
forms.ModelMultipleChoiceField(
queryset=Role.objects.all(), widget=CustomCheckboxSelectMultiple() ),在__init__初始化的情况下,这块内容我具体改怎么写呢?
追答
def __init__(self,*args,**kwargs):
super(AddBookForm,self).__init__(*args,**kwargs)
self.fields['authors'].choices = [(author.id,author.first_name + " " + author.last_name) for author in Author.objects.all()]
self.fields['publisher'].choices = [('','-----------')] + [(publisher.id,publisher.name) for publisher in Publisher.objects.all()]
把这个方法都注释掉,不要初始化的方法,如果你不想要改变初始值的话。。。追问的话最好把错误代码也贴上。
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询