0
我似乎錯過了一些東西。我試圖讓用戶爲他們的寫作選擇一種流派,然後將其設置爲來自Work(寫作)表/模型的流派表格/模型的外鍵。Django:如何使用表單數據設置ForeignKey
錯誤:Django AttributeError: 'str' object has no attribute '_default_manager'
這就是我現在要做的。
Form.py
class post_ow(forms.Form):
def __init__(self, *args, **kwargs):
super(post_ow, self).__init__(*args, **kwargs)
self.fields['one_shot'].label = "Single Chapter or Multiple Chapters"
c = []
genre = Genre.objects.filter(poem = False).order_by('name')
for b in genre:
c.append((b.id,b.name))
self.fields['genre'] = forms.ChoiceField(choices = c)
title = forms.CharField(error_messages = {'required' : 'Title Required'}, widget= forms.TextInput(attrs={'style':'width=600px'}))
summery = forms.CharField(widget = forms.Textarea(), error_messages= {'required' : 'Summery Required'})
genre = forms.ChoiceField(choices =())
one_shot = forms.ChoiceField(choices = (
('one', 'Single Chapter'),
('multi', 'Multiple Chapters'),
))
Model.py
class Genre(models.Model):
name = models.CharField(max_length=20)
poem = models.BooleanField()
ordernumber = models.IntegerField()
def __unicode__(self):
return self.name
class Work(models.Model):
title = models.CharField(max_length=30)
summery = models.TextField()
user = models.ForeignKey(User)
date_published = models.DateField()
date_updated = models.DateField()
one_shot = models.BooleanField()
completed = models.BooleanField()
genre = models.ForeignKey(Genre)
TYPES = (
('FF', 'Fan Fiction'),
('OF', 'Original Work'),
('PW', 'Poetry Work'),
)
types = models.CharField(max_length=2, choices=TYPES)
fandom = models.ForeignKey(Book, blank = True, null= True)
def __unicode__(self):
return self.title + '-' + self.user.email
線在view.py造成錯誤:
g = get_object_or_404('Genre', id = form.cleaned_data['genre'])
pw = Work(title = form.cleaned_data['title'], summery = form.cleaned_data['summery'], user = request.user, one_shot = True, types = 'pw',
date_published = current_date, date_updated = current_date, completed = True, genre = g)
兩個問題:你看到了什麼樣的錯誤?請與我們分享。爲什麼使用簡單的'Form'並避免使用'ModelForm'? – marianobianchi
@marianobianchi我使用一個簡單的'Form',因爲有一些需求(我已經添加了一些),這個表單需要能夠處理'ModelForm'不能做的事情。我現在會發布確切的錯誤。 –