Pergunta

I have a date time field called bk_time. Now, I would like to write custom validation for bk_time based on different users.

For example, I have users Staff_A, Staff_B and Superuser:

  1. Staff_A can only set the time = Mon-Fri 9am-12am
  2. Staff_B can only set the time = Monday only
  3. Superuser no limitation

I have referred Django Doc Validators. But it seems not working for multiple validation

I have tried to write save_formsetDjango Doc Admin.But it seems not able to raise ValidationError

models.py

class Location(models.Model):
    name = models.CharField('Location', max_length=100)

class Room(models.Model):
    room_label = models.CharField('Room Lebel', max_length=100)
    bk_time= models.DateTimeField('Booking Time')

admin.py

class RoomInline(admin.StackedInline):
    model = Room
    extra = 0

class LocationAdmin(admin.ModelAdmin):
    list_display = ['id', 'name']
    fields = ('name')
    inlines = [RoomInline]

If this is relevant, I'm using Django 1.4.

Foi útil?

Solução

I think this has to come on the form validation, and not on the field validation. This is because your validation depends on two independent fields.

In particular, this is very similar to an authentication: your validation depends on the user and on another field. Take a look how Django implements its authentication (from django.contrib.auth):

class AuthenticationForm(forms.Form):
    [...]
    def clean(self):
        username = self.cleaned_data.get('username')
        password = self.cleaned_data.get('password')

        if username and password:
            self.user_cache = authenticate(username=username,
                                           password=password)
            if self.user_cache is None:
                raise forms.ValidationError(
                    self.error_messages['invalid_login'],
                    code='invalid_login',
                    params={'username': self.username_field.verbose_name},
                )
            elif not self.user_cache.is_active:
                raise forms.ValidationError(
                    self.error_messages['inactive'],
                    code='inactive',
                )
        return self.cleaned_data

In your case, you want to raise a ValidationError on a given constraint, and return cleaned_data otherwise.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top