首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >为什么self.instance没有为绑定表单设置干净的函数?

为什么self.instance没有为绑定表单设置干净的函数?
EN

Stack Overflow用户
提问于 2010-10-26 16:55:36
回答 1查看 3.6K关注 0票数 1

我有一个Django 1.1模型,它的所有者和标题上都有unique_together,其中所有者是用户的外键。此约束是强制执行的,但只在清洁之后。根据姜戈博士,我应该能够访问self.instance来查看模型实例的非表单字段对象属性。

但是,我得到了错误

'JournalForm‘对象没有属性’实例‘

为什么没有在表单self.instance ()或字段clean_title()方法中设置这个绑定表单?

我的模特:

代码语言:javascript
运行
复制
class Journal (models.Model):
    owner = models.ForeignKey(User, null=True, related_name='journals')
    title = models.CharField(null=False, max_length=256)
    published = models.BooleanField(default=False)

    class Meta:
        unique_together = ("owner", "title")

    def __unicode__(self):
        return self.title

我的表格:

代码语言:javascript
运行
复制
class JournalForm (forms.Form):
    title = forms.CharField(max_length=256,
                                label=u'Title:')
    html_input = forms.CharField(widget=TinyMCE(attrs={'cols':'85', 'rows':'40'}, ), 
                            label=u'Journal Content:')
    published = forms.BooleanField(required=False)

    def clean(self):
        super(JournalForm, self).clean()
        instance = self.instance
        return self.cleaned_input

    def clean_title(self):
        title = self.cleaned_data['title']
        if self.is_bound:
            if models.Journal.objects.filter(owner.id=self.instance.owner.id, title=title).exclude(id=self.instance.id).count() > 0:
               raise forms.ValidationError(u'You already have a Journal with that title. Please change your title so it is unique.')
        else:
            if models.LabJournal.objects.filter(owner.id=self.instance.owner.id, title=title).count() > 0:
               raise forms.ValidationError(u'You already have a Journal with that title. Please change your title so it is unique.')
        return title

根据请求-视图代码:

代码语言:javascript
运行
复制
def journal (request):
    try:
        journal = models.Journal.objects.get(id=id)
        if request.method == 'GET':
            if request.user.is_active:
                if request.user.id == journal.owner.id:
                    data = {
                        'title' : journal.title,
                        'html_input' : _journal_fields_to_HTML(journal.id),
                        'published' : journal.published
                    }
                    form = forms.JournalForm(initial=data)
                    return shortcuts.render_to_response('journal/Journal.html', { 'form':form, })
                else:
                    return http.HttpResponseForbidden('<h1>Access denied</h1>')
            else:
                return _display_login_form(request)
        elif request.method == 'POST':
            if LOGIN_FORM_KEY in request.POST:
                return _handle_login(request)
            elif request.user.is_active and request.user.id == journal.owner.id:
                form = forms.JournalForm(data=request.POST)
                if form.is_valid():
                    journal.title = form.cleaned_data['title']
                    journal.published = form.cleaned_data['title'];
                    journal.save()
                    if _HTML_to_journal_fields(journal, form.cleaned_data['html_input']):
                        html_memo = "Save successful."
                    else:
                        html_memo = "Unable to save Journal."
                    return shortcuts.render_to_response('journal/Journal.html', { 'form':form, 'saved':html_memo})
                else:
                    return shortcuts.render_to_response('journal/Journal.html', { 'form':form })
        return http.HttpResponseNotAllowed(['GET', 'POST'])
    except models.Journal.DoesNotExist:
        return http.HttpResponseNotFound('<h1>Requested journal not found</h1>')
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2010-10-26 17:46:09

这里有几个问题。

首先,您没有使用ModelForm。您链接到的文档是针对这些的,而不是针对标准表单的。

其次,为了使表单具有一个实例属性,您需要在实例化表单时传递该实例。

如果确实使用ModelForm,则不需要将日志字段转换为表单字段的代码,保存时也不需要转换为表单字段的代码--表单可以为您完成此操作。您还可以删除检查唯一性的clean_title方法,因为模型上的unique_together约束已经定义了该方法,而ModelForm将为您强制执行该方法。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4025968

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档