您好我需要您的帮助我需要在必填字段为空时禁用此按钮发送。我是一个使用django的初学者,我不知道如何解决它。我需要你的帮助..我没有时间试图找到解决方案。
Views.py:
def contact(request):
form = FeedbackForm(request.POST or None)
if form.is_valid():
recaptcha_response = request.POST.get('g-recaptcha-response')
url = 'https://www.google.com/recaptcha/api/siteverify'
values = {
'secret': settings.GOOGLE_RECAPTCHA_SECRET_KEY,
'response': recaptcha_response
}
data = urllib.urlencode(values).encode()
req = urllib2.Request(url, data=data)
response = urllib2.urlopen(req)
result = json.loads(response.read().decode())
''' End reCAPTCHA validation '''
if result['success']:
form.save()
message = u'You have feedback\nName: %s\nEmail: %s\nPhone: %s\nCountry: %s\nFeedback:\n%s' % (
form.cleaned_data['name'],
form.cleaned_data['email'],
form.cleaned_data['phone'],
form.cleaned_data['country'],
form.cleaned_data['feedback'])
try:
send_mail('NEW FEEDBACK', message, '', settings.DEFAULT_FROM_EMAIL) # to admin
send_mail('THANK YOU for contacting us', 'We will be back to you promptly.', '', [form.cleaned_data['email'],]) # to user
messages.info(request, 'SUCCESS! Your message has been sent!')
form = FeedbackForm()
except:
messages.info(request, 'Sorry, can\'t send feedback right now.')
else:
messages.error(request, 'Invalid reCAPTCHA. Please try again.')
return render(request, 'contact.html', {'active_page':'contact','form': form,})
Contact.html:
<html>
<div class="col-md-6">
<form role="form" class="form" method="post">
{% csrf_token %}
{% for field in form %}
<label for="{{ field.label }}">{{ field.label_tag }}
{% if field.field.required %}<span class="red">*</span>{% endif %}</label>{{ field.errors }}{{ field }}
{% endfor %}
<p><span class="redText">*</span> Indicates a required field</p>
<script src='https://www.google.com/recaptcha/api.js'></script>
<div class="g-recaptcha" data-sitekey=""></div>
<input type="submit" value="Send" class="btn btn-lg">
</form>
答案 0 :(得分:1)
执行此操作的最佳方法是使用JavaScript和jQuery。 在此示例中,当您单击按钮时,可以确保表单在提交之前有效。
$(".validate").on("click", function () {
if (!valid()) {
alert("You are missing required fields.");
return false;
}
else {
return confirm("This will submit the form. Are you sure?");
}
});
function valid() {
return false;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="submit" class="validate" value="Send" class="btn btn-lg">
此代码为您的按钮添加了一个类。 jQuery侦听单击,然后创建一个JavaScript函数来检查它是否有效。如果不是,则显示警报。如果是,则显示确认消息。 有很多其他的方法可以用JS做到这一点。