Django如何选择ModelForm的一个字段

时间:2014-02-19 23:46:57

标签: django django-forms

我有一个带有两个TextAreas的ModelForm,因此,在视图中,我想决定使用哪一个(在我定义两个ModelForms之前,每个字段一个,但是它有很多重复的代码。

这是ModelForm:

class f_post_comment(ModelForm):
class Meta:
    model = Post
    fields = ['commentCreator', 'commentReceiver']
    widgets = {
        'commentCreator': forms.Textarea(
            attrs={
                'class': 'form-control',
                'placeholder': 'Write your comment for your post'
            }
        ),
        'commentReceiver': forms.Textarea(
            attrs={
                'class': 'form-control',
                'placeholder': 'Write your comment for the post you\'ve received'
            }
        ),
    }

以下是我在视图中使用的方式:

@login_required
def commentpost(request, id_post):
    try:
        favor = Favor.objects.get(id=id_favor)
    except Favor.DoesNotExist:
        messages.add_message(request, messages.ERROR, "Post doesn't exists")
        return redirect('home')

    option= None
    if request.user == post.Creator:
        option = 'commentCreator'
    elif request.user == post.Receiver:
        option = 'commentReceiver'
    formBasic = modelform_factory(Post, form=f_post_comment, fields=(option,))
    if option is not None:
        if request.method == 'POST':
            form = formBasic(request.POST)
            if form.is_valid:
                form.save()
                messages.add_message(request, messages.INFO, "Thanks for the comment.")
            else:
                messages.add_message(request, messages.ERROR,
                                      "Can't make an empty comment.")
        else:
            form = formBasic
            return render(request, 'posts/commentpost.html', {'post': post, 'form': form})
    else:
        messages.add_message(request, messages.ERROR,
                             "You are neither the Creator nor the Receiver of this post")
    return redirect('home')

有什么想法吗?

模板怎么样?

非常感谢。

1 个答案:

答案 0 :(得分:0)

一种更简单的方法可能是为Post创建具有通用功能的基础ModelForm类,然后为创建者和接收者创建2个子类。

从modelform继承时,您也可以从父Meta继承Meta对象 - 请参阅https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#form-inheritance