2010-10-27 40 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