2👍
First of all, I recommend you use only form.cleaned_data
to get submited data.
id = form.cleaned_data['hidden_field']
Also, why you reassign id
from request.POST data when you already have id
defined in your function args? Maybe it should look like:
msg_response_id = form.cleaned_data['hidden_field']
Then, you always need to check hidden_field
value and you can do it with your custom clean method. Add clean_hidden_field
method to your form and also you should override init form method and pass id
and msg_response_id
.
In your views:
form = ReplyForm(initial=initial, id=id, msg_response_id=msg_response_id)
And forms:
class ReplyForm(forms.Form):
def __init__(self, *args, **kwargs):
self.id = kwargs.pop('id', None)
self.msg_response_id = kwargs.pop('msg_response_id', None)
super(ReplyForm, self).__init__(*args, **kwargs)
hidden_field = forms.CharField(widget=forms.HiddenInput())
def clean_hidden_field(self):
if self.id and self.msg_response_id and self.id == self.msg_response_id:
# Raise form error, which will appear in your template.
raise forms.ValidationError(_('You can't reply to your own message.'))
1👍
The last paragraph describing what you want is not all too clear, but I believe what you are trying to do, is make an raise an exception when a certain requirement is not met in your form.
If that is the case, then simply catching an ValidationError
which is inbuilt into django will do the trick.
So, something like this:
try:
form = ReplyForm(request.POST)
except ValidationError:
# do what you want here
Alternatively,
form = ReplyForm(request.POST)
if form.is_valid():
# do stuff
else:
raise ValidationError
If this does not work for you, then you might try validation the post-data without using django-forms, but usually django takes care of this problem for you, and it will automatically generate the error messages. You can take a deeper look @ form validation here.
However if you want even more fine grain control you can make the form yourself, and handle the validation within your views. Otherwise, ValidationError
should do the trick and let you redirect the error messages.
- [Django]-Loop through a defaultdict(list) structure in a django template
- [Django]-Display link on template when user is a staff member in Django
- [Django]-I'm trying to build site navigation using django-mptt
- [Django]-Django view with cross-domain Ajax
- [Django]-Django with google charts