Django数据库自学
我有一个依赖其他模型的系统,但希望使其更加开放,因为我的用户有时需要更多一点。
目前,为了论证,我在一个 Author
模型中有 2 位作者
。
john, james
当用户添加一本书,并且 Author
不可用时,如何在表单中添加 other
字段,如果选择该字段,则会生成一个额外的字段,其中用户可以输入作者的姓名,并且表单处理的方式是在提交时添加并选择新作者?
MODELS.PY
class Author(models.Model):
name = models.CharField(max_length=30)
FORMS.PY
class AuthorForm(ModelForm):
class Meta:
model = Author
VIEWS.PY
def new(request, template_name='authors/new.html'):
if request.method == 'POST':
form = AuthorForm(request.POST, request.FILES)
if form.is_valid():
newform = form.save(commit=False)
newform.user = request.user
newform.save()
return HttpResponseRedirect('/')
else:
form = AuthorForm()
context = { 'form':form, }
return render_to_response(template_name, context,
context_instance=RequestContext(request))
I have a system that relies on other models but want to make it a little more open-ended as my users demand a bit more sometimes.
currently for arguments sake I have 2 authors
in an Author
model.
john, james
When a user adds a book, and the Author
is not available, how do I add a other
field in the form, that if selected, then generates an extra field where the user can enter the name of the Author
and the form handling is in such a way that the new Author gets added and selected on submission?
MODELS.PY
class Author(models.Model):
name = models.CharField(max_length=30)
FORMS.PY
class AuthorForm(ModelForm):
class Meta:
model = Author
VIEWS.PY
def new(request, template_name='authors/new.html'):
if request.method == 'POST':
form = AuthorForm(request.POST, request.FILES)
if form.is_valid():
newform = form.save(commit=False)
newform.user = request.user
newform.save()
return HttpResponseRedirect('/')
else:
form = AuthorForm()
context = { 'form':form, }
return render_to_response(template_name, context,
context_instance=RequestContext(request))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
假设您的书籍模型是这样的:
尝试这样的事情:
如果作者是一个manytomanyfield:
class BookForm(ModelForm):
其他 = forms.CharField(max_length=200, required=False)
assuming your book model is this:
try something like this:
If author would be a manytomanyfield:
class BookForm(ModelForm):
other = forms.CharField(max_length=200, required=False)