Django database learn itself
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))
assuming your book model is this:
class Book(models.Model):
author = models.ForeignKey(Author)
#etc.
try something like this:
class BookForm(ModelForm):
other = forms.CharField(max_length=200, required=False)
def clean(self, *args, **kwargs):
other = self.cleaned_data.get('other')
author = self.cleaned_data.get('author')
if author is None or author == '':
self.cleaned_data['author'] = Author(name=other).save()
return self.cleaned_data
class Meta:
model = Book
If author would be a manytomanyfield:
class BookForm(ModelForm): other = forms.CharField(max_length=200, required=False)
def clean(self, *args, **kwargs):
other = self.cleaned_data.get('other')
author = self.cleaned_data.get('author')
if other is not None or other != '':
for newauthor in other.split(','): #separate new authors by comma.
self.cleaned_data['author'].append(Author(name=newauthor).save())
return self.cleaned_data
class Meta:
model = Book
精彩评论