I have this model:
class Server(models.Model):
user = models.ForeignKey('auth.User',related_name="servers")
is_shared = models.BooleanField(default=True, editable=False)
name = models.CharField(max_length=255, default='testserver')
hostname = models.CharField(max_length=255, default='localhost')
username = models.CharField(max_length=255, default='user')
password = models.CharField(max_length=255, default='pass')
path = models.CharField(max_length=255, default='/')
mkdir = models.BooleanField(default=False)
port = models.IntegerField(max_length=4, default=21)
quirky = models.BooleanField(default=False)
class Meta:
unique_together = ('user', 'name',)
def __unicode__(self):
return self.name
class Meta:
verbose_name_plural = "Server"
And I'm creating a model form from that:
class ServerForm(ModelForm):
delete = forms.BooleanField(required=False)
def __init__(self, *args, **kwargs):
super(ServerForm, self).__init__(*args,**kwargs)
if (self.instance.pk is None):
self.fields['name'] = forms.CharField(max_length=255, required=True)
del self.fields['delete']
class Meta:
model = Server
exclude = ["user","name"]
The point is that a user may not change the name field of an existing server object, but if there is no instance to the form I want the user to specify a name. In other words: The user is supposed to supply a name, but don't change it later.
When I use this code the name ends up at the bottom, but it should be on top. In earlier django version an insert could do the trick, but that doesn't work anymore since going to django 1.7.
Then I read here: How can I order fields in Django ModelForm?
... to use the fields value in the meta class. But now I have the problem that the field list should sometimes include "name" and other times not. Depending on whether there is an instance. But from the Meta class I cannot use self.instance to check. Also it seems a bit annoying to list all fields again just to change there order.
How can I change the order of my model form fields?
EDIT: I'd love to keep looping in the template. Also It would be nice to have the correct order in admin as well as any templates. Templates are more important though.