Using model method in form validation
I have a ModelForm
and I want to use my Model method for form validation process, I have tried form.save(commit=False)
but it return a None
object.
The period model have two attributes which are start and end time fields.
models.py
class Booking(models.Model):
CATEGORY_CHOICES = (
('Web', 'Web Application'),
('Emb', 'Embedded Application')
)
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='bookings')
room = models.ForeignKey(Room, on_delete=models.CASCADE, related_name='bookings')
category = models.CharField(max_length=50, choices=CATEGORY_CHOICES, default='Web')
date = models.DateField('Booking Date', db_index=True)
start = models.ForeignKey(Period, on_delete=models.SET_NULL, related_name='start_at', null=True)
end = models.ForeignKey(Period, on_delete=models.SET_NULL, related_name='end_at', null=True)
used = models.BooleanField(default=False)
objects = BookingManager()
class Meta:
ordering = ['-date']
def get_start_time(self):
return datetime.datetime.combine(self.date, self.start.start,
tzinfo=timezone.get_current_timezone())
def get_end_time(self):
return datetime.datetime.combine(self.date, self.end.end,
tzinfo=timezone.get_current_timezone())
def is_occurring(self):
now = timezone.localtime(timezone.now())
return (now >= self.get_start_time()) and (now <= self.get_end_time())
def extend_booking_time(self):
next_end = self.end.next_period()
if next_end is None:
raise ValidationError("Invalid extending period")
if not next_end.is_available(self.date, next_end):
raise ValidationError("Overlapped extension")
else:
self.end = next_end
self.save()
def check_in(self):
# Create record
'''
Log.objects.create(user=self.user.username,
room=self.room, booking= self.id)
'''
self.used = True
self.save()
def check_out(self, time):
# Record Log
#log = Log.objects.get(booking=self.id)
#log.check_out = time
#log.save()
self.delete()
def check_periods(self):
return self.start.start < self.end.end
def check_time(self):
now = timezone.localtime(timezone.now())
if now >= self.get_end_time():
return False
else:
return True
def check_overlap(self):
start = self.get_start_time()
end = self.get_end_time()
bookings = Booking.objects.filter(room=self.room, date=self.date)
for booking in bookings:
if (start < booking.get_end_time()) and (end > booking.get_start_time()):
return False
return True
def clean(self):
if not self.check_periods():
raise ValidationError('Period error!')
if not self.check_time():
raise ValidationError('Time error!')
if not self.check_overlap():
raise ValidationError('Overlap error!')
forms.py
class BookingForm(forms.ModelForm):
class Meta:
model = Booking
fields= ['room', 'date', 'start', 'end']
def __init__(self, *args, **kwargs):
initial_args = kwargs.get('initial', None)
if initial_args:
super(BookingForm, self).__init__(*args, **kwargs)
self.fields['start'].widget = forms.TextInput()
self.fields['date'].widget.attrs['readonly'] = True
self.fields['start'].widget.attrs['readonly'] = True
self.fields['room'].queryset = Room.objects.filter(
id=initial_args['room'].id
)
self.fields['end'].queryset = Period.objects.get_available_periods(
initial_args['room'],
initial_args['date'],
initial_args['start']
)
def clean_date(self):
now = timezone.localtime(timezone.now()).date()
date = self.cleaned_data['date']
if date < now:
raise ValidationError('Ngay dang ky khong hop le')
return date
def clean(self):
pass
views.py
class BookingCreateView(LoginRequiredMixin, CreateView):
login_url = 'login'
form_class = BookingForm
template_name = 'booking_add.html'
success_url = reverse_lazy('booking_list')
def get(self, request, *args, **kwargs):
room = self.request.GET.get('room', None)
date = self.request.GET.get('date', None)
start = self.request.GET.get('start', None)
if room is None or date is None or start is None:
return redirect('select')
else:
room_object = get_object_or_404(Room, id=room)
period = get_object_or_404(Period, number=start)
date = datetime.datetime.strptime(
date, '%d-%m-%Y'
).replace(tzinfo=timezone.get_current_timezone())
if period.is_expired(date) or not period.is_available(room, date):
return redirect(room_object.get_absolute_url())
return super(BookingCreateView, self).get(request, *args, **kwargs)
def get_initial(self):
initial = super(BookingCreateView, self).get_initial()
initial['date'] = datetime.datetime.strptime(
self.request.GET.get('date'), '%d-%m-%Y'
)
initial['room'] = get_object_or_404(
Room, id=self.request.GET.get('room')
)
initial['start'] = get_object_or_404(
Period, number=self.request.GET.get('start')
)
return initial
def form_valid(self, form):
form.instance.user = self.request.user
return super().form_valid(form)
template.
<main>
<div class="reg-form">
<form class="form" method="post" action="">
% csrf_token %
<label for="room">Phòng</label>
form.room
<label for="date">Ngày</label>
form.date
<label for="start">Ca bắt đầu</label>
form.start
<label for="end">Ca kết thúc</label>
form.end
<button type="submit">Đăng ký</button>
<p> form.errors </p>
</form>
</div>
</main>
I want to use the method check_overlap
in BookingForm
validation process, what is the best way to do that?
django django-models django-forms
add a comment |
I have a ModelForm
and I want to use my Model method for form validation process, I have tried form.save(commit=False)
but it return a None
object.
The period model have two attributes which are start and end time fields.
models.py
class Booking(models.Model):
CATEGORY_CHOICES = (
('Web', 'Web Application'),
('Emb', 'Embedded Application')
)
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='bookings')
room = models.ForeignKey(Room, on_delete=models.CASCADE, related_name='bookings')
category = models.CharField(max_length=50, choices=CATEGORY_CHOICES, default='Web')
date = models.DateField('Booking Date', db_index=True)
start = models.ForeignKey(Period, on_delete=models.SET_NULL, related_name='start_at', null=True)
end = models.ForeignKey(Period, on_delete=models.SET_NULL, related_name='end_at', null=True)
used = models.BooleanField(default=False)
objects = BookingManager()
class Meta:
ordering = ['-date']
def get_start_time(self):
return datetime.datetime.combine(self.date, self.start.start,
tzinfo=timezone.get_current_timezone())
def get_end_time(self):
return datetime.datetime.combine(self.date, self.end.end,
tzinfo=timezone.get_current_timezone())
def is_occurring(self):
now = timezone.localtime(timezone.now())
return (now >= self.get_start_time()) and (now <= self.get_end_time())
def extend_booking_time(self):
next_end = self.end.next_period()
if next_end is None:
raise ValidationError("Invalid extending period")
if not next_end.is_available(self.date, next_end):
raise ValidationError("Overlapped extension")
else:
self.end = next_end
self.save()
def check_in(self):
# Create record
'''
Log.objects.create(user=self.user.username,
room=self.room, booking= self.id)
'''
self.used = True
self.save()
def check_out(self, time):
# Record Log
#log = Log.objects.get(booking=self.id)
#log.check_out = time
#log.save()
self.delete()
def check_periods(self):
return self.start.start < self.end.end
def check_time(self):
now = timezone.localtime(timezone.now())
if now >= self.get_end_time():
return False
else:
return True
def check_overlap(self):
start = self.get_start_time()
end = self.get_end_time()
bookings = Booking.objects.filter(room=self.room, date=self.date)
for booking in bookings:
if (start < booking.get_end_time()) and (end > booking.get_start_time()):
return False
return True
def clean(self):
if not self.check_periods():
raise ValidationError('Period error!')
if not self.check_time():
raise ValidationError('Time error!')
if not self.check_overlap():
raise ValidationError('Overlap error!')
forms.py
class BookingForm(forms.ModelForm):
class Meta:
model = Booking
fields= ['room', 'date', 'start', 'end']
def __init__(self, *args, **kwargs):
initial_args = kwargs.get('initial', None)
if initial_args:
super(BookingForm, self).__init__(*args, **kwargs)
self.fields['start'].widget = forms.TextInput()
self.fields['date'].widget.attrs['readonly'] = True
self.fields['start'].widget.attrs['readonly'] = True
self.fields['room'].queryset = Room.objects.filter(
id=initial_args['room'].id
)
self.fields['end'].queryset = Period.objects.get_available_periods(
initial_args['room'],
initial_args['date'],
initial_args['start']
)
def clean_date(self):
now = timezone.localtime(timezone.now()).date()
date = self.cleaned_data['date']
if date < now:
raise ValidationError('Ngay dang ky khong hop le')
return date
def clean(self):
pass
views.py
class BookingCreateView(LoginRequiredMixin, CreateView):
login_url = 'login'
form_class = BookingForm
template_name = 'booking_add.html'
success_url = reverse_lazy('booking_list')
def get(self, request, *args, **kwargs):
room = self.request.GET.get('room', None)
date = self.request.GET.get('date', None)
start = self.request.GET.get('start', None)
if room is None or date is None or start is None:
return redirect('select')
else:
room_object = get_object_or_404(Room, id=room)
period = get_object_or_404(Period, number=start)
date = datetime.datetime.strptime(
date, '%d-%m-%Y'
).replace(tzinfo=timezone.get_current_timezone())
if period.is_expired(date) or not period.is_available(room, date):
return redirect(room_object.get_absolute_url())
return super(BookingCreateView, self).get(request, *args, **kwargs)
def get_initial(self):
initial = super(BookingCreateView, self).get_initial()
initial['date'] = datetime.datetime.strptime(
self.request.GET.get('date'), '%d-%m-%Y'
)
initial['room'] = get_object_or_404(
Room, id=self.request.GET.get('room')
)
initial['start'] = get_object_or_404(
Period, number=self.request.GET.get('start')
)
return initial
def form_valid(self, form):
form.instance.user = self.request.user
return super().form_valid(form)
template.
<main>
<div class="reg-form">
<form class="form" method="post" action="">
% csrf_token %
<label for="room">Phòng</label>
form.room
<label for="date">Ngày</label>
form.date
<label for="start">Ca bắt đầu</label>
form.start
<label for="end">Ca kết thúc</label>
form.end
<button type="submit">Đăng ký</button>
<p> form.errors </p>
</form>
</div>
</main>
I want to use the method check_overlap
in BookingForm
validation process, what is the best way to do that?
django django-models django-forms
add a comment |
I have a ModelForm
and I want to use my Model method for form validation process, I have tried form.save(commit=False)
but it return a None
object.
The period model have two attributes which are start and end time fields.
models.py
class Booking(models.Model):
CATEGORY_CHOICES = (
('Web', 'Web Application'),
('Emb', 'Embedded Application')
)
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='bookings')
room = models.ForeignKey(Room, on_delete=models.CASCADE, related_name='bookings')
category = models.CharField(max_length=50, choices=CATEGORY_CHOICES, default='Web')
date = models.DateField('Booking Date', db_index=True)
start = models.ForeignKey(Period, on_delete=models.SET_NULL, related_name='start_at', null=True)
end = models.ForeignKey(Period, on_delete=models.SET_NULL, related_name='end_at', null=True)
used = models.BooleanField(default=False)
objects = BookingManager()
class Meta:
ordering = ['-date']
def get_start_time(self):
return datetime.datetime.combine(self.date, self.start.start,
tzinfo=timezone.get_current_timezone())
def get_end_time(self):
return datetime.datetime.combine(self.date, self.end.end,
tzinfo=timezone.get_current_timezone())
def is_occurring(self):
now = timezone.localtime(timezone.now())
return (now >= self.get_start_time()) and (now <= self.get_end_time())
def extend_booking_time(self):
next_end = self.end.next_period()
if next_end is None:
raise ValidationError("Invalid extending period")
if not next_end.is_available(self.date, next_end):
raise ValidationError("Overlapped extension")
else:
self.end = next_end
self.save()
def check_in(self):
# Create record
'''
Log.objects.create(user=self.user.username,
room=self.room, booking= self.id)
'''
self.used = True
self.save()
def check_out(self, time):
# Record Log
#log = Log.objects.get(booking=self.id)
#log.check_out = time
#log.save()
self.delete()
def check_periods(self):
return self.start.start < self.end.end
def check_time(self):
now = timezone.localtime(timezone.now())
if now >= self.get_end_time():
return False
else:
return True
def check_overlap(self):
start = self.get_start_time()
end = self.get_end_time()
bookings = Booking.objects.filter(room=self.room, date=self.date)
for booking in bookings:
if (start < booking.get_end_time()) and (end > booking.get_start_time()):
return False
return True
def clean(self):
if not self.check_periods():
raise ValidationError('Period error!')
if not self.check_time():
raise ValidationError('Time error!')
if not self.check_overlap():
raise ValidationError('Overlap error!')
forms.py
class BookingForm(forms.ModelForm):
class Meta:
model = Booking
fields= ['room', 'date', 'start', 'end']
def __init__(self, *args, **kwargs):
initial_args = kwargs.get('initial', None)
if initial_args:
super(BookingForm, self).__init__(*args, **kwargs)
self.fields['start'].widget = forms.TextInput()
self.fields['date'].widget.attrs['readonly'] = True
self.fields['start'].widget.attrs['readonly'] = True
self.fields['room'].queryset = Room.objects.filter(
id=initial_args['room'].id
)
self.fields['end'].queryset = Period.objects.get_available_periods(
initial_args['room'],
initial_args['date'],
initial_args['start']
)
def clean_date(self):
now = timezone.localtime(timezone.now()).date()
date = self.cleaned_data['date']
if date < now:
raise ValidationError('Ngay dang ky khong hop le')
return date
def clean(self):
pass
views.py
class BookingCreateView(LoginRequiredMixin, CreateView):
login_url = 'login'
form_class = BookingForm
template_name = 'booking_add.html'
success_url = reverse_lazy('booking_list')
def get(self, request, *args, **kwargs):
room = self.request.GET.get('room', None)
date = self.request.GET.get('date', None)
start = self.request.GET.get('start', None)
if room is None or date is None or start is None:
return redirect('select')
else:
room_object = get_object_or_404(Room, id=room)
period = get_object_or_404(Period, number=start)
date = datetime.datetime.strptime(
date, '%d-%m-%Y'
).replace(tzinfo=timezone.get_current_timezone())
if period.is_expired(date) or not period.is_available(room, date):
return redirect(room_object.get_absolute_url())
return super(BookingCreateView, self).get(request, *args, **kwargs)
def get_initial(self):
initial = super(BookingCreateView, self).get_initial()
initial['date'] = datetime.datetime.strptime(
self.request.GET.get('date'), '%d-%m-%Y'
)
initial['room'] = get_object_or_404(
Room, id=self.request.GET.get('room')
)
initial['start'] = get_object_or_404(
Period, number=self.request.GET.get('start')
)
return initial
def form_valid(self, form):
form.instance.user = self.request.user
return super().form_valid(form)
template.
<main>
<div class="reg-form">
<form class="form" method="post" action="">
% csrf_token %
<label for="room">Phòng</label>
form.room
<label for="date">Ngày</label>
form.date
<label for="start">Ca bắt đầu</label>
form.start
<label for="end">Ca kết thúc</label>
form.end
<button type="submit">Đăng ký</button>
<p> form.errors </p>
</form>
</div>
</main>
I want to use the method check_overlap
in BookingForm
validation process, what is the best way to do that?
django django-models django-forms
I have a ModelForm
and I want to use my Model method for form validation process, I have tried form.save(commit=False)
but it return a None
object.
The period model have two attributes which are start and end time fields.
models.py
class Booking(models.Model):
CATEGORY_CHOICES = (
('Web', 'Web Application'),
('Emb', 'Embedded Application')
)
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='bookings')
room = models.ForeignKey(Room, on_delete=models.CASCADE, related_name='bookings')
category = models.CharField(max_length=50, choices=CATEGORY_CHOICES, default='Web')
date = models.DateField('Booking Date', db_index=True)
start = models.ForeignKey(Period, on_delete=models.SET_NULL, related_name='start_at', null=True)
end = models.ForeignKey(Period, on_delete=models.SET_NULL, related_name='end_at', null=True)
used = models.BooleanField(default=False)
objects = BookingManager()
class Meta:
ordering = ['-date']
def get_start_time(self):
return datetime.datetime.combine(self.date, self.start.start,
tzinfo=timezone.get_current_timezone())
def get_end_time(self):
return datetime.datetime.combine(self.date, self.end.end,
tzinfo=timezone.get_current_timezone())
def is_occurring(self):
now = timezone.localtime(timezone.now())
return (now >= self.get_start_time()) and (now <= self.get_end_time())
def extend_booking_time(self):
next_end = self.end.next_period()
if next_end is None:
raise ValidationError("Invalid extending period")
if not next_end.is_available(self.date, next_end):
raise ValidationError("Overlapped extension")
else:
self.end = next_end
self.save()
def check_in(self):
# Create record
'''
Log.objects.create(user=self.user.username,
room=self.room, booking= self.id)
'''
self.used = True
self.save()
def check_out(self, time):
# Record Log
#log = Log.objects.get(booking=self.id)
#log.check_out = time
#log.save()
self.delete()
def check_periods(self):
return self.start.start < self.end.end
def check_time(self):
now = timezone.localtime(timezone.now())
if now >= self.get_end_time():
return False
else:
return True
def check_overlap(self):
start = self.get_start_time()
end = self.get_end_time()
bookings = Booking.objects.filter(room=self.room, date=self.date)
for booking in bookings:
if (start < booking.get_end_time()) and (end > booking.get_start_time()):
return False
return True
def clean(self):
if not self.check_periods():
raise ValidationError('Period error!')
if not self.check_time():
raise ValidationError('Time error!')
if not self.check_overlap():
raise ValidationError('Overlap error!')
forms.py
class BookingForm(forms.ModelForm):
class Meta:
model = Booking
fields= ['room', 'date', 'start', 'end']
def __init__(self, *args, **kwargs):
initial_args = kwargs.get('initial', None)
if initial_args:
super(BookingForm, self).__init__(*args, **kwargs)
self.fields['start'].widget = forms.TextInput()
self.fields['date'].widget.attrs['readonly'] = True
self.fields['start'].widget.attrs['readonly'] = True
self.fields['room'].queryset = Room.objects.filter(
id=initial_args['room'].id
)
self.fields['end'].queryset = Period.objects.get_available_periods(
initial_args['room'],
initial_args['date'],
initial_args['start']
)
def clean_date(self):
now = timezone.localtime(timezone.now()).date()
date = self.cleaned_data['date']
if date < now:
raise ValidationError('Ngay dang ky khong hop le')
return date
def clean(self):
pass
views.py
class BookingCreateView(LoginRequiredMixin, CreateView):
login_url = 'login'
form_class = BookingForm
template_name = 'booking_add.html'
success_url = reverse_lazy('booking_list')
def get(self, request, *args, **kwargs):
room = self.request.GET.get('room', None)
date = self.request.GET.get('date', None)
start = self.request.GET.get('start', None)
if room is None or date is None or start is None:
return redirect('select')
else:
room_object = get_object_or_404(Room, id=room)
period = get_object_or_404(Period, number=start)
date = datetime.datetime.strptime(
date, '%d-%m-%Y'
).replace(tzinfo=timezone.get_current_timezone())
if period.is_expired(date) or not period.is_available(room, date):
return redirect(room_object.get_absolute_url())
return super(BookingCreateView, self).get(request, *args, **kwargs)
def get_initial(self):
initial = super(BookingCreateView, self).get_initial()
initial['date'] = datetime.datetime.strptime(
self.request.GET.get('date'), '%d-%m-%Y'
)
initial['room'] = get_object_or_404(
Room, id=self.request.GET.get('room')
)
initial['start'] = get_object_or_404(
Period, number=self.request.GET.get('start')
)
return initial
def form_valid(self, form):
form.instance.user = self.request.user
return super().form_valid(form)
template.
<main>
<div class="reg-form">
<form class="form" method="post" action="">
% csrf_token %
<label for="room">Phòng</label>
form.room
<label for="date">Ngày</label>
form.date
<label for="start">Ca bắt đầu</label>
form.start
<label for="end">Ca kết thúc</label>
form.end
<button type="submit">Đăng ký</button>
<p> form.errors </p>
</form>
</div>
</main>
I want to use the method check_overlap
in BookingForm
validation process, what is the best way to do that?
django django-models django-forms
django django-models django-forms
edited Nov 11 at 6:06
asked Nov 10 at 1:27
Q.Nguyen
366
366
add a comment |
add a comment |
1 Answer
1
active
oldest
votes
The best way is pretty subjective but here's a way that isn't too involved.
In your model, call the method in clean
. A ModelForm will call your model's clean method during the validation process (before you finish save).
Here are the relevant source portions:
https://github.com/django/django/blob/master/django/forms/models.py#L381
https://github.com/django/django/blob/master/django/forms/models.py#L381
Here's the model validation documentation: https://docs.djangoproject.com/en/dev/ref/models/instances/#validating-objects
Overriding clean
on the form breaks the method resolution order so your model's clean won't get called the way this is written.
Hope this helps!
I got your idea. But how can I display Validation Error from model clean method into the form template?
– Q.Nguyen
Nov 10 at 6:57
You need to call the field and form errors explicitly in the the template. docs.djangoproject.com/en/dev/topics/forms/…
– theWanderer4865
Nov 10 at 14:07
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53235245%2fusing-model-method-in-form-validation%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
The best way is pretty subjective but here's a way that isn't too involved.
In your model, call the method in clean
. A ModelForm will call your model's clean method during the validation process (before you finish save).
Here are the relevant source portions:
https://github.com/django/django/blob/master/django/forms/models.py#L381
https://github.com/django/django/blob/master/django/forms/models.py#L381
Here's the model validation documentation: https://docs.djangoproject.com/en/dev/ref/models/instances/#validating-objects
Overriding clean
on the form breaks the method resolution order so your model's clean won't get called the way this is written.
Hope this helps!
I got your idea. But how can I display Validation Error from model clean method into the form template?
– Q.Nguyen
Nov 10 at 6:57
You need to call the field and form errors explicitly in the the template. docs.djangoproject.com/en/dev/topics/forms/…
– theWanderer4865
Nov 10 at 14:07
add a comment |
The best way is pretty subjective but here's a way that isn't too involved.
In your model, call the method in clean
. A ModelForm will call your model's clean method during the validation process (before you finish save).
Here are the relevant source portions:
https://github.com/django/django/blob/master/django/forms/models.py#L381
https://github.com/django/django/blob/master/django/forms/models.py#L381
Here's the model validation documentation: https://docs.djangoproject.com/en/dev/ref/models/instances/#validating-objects
Overriding clean
on the form breaks the method resolution order so your model's clean won't get called the way this is written.
Hope this helps!
I got your idea. But how can I display Validation Error from model clean method into the form template?
– Q.Nguyen
Nov 10 at 6:57
You need to call the field and form errors explicitly in the the template. docs.djangoproject.com/en/dev/topics/forms/…
– theWanderer4865
Nov 10 at 14:07
add a comment |
The best way is pretty subjective but here's a way that isn't too involved.
In your model, call the method in clean
. A ModelForm will call your model's clean method during the validation process (before you finish save).
Here are the relevant source portions:
https://github.com/django/django/blob/master/django/forms/models.py#L381
https://github.com/django/django/blob/master/django/forms/models.py#L381
Here's the model validation documentation: https://docs.djangoproject.com/en/dev/ref/models/instances/#validating-objects
Overriding clean
on the form breaks the method resolution order so your model's clean won't get called the way this is written.
Hope this helps!
The best way is pretty subjective but here's a way that isn't too involved.
In your model, call the method in clean
. A ModelForm will call your model's clean method during the validation process (before you finish save).
Here are the relevant source portions:
https://github.com/django/django/blob/master/django/forms/models.py#L381
https://github.com/django/django/blob/master/django/forms/models.py#L381
Here's the model validation documentation: https://docs.djangoproject.com/en/dev/ref/models/instances/#validating-objects
Overriding clean
on the form breaks the method resolution order so your model's clean won't get called the way this is written.
Hope this helps!
answered Nov 10 at 6:34
theWanderer4865
7211020
7211020
I got your idea. But how can I display Validation Error from model clean method into the form template?
– Q.Nguyen
Nov 10 at 6:57
You need to call the field and form errors explicitly in the the template. docs.djangoproject.com/en/dev/topics/forms/…
– theWanderer4865
Nov 10 at 14:07
add a comment |
I got your idea. But how can I display Validation Error from model clean method into the form template?
– Q.Nguyen
Nov 10 at 6:57
You need to call the field and form errors explicitly in the the template. docs.djangoproject.com/en/dev/topics/forms/…
– theWanderer4865
Nov 10 at 14:07
I got your idea. But how can I display Validation Error from model clean method into the form template?
– Q.Nguyen
Nov 10 at 6:57
I got your idea. But how can I display Validation Error from model clean method into the form template?
– Q.Nguyen
Nov 10 at 6:57
You need to call the field and form errors explicitly in the the template. docs.djangoproject.com/en/dev/topics/forms/…
– theWanderer4865
Nov 10 at 14:07
You need to call the field and form errors explicitly in the the template. docs.djangoproject.com/en/dev/topics/forms/…
– theWanderer4865
Nov 10 at 14:07
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53235245%2fusing-model-method-in-form-validation%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown