Django:如何使用Form数据设置ForeignKey

时间:2012-11-24 00:45:59

标签: python django

我似乎错过了一些东西。我正在尝试允许用户为他们的写作选择一种类型,然后将其设置为来自工作(写作)表/模型的类型表/模型的外键。

错误: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)

1 个答案:

答案 0 :(得分:0)

将您的表单“流派”字段更改为django documentation说:

genre = forms.ModelChoiceField(queryset=Genre.objects.filter(poem = False).order_by('name'))

并删除 init 方法。使用此行,您可以替换该字段的初始值并将该标签放入“one_shot”字段,您可以将其作为字段参数传递:

one_shot = forms.ChoiceField(
    choices = (
        ('one', 'Single Chapter'),
        ('multi', 'Multiple Chapters'),
    ),
    label = "Single Chapter or Multiple Chapters"
)