django - 如何使用 Django 中的通用 View CreateView 自定义表单的 View

标签 django django-forms django-templates django-urls

我不太熟悉 Django 的表单

这是来自 models.py订单

class Order( models.Model ) :
    def __unicode__( self ) :
        return unicode( self.pk )

    def get_absolute_url( self ) :
        return reverse( 'orders_detail', args = [ self.pk ] )

    STATUS_CHOICES = (
        ( 'p', 'pending'  ),
        ( 'a', 'approved' ),
        ( 'r', 'rejected' ),
        ( 'c', 'closed'   ),
        ( 'l', 'locked'   ),
    )

    WORK_TYPE_CHOICES = (
        ( 'hc', 'Heating and cooling' ),
        ( 'el', 'Electrical'          ),
        ( 'pl', 'Plumbing'            ),
        ( 'ap', 'Appliances'          ),
        ( 'pe', 'Pests'               ),
        ( 'ex', 'Exterior'            ),
        ( 'in', 'Interior'            ),
        ( 'sa', 'Safety'              ),
        ( 'ot', 'Others'              ),
    )

    creator   = models.ForeignKey( User, related_name = 'creator' )
    approver  = models.ForeignKey( User, related_name = 'approver' )
    comments  = models.TextField( blank = True )
    status    = models.CharField( max_length = 1, choices = STATUS_CHOICES, default = 'p' )
    quote     = models.DecimalField( max_digits = 8, decimal_places = 2, null = True, blank = True )
    payment   = models.DecimalField( max_digits = 8, decimal_places = 2, null = True, blank = True )
    work_type = models.CharField( max_length = 2, choices = WORK_TYPE_CHOICES )
    vendor    = models.ForeignKey( Vendor, null = True, blank = True )
    created   = models.DateTimeField( auto_now_add = True )
    modified  = models.DateTimeField( auto_now = True )

class OrderCreateForm( ModelForm ) :
    class Meta :
        model = Order
        fields = (
            'creator',
            'approver',
            'comments',
            'work_type',
        )

到目前为止,我在 urls.py 中为 Order 模型使用通用 View CreateView

url(
    r'^orders/create/$',
    CreateView.as_view(
        model = Order,
        template_name = 'doors/orders/create.html',
        form_class = OrderCreateForm
    ),
    name = 'orders_create'
),

在我的模板中,我只是有

{% extends "base.html" %}

{% block title %}Create order{% endblock %}

{% block content %}
    {{ form }}
{% endblock %}

它会创建一个像这样的部分表单(没有提交按钮)

但是,我想根据 user.get_profile().user_type 控制 creatorapprover 字段的可见性。如果登录用户的 user_type 不是管理员,则 creator 会自动设置为用户,approver 也会自动设置。如果user_type经理,则该用户可以将这两个字段指定给不同的用户。

我还希望能够命名每个字段的实际标签。例如,将工作类型更改为类别

目前我认为执行此操作的唯一方法是在模板内执行 {% for field in form %} 并运行诸如 {% if field.名称==“创建者”%}。有没有比一堆受控循环和 if-then 语句更简单的方法?

最佳答案

I want to control the visibility of the creator and approver fields depending on user.get_profile().user_type. If the logged in user's user_type isn't a manager, then the creator is automatically set as user and approver will be set also set automatically. If the user_type is a manager, then that user can specify both fields to different users.

我会为用户制作另一个表单:

class UserOrderCreateForm( ModelForm ) :
    class Meta :
        model = Order
        fields = (
            'comments',
            'work_type',
        )

    def __init__(self, *args, **kwargs):
         self.user = kwargs.pop('user')
        super(UserOrderCreateForm, self).__init__(*args, **kwargs)

    def save(self):
        result = super(UserOrderCreateForm, self).save(commit=False)
        result.creator = self.user
        result.approver = self.user.some_other_field # "will be set also set automatically"
        result.save()
        return result

然后您可以决定在 View 中使用什么形式。像这样使用它

form = UserOrderCreateForm(user=request.user)

我认为您将需要花费一些时间才能使其与CreateView一起工作。这就是为什么我不喜欢CBV。 :-)

I also want to be able to name the actual labels of each fields. For example, change Work type to Category.

work_type = models.CharField( max_length = 2, choices = WORK_TYPE_CHOICES, verbose_name=u'Category')

关于django - 如何使用 Django 中的通用 View CreateView 自定义表单的 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9921340/

相关文章:

python - 如何根据url请求更改django listview中的模板名称?

Django navigator.sendbeacon csrf保护

Django:如何在外键模型字段上定义动态初始值

python - Django - 在结果页面的搜索框中显示查询

python - Django 模型表单集和命名 url

Django - 使用 request.GET 和 request.POST 之间的区别

python - 在 Django 模板中的元组列表的第一个元素中访问元组的第三项

python - 使用for循环打印值django模板

python - 在Django模板中动态访问request.GET

python - Django 教程 NoReverseMatch