2010-10-27 29 views
1

我有一个系统依赖于其他模型,但想让它更开放一点,因为我的用户有时需要更多一点。Django数据库自学

目前为了参数目的我有2 authorsAuthor模型。

john, james 

当用户添加了一本书,而Author没有,我怎么添加other场的形式,如果选中,然后产生一个额外的字段,用户可以输入的名称Author并且表单处理的方式使新作者在提交时被添加和选择?

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)) 

回答

1

假设你的书模型是这样的:

class Book(models.Model): 
    author = models.ForeignKey(Author) 
    #etc. 

尝试这样的事:

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 

如果作者将是一个manytomanyfield:

类BookForm(的ModelForm): 其他= 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 
+0

非常感谢你,我来看看,让你知道! – ApPeL 2010-10-27 14:11:38