Django可选择显示表单字段

时间:2016-05-24 15:01:19

标签: django-forms

我'创建评论系统,我希望为注册用户和匿名用户提供不同的表单呈现。这是一个想法:
对于匿名用户:

Name:|     |
E-mail:|     |
Text:
 ________________
|                |
|                |
|________________|

对于注册用户

Text:
 ________________
|                |
|                |
|________________|

这是我的代码:
models.py

class Comment(models.Model):
    """
    Class for comments
    """
    post = models.ForeignKey(Post, related_name='comments')
    title = models.CharField(max_length=40)
    author = models.ForeignKey(User, blank=True, null=True)
    body = models.TextField()
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    active = models.BooleanField(default=True)

    class Meta:
        ordering = ('created',)

forms.py

class CommentForm(forms.ModelForm):
    """
    Form for adding comments
    """
    class Meta:
        model = Comment
        fields = ('title', 'email', 'body')

这里最好的方法是什么?

我虽然将电子邮件和名称都设为空白= True和null = True并在自定义保存方法中填充它们。添加视图if user.is_authenticated并相应地显示字段,但我不知道它是否正常。你能推荐我最佳实践吗?

1 个答案:

答案 0 :(得分:0)

想出了这个解决方案:
在forms.py

    def __init__(self, *args, **kwargs):
        """
        Differend fields for auth and non-auth user
        """
        user = kwargs.pop('user', None)
        super(CommentForm, self).__init__(*args, **kwargs)
        # if user and user.is_authenticated():
        del self.fields['name']
        del self.fields['email']
在views.py中

....
    if request.method == 'POST':
    comment_form = CommentForm(request.POST)
    if comment_form.is_valid():
        new_comment = comment_form.save(commit=False)
        new_comment.post = post
        if user.is_authenticated():
            new_comment.author = User.objects.get(username=user.username)
            new_comment.email = User.objects.get(email=user.email)
        new_comment.save()
....