I’m not very good with Django’s form.
Here is Order from 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',
)
So far I am using the generic view CreateView for a Order model in urls.py
url(
r'^orders/create/$',
CreateView.as_view(
model = Order,
template_name = 'doors/orders/create.html',
form_class = OrderCreateForm
),
name = 'orders_create'
),
In my template, I simply have
{% extends "base.html" %}
{% block title %}Create order{% endblock %}
{% block content %}
{{ form }}
{% endblock %}
and it create a partial form (with no submit button) like this

However, 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.
I also want to be able to name the actual labels of each fields. For example, change Work type to Category.
Currently I’m thinking the only way to do this is to do {% for field in form %} inside the template and run a bunch of lines like {% if field.name == "creator" %}. Is there an easier way than a bunch of controlled loops and if-then statements?
I’d make another form for just user:
Then you can decide what form to use in view. Use it like
I think you will have to spend some time to make it work with
CreateView. That’s why I don’t like CBV. 🙂