Имеются две сущности: Server и Server_page. Обе содержат поля name, которые должны быть уникальны.
Форма из модели Server_page работает как надо.
Модель:
class Server_page(models.Model):
server = models.ForeignKey(Server)
name = models.CharField(max_length=16, validators=[RegexValidator(regex='[a-z0-9_]+', message=_('You can use only lower case letters of the English alphabet, digits and a sign "_".'))])
title = models.CharField(max_length=64)
content = models.CharField(max_length=4096)
sort_number = models.IntegerField(default=0)
class ServerPageCreationForm(forms.ModelForm):
captcha = CaptchaField()
class Meta:
model = Server_page
fields = ['name', 'title', 'content', 'sort_number']
widgets = {
'content': forms.Textarea
}
def clean_name(self):
data = self.cleaned_data['name']
try:
another_server_page = Server_page.objects.get(name=data)
except:
another_server_page = None
if another_server_page == None or another_server_page.id == self.instance.id:
return data
else:
raise forms.ValidationError(_('Server page with same name is exist already.'))
class ServerPageEditingForm(ServerPageCreationForm):
def __init__(self, *args, **kwargs):
super(ServerPageEditingForm, self).__init__(*args, **kwargs)
del self.fields['captcha']
Аналогичный подход с Server не работает. Модель:
class Server(models.Model):
game = models.ForeignKey(Game)
user = models.ForeignKey(User)
name = models.CharField(unique = True, max_length=16, validators=[RegexValidator(regex='[a-z0-9_]+', message=_('You can use only lower case letters of the English alphabet, digits and a sign "_".'))])
title = models.CharField(max_length=64)
password = models.CharField(max_length=64)
public_state = models.IntegerField(default=0)
creating_timestamp = models.DateTimeField(auto_now_add=True)
updating_timestamp = models.DateTimeField(auto_now_add=True)
ip_address = models.GenericIPAddressField(verbose_name='Ip address')
port = models.IntegerField(validators=[MinValueValidator(1), MaxValueValidator(65535)])
class ServerCreationForm(forms.ModelForm):
captcha = CaptchaField()
class Meta:
model = Server
fields = ['game', 'name', 'title', 'password', 'ip_address', 'port']
def clean_name(self):
data = self.cleaned_data['name']
try:
another_server = Server.objects.get(name=data)
except:
another_server = None
if another_server == None or another_server.id == self.instance.id:
return data
else:
raise forms.ValidationError(_('Server with same name is exist already.'))
class ServerEditingForm(ServerCreationForm):
def __init__(self, *args, **kwargs):
super(ServerEditingForm, self).__init__(*args, **kwargs)
del self.fields['game']
del self.fields['captcha']
ServerEditingForm(instance=server)
Перемещено true_admin из development